content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Normalising book titles - Python I have a list of books titles: "The Hobbit: 70th Anniversary Edition" "The Hobbit" "The Hobbit (Illustrated/Collector Edition)[There and Back Again]" "The Hobbit: or, There and Back Again" "The Hobbit: Gift Pack" and so on... I thought that if I normalised the titles somehow, it would be easier to implement an automated way to know what book each edition is referring to. normalised = ''.join([char for char in title if char in (string.ascii_letters + string.digits)]) or normalised = '' for char in title: if char in ':/()|': break normalised += char return normalised But obviously they are not working as intended, as titles can contain special characters and editions can basically have very different title layouts. Help would be very much appreciated! Thanks :) A: It depends completely on your data. For the examples you gave, a simple normalization solution could be: import re book_normalized = re.sub(r':.*|\[.*?\]|\(.*?\)|\{.*?\}', '', book_name).strip() This will return "The Hobbit" for all the examples. What it does is remove anything after and including the first colon, or anything in brackets (normal, square, curly) as well as leading and trailing spaces. However, this is not a very good solution in the general case, as some books have colons or bracketed parts in the actual book name. E.g. the name of the series, followed by a colon, followed by the name of the particular entry of the series. A: I would suggest using a 3rd party web service, such as librarything which I believe can do what you're asking, for a starting point, see their documentation: http://www.librarything.com/services/rest/documentation/1.0/librarything.ck.getwork.php
Normalising book titles - Python
I have a list of books titles: "The Hobbit: 70th Anniversary Edition" "The Hobbit" "The Hobbit (Illustrated/Collector Edition)[There and Back Again]" "The Hobbit: or, There and Back Again" "The Hobbit: Gift Pack" and so on... I thought that if I normalised the titles somehow, it would be easier to implement an automated way to know what book each edition is referring to. normalised = ''.join([char for char in title if char in (string.ascii_letters + string.digits)]) or normalised = '' for char in title: if char in ':/()|': break normalised += char return normalised But obviously they are not working as intended, as titles can contain special characters and editions can basically have very different title layouts. Help would be very much appreciated! Thanks :)
[ "It depends completely on your data. For the examples you gave, a simple normalization solution could be:\nimport re\n\nbook_normalized = re.sub(r':.*|\\[.*?\\]|\\(.*?\\)|\\{.*?\\}', '', book_name).strip()\n\nThis will return \"The Hobbit\" for all the examples. What it does is remove anything after and including the first colon, or anything in brackets (normal, square, curly) as well as leading and trailing spaces.\nHowever, this is not a very good solution in the general case, as some books have colons or bracketed parts in the actual book name. E.g. the name of the series, followed by a colon, followed by the name of the particular entry of the series.\n", "I would suggest using a 3rd party web service, such as librarything which I believe can do what you're asking, for a starting point, see their documentation:\nhttp://www.librarything.com/services/rest/documentation/1.0/librarything.ck.getwork.php\n" ]
[ 1, 1 ]
[]
[]
[ "data_cleaning", "django", "python", "string" ]
stackoverflow_0002458720_data_cleaning_django_python_string.txt
Q: Are Python properties broken? How can it be that this test case import unittest class PropTest(unittest.TestCase): def test(self): class C(): val = 'initial val' def get_p(self): return self.val def set_p(self, prop): if prop == 'legal val': self.val = prop prop=property(fget=get_p, fset=set_p) c=C() self.assertEqual('initial val', c.prop) c.prop='legal val' self.assertEqual('legal val', c.prop) c.prop='illegal val' self.assertNotEqual('illegal val', c.prop) fails as below? Failure Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 279, in run testMethod() File "/Users/jacob/aau/admissions_proj/admissions/plain_old_unit_tests.py", line 24, in test self.assertNotEqual('illegal val', c.prop) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 358, in failIfEqual (msg or '%r == %r' % (first, second)) AssertionError: 'illegal val' == 'illegal val' A: Your class C does not inherit from object or any other new-style class, so it is an old-style class (and therefore does not support properties). Descriptors are for new-style classes only. To fix, change class C() to class C(object). http://www.python.org/download/releases/2.2.3/descrintro/ provides some details, if you are interested. New-style classes are better in several ways.
Are Python properties broken?
How can it be that this test case import unittest class PropTest(unittest.TestCase): def test(self): class C(): val = 'initial val' def get_p(self): return self.val def set_p(self, prop): if prop == 'legal val': self.val = prop prop=property(fget=get_p, fset=set_p) c=C() self.assertEqual('initial val', c.prop) c.prop='legal val' self.assertEqual('legal val', c.prop) c.prop='illegal val' self.assertNotEqual('illegal val', c.prop) fails as below? Failure Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 279, in run testMethod() File "/Users/jacob/aau/admissions_proj/admissions/plain_old_unit_tests.py", line 24, in test self.assertNotEqual('illegal val', c.prop) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 358, in failIfEqual (msg or '%r == %r' % (first, second)) AssertionError: 'illegal val' == 'illegal val'
[ "Your class C does not inherit from object or any other new-style class, so it is an old-style class (and therefore does not support properties). Descriptors are for new-style classes only. To fix, change class C() to class C(object).\nhttp://www.python.org/download/releases/2.2.3/descrintro/ provides some details, if you are interested. New-style classes are better in several ways.\n" ]
[ 13 ]
[]
[]
[ "properties", "python" ]
stackoverflow_0002459715_properties_python.txt
Q: UTF-8 HTML and CSS files with BOM (and how to remove the BOM with Python) First, some background: I'm developing a web application using Python. All of my (text) files are currently stored in UTF-8 with the BOM. This includes all my HTML templates and CSS files. These resources are stored as binary data (BOM and all) in my DB. When I retrieve the templates from the DB, I decode them using template.decode('utf-8'). When the HTML arrives in the browser, the BOM is present at the beginning of the HTTP response body. This generates a very interesting error in Chrome: Extra <html> encountered. Migrating attributes back to the original <html> element and ignoring the tag. Chrome seems to generate an <html> tag automatically when it sees the BOM and mistakes it for content, making the real <html> tag an error. So, using Python, what is the best way to remove the BOM from my UTF-8 encoded templates (if it exists -- I can't guarantee this in the future)? For other text-based files like CSS, will major browsers correctly interpret (or ignore) the BOM? They are being sent as plain binary data without .decode('utf-8'). Note: I am using Python 2.5. Thanks! A: Since you state: All of my (text) files are currently stored in UTF-8 with the BOM then use the 'utf-8-sig' codec to decode them: >>> s = u'Hello, world!'.encode('utf-8-sig') >>> s '\xef\xbb\xbfHello, world!' >>> s.decode('utf-8-sig') u'Hello, world!' It automatically removes the expected BOM, and works correctly if the BOM is not present as well. A: Check the first character after decoding to see if it's the BOM: if u.startswith(u'\ufeff'): u = u[1:] A: The previously-accepted answer is WRONG. u'\ufffe' is not a character. If you get it in a unicode string somebody has stuffed up mightily. The BOM (aka ZERO WIDTH NO-BREAK SPACE) is u'\ufeff' >>> UNICODE_BOM = u'\N{ZERO WIDTH NO-BREAK SPACE}' >>> UNICODE_BOM u'\ufeff' >>> Read this (Ctrl-F search for BOM) and this and this (Ctrl-F search for BOM). Here's a correct and typo/braino-resistant answer: Decode your input into unicode_str. Then do this: # If I mistype the following, it's very likely to cause a SyntaxError. UNICODE_BOM = u'\N{ZERO WIDTH NO-BREAK SPACE}' if unicode_str and unicode_str[0] == UNICODE_BOM: unicode_str = unicode_str[1:] Bonus: using a named constant gives your readers a bit more of a clue to what is going on than does a collection of seemingly-arbitrary hexoglyphics. Update Unfortunately there seems to be no suitable named constant in the standard Python library. Alas, the codecs module provides only "a snare and a delusion": >>> import pprint, codecs >>> pprint.pprint([(k, getattr(codecs, k)) for k in dir(codecs) if k.startswith('BOM')]) [('BOM', '\xff\xfe'), #### aarrgghh!! #### ('BOM32_BE', '\xfe\xff'), ('BOM32_LE', '\xff\xfe'), ('BOM64_BE', '\x00\x00\xfe\xff'), ('BOM64_LE', '\xff\xfe\x00\x00'), ('BOM_BE', '\xfe\xff'), ('BOM_LE', '\xff\xfe'), ('BOM_UTF16', '\xff\xfe'), ('BOM_UTF16_BE', '\xfe\xff'), ('BOM_UTF16_LE', '\xff\xfe'), ('BOM_UTF32', '\xff\xfe\x00\x00'), ('BOM_UTF32_BE', '\x00\x00\xfe\xff'), ('BOM_UTF32_LE', '\xff\xfe\x00\x00'), ('BOM_UTF8', '\xef\xbb\xbf')] >>> Update 2 If you have not yet decoded your input, and wish to check it for a BOM, you need to check for TWO different BOMs for UTF-16 and at least TWO different BOMs for UTF-32. If there was only one way each, then you wouldn't need a BOM, would you? Here verbatim unprettified from my own code is my solution to this: def check_for_bom(s): bom_info = ( ('\xFF\xFE\x00\x00', 4, 'UTF-32LE'), ('\x00\x00\xFE\xFF', 4, 'UTF-32BE'), ('\xEF\xBB\xBF', 3, 'UTF-8'), ('\xFF\xFE', 2, 'UTF-16LE'), ('\xFE\xFF', 2, 'UTF-16BE'), ) for sig, siglen, enc in bom_info: if s.startswith(sig): return enc, siglen return None, 0 The input s should be at least the first 4 bytes of your input. It returns the encoding that can be used to decode the post-BOM part of your input, plus the length of the BOM (if any). If you are paranoid, you could allow for another 2 (non-standard) UTF-32 orderings, but Python doesn't supply an encoding for them and I've never heard of an actual occurrence, so I don't bother. A: You can use something similar to remove BOM: import os, codecs def remove_bom_from_file(filename, newfilename): if os.path.isfile(filename): # open file f = open(filename,'rb') # read first 4 bytes header = f.read(4) # check if we have BOM... bom_len = 0 encodings = [ ( codecs.BOM_UTF32, 4 ), ( codecs.BOM_UTF16, 2 ), ( codecs.BOM_UTF8, 3 ) ] # ... and remove appropriate number of bytes for h, l in encodings: if header.startswith(h): bom_len = l break f.seek(0) f.read(bom_len) # copy the rest of file contents = f.read() nf = open(newfilename) nf.write(contents) nf.close()
UTF-8 HTML and CSS files with BOM (and how to remove the BOM with Python)
First, some background: I'm developing a web application using Python. All of my (text) files are currently stored in UTF-8 with the BOM. This includes all my HTML templates and CSS files. These resources are stored as binary data (BOM and all) in my DB. When I retrieve the templates from the DB, I decode them using template.decode('utf-8'). When the HTML arrives in the browser, the BOM is present at the beginning of the HTTP response body. This generates a very interesting error in Chrome: Extra <html> encountered. Migrating attributes back to the original <html> element and ignoring the tag. Chrome seems to generate an <html> tag automatically when it sees the BOM and mistakes it for content, making the real <html> tag an error. So, using Python, what is the best way to remove the BOM from my UTF-8 encoded templates (if it exists -- I can't guarantee this in the future)? For other text-based files like CSS, will major browsers correctly interpret (or ignore) the BOM? They are being sent as plain binary data without .decode('utf-8'). Note: I am using Python 2.5. Thanks!
[ "Since you state:\n\nAll of my (text) files are currently\n stored in UTF-8 with the BOM\n\nthen use the 'utf-8-sig' codec to decode them:\n>>> s = u'Hello, world!'.encode('utf-8-sig')\n>>> s\n'\\xef\\xbb\\xbfHello, world!'\n>>> s.decode('utf-8-sig')\nu'Hello, world!'\n\nIt automatically removes the expected BOM, and works correctly if the BOM is not present as well.\n", "Check the first character after decoding to see if it's the BOM:\nif u.startswith(u'\\ufeff'):\n u = u[1:]\n\n", "The previously-accepted answer is WRONG.\nu'\\ufffe' is not a character. If you get it in a unicode string somebody has stuffed up mightily.\nThe BOM (aka ZERO WIDTH NO-BREAK SPACE) is u'\\ufeff'\n>>> UNICODE_BOM = u'\\N{ZERO WIDTH NO-BREAK SPACE}'\n>>> UNICODE_BOM\nu'\\ufeff'\n>>>\n\nRead this (Ctrl-F search for BOM) and this and this (Ctrl-F search for BOM).\nHere's a correct and typo/braino-resistant answer:\nDecode your input into unicode_str. Then do this:\n# If I mistype the following, it's very likely to cause a SyntaxError.\nUNICODE_BOM = u'\\N{ZERO WIDTH NO-BREAK SPACE}'\nif unicode_str and unicode_str[0] == UNICODE_BOM:\n unicode_str = unicode_str[1:]\n\nBonus: using a named constant gives your readers a bit more of a clue to what is going on than does a collection of seemingly-arbitrary hexoglyphics.\nUpdate Unfortunately there seems to be no suitable named constant in the standard Python library.\nAlas, the codecs module provides only \"a snare and a delusion\":\n>>> import pprint, codecs\n>>> pprint.pprint([(k, getattr(codecs, k)) for k in dir(codecs) if k.startswith('BOM')])\n[('BOM', '\\xff\\xfe'), #### aarrgghh!! ####\n ('BOM32_BE', '\\xfe\\xff'),\n ('BOM32_LE', '\\xff\\xfe'),\n ('BOM64_BE', '\\x00\\x00\\xfe\\xff'),\n ('BOM64_LE', '\\xff\\xfe\\x00\\x00'),\n ('BOM_BE', '\\xfe\\xff'),\n ('BOM_LE', '\\xff\\xfe'),\n ('BOM_UTF16', '\\xff\\xfe'),\n ('BOM_UTF16_BE', '\\xfe\\xff'),\n ('BOM_UTF16_LE', '\\xff\\xfe'),\n ('BOM_UTF32', '\\xff\\xfe\\x00\\x00'),\n ('BOM_UTF32_BE', '\\x00\\x00\\xfe\\xff'),\n ('BOM_UTF32_LE', '\\xff\\xfe\\x00\\x00'),\n ('BOM_UTF8', '\\xef\\xbb\\xbf')]\n>>>\n\nUpdate 2 If you have not yet decoded your input, and wish to check it for a BOM, you need to check for TWO different BOMs for UTF-16 and at least TWO different BOMs for UTF-32. If there was only one way each, then you wouldn't need a BOM, would you?\nHere verbatim unprettified from my own code is my solution to this:\ndef check_for_bom(s):\n bom_info = (\n ('\\xFF\\xFE\\x00\\x00', 4, 'UTF-32LE'),\n ('\\x00\\x00\\xFE\\xFF', 4, 'UTF-32BE'),\n ('\\xEF\\xBB\\xBF', 3, 'UTF-8'),\n ('\\xFF\\xFE', 2, 'UTF-16LE'),\n ('\\xFE\\xFF', 2, 'UTF-16BE'),\n )\n for sig, siglen, enc in bom_info:\n if s.startswith(sig):\n return enc, siglen\n return None, 0\n\nThe input s should be at least the first 4 bytes of your input. It returns the encoding that can be used to decode the post-BOM part of your input, plus the length of the BOM (if any).\nIf you are paranoid, you could allow for another 2 (non-standard) UTF-32 orderings, but Python doesn't supply an encoding for them and I've never heard of an actual occurrence, so I don't bother.\n", "You can use something similar to remove BOM:\nimport os, codecs\ndef remove_bom_from_file(filename, newfilename):\n if os.path.isfile(filename):\n # open file\n f = open(filename,'rb')\n\n # read first 4 bytes\n header = f.read(4)\n\n # check if we have BOM...\n bom_len = 0\n encodings = [ ( codecs.BOM_UTF32, 4 ),\n ( codecs.BOM_UTF16, 2 ),\n ( codecs.BOM_UTF8, 3 ) ]\n\n # ... and remove appropriate number of bytes \n for h, l in encodings:\n if header.startswith(h):\n bom_len = l\n break\n f.seek(0)\n f.read(bom_len)\n\n # copy the rest of file\n contents = f.read() \n nf = open(newfilename)\n nf.write(contents)\n nf.close()\n\n" ]
[ 24, 10, 1, 0 ]
[]
[]
[ "byte_order_mark", "file", "python", "utf_8" ]
stackoverflow_0002456380_byte_order_mark_file_python_utf_8.txt
Q: Troubleshooting 'ValueError: time data ... does not match format' when using datetime.strptime My input string is '16-MAR-2010 03:37:04' and i want to store it as datetime. I am trying to use: db_inst.HB_Create_Ship_Date = datetime.strptime(fields[7]," %d-%b-%Y %H:%M:%S ") fields[7] = '16-MAR-2010 03:37:04' I am getting an error: ::ValueError: time data '16-MAR-2010 03:37:04' does not match format ' %d-%b-%Y %H:%M:%S ' A: Edit: As John mentions, make it easier on yourself and remove the leading and trailing spaces. Another thought: Your current locale may not specify "MAR" as a month abbreviation. What does the output of this code give?: import locale locale.getdefaultlocale() I tested your code on a Linux machine (Ubuntu 9.10, Python 2.6.4) and got the ValueError. I removed the spaces, changed to non-English locale (Czech), and got the ValueError. Academic note: Oddly your code works on Windows XP Python 2.5.5 with the extraneous spaces: >>> from datetime import datetime >>> dt = '16-MAR-2010 03:37:04' >>> datetime.strptime(dt, " %d-%b-%Y %H:%M:%S ") datetime.datetime(2010, 3, 16, 3, 37, 4) A: Lose the spaces at the front and back of your format. I thought that strptime was documented to vary depending on the whims of whoever wrote the C runtime for your box. However it seems I'm wrong. Which would mean that there's a bug in Python. Python 2.6.4 on Windows doesn't like leading trailing spaces; see below. *x users, what do you find? In the meantime, use the lowest common denominator -- lose the spaces. You may also have a locale problem, as Adam mentioned. With spaces: >>> datetime.datetime.strptime('16-MAR-2010 03:37:04'," %d-%b-%Y %H:%M:%S ") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\python26\lib\_strptime.py", line 325, in _strptime (data_string, format)) ValueError: time data '16-MAR-2010 03:37:04' does not match format ' %d-%b-%Y %H :%M:%S ' Without spaces: >>> datetime.datetime.strptime('16-MAR-2010 03:37:04',"%d-%b-%Y %H:%M:%S") datetime.datetime(2010, 3, 16, 3, 37, 4) >>> A: Your format string has a leading space and a trailing space, but your input string does not. Remove the space after the starting quotation mark and before the ending quotation mark. A: Try this: db_inst.HB_Create_Ship_Date = datetime.strptime(fields[7],"%d-%b-%Y %H:%M:%S") Also, have a look here as a reference for DateTime formatting in Python.
Troubleshooting 'ValueError: time data ... does not match format' when using datetime.strptime
My input string is '16-MAR-2010 03:37:04' and i want to store it as datetime. I am trying to use: db_inst.HB_Create_Ship_Date = datetime.strptime(fields[7]," %d-%b-%Y %H:%M:%S ") fields[7] = '16-MAR-2010 03:37:04' I am getting an error: ::ValueError: time data '16-MAR-2010 03:37:04' does not match format ' %d-%b-%Y %H:%M:%S '
[ "Edit:\nAs John mentions, make it easier on yourself and remove the leading and trailing spaces.\nAnother thought:\nYour current locale may not specify \"MAR\" as a month abbreviation.\nWhat does the output of this code give?:\nimport locale\nlocale.getdefaultlocale()\n\nI tested your code on a Linux machine (Ubuntu 9.10, Python 2.6.4) and got the ValueError.\nI removed the spaces, changed to non-English locale (Czech), and got the ValueError.\nAcademic note:\nOddly your code works on Windows XP Python 2.5.5 with the extraneous spaces:\n>>> from datetime import datetime\n>>> dt = '16-MAR-2010 03:37:04'\n>>> datetime.strptime(dt, \" %d-%b-%Y %H:%M:%S \")\ndatetime.datetime(2010, 3, 16, 3, 37, 4)\n\n", "Lose the spaces at the front and back of your format. I thought that strptime was documented to vary depending on the whims of whoever wrote the C runtime for your box. However it seems I'm wrong. Which would mean that there's a bug in Python.\nPython 2.6.4 on Windows doesn't like leading trailing spaces; see below.\n*x users, what do you find?\nIn the meantime, use the lowest common denominator -- lose the spaces. You may also have a locale problem, as Adam mentioned.\nWith spaces:\n>>> datetime.datetime.strptime('16-MAR-2010 03:37:04',\" %d-%b-%Y %H:%M:%S \")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"C:\\python26\\lib\\_strptime.py\", line 325, in _strptime\n (data_string, format))\nValueError: time data '16-MAR-2010 03:37:04' does not match format ' %d-%b-%Y %H\n:%M:%S '\n\nWithout spaces:\n>>> datetime.datetime.strptime('16-MAR-2010 03:37:04',\"%d-%b-%Y %H:%M:%S\")\ndatetime.datetime(2010, 3, 16, 3, 37, 4)\n>>>\n\n", "Your format string has a leading space and a trailing space, but your input string does not. Remove the space after the starting quotation mark and before the ending quotation mark.\n", "Try this:\ndb_inst.HB_Create_Ship_Date = datetime.strptime(fields[7],\"%d-%b-%Y %H:%M:%S\")\n\nAlso, have a look here as a reference for DateTime formatting in Python.\n" ]
[ 4, 2, 2, 0 ]
[]
[]
[ "python", "strptime" ]
stackoverflow_0002460233_python_strptime.txt
Q: In Python, if I have a unix timestamp, how do I insert that into a MySQL datetime field? I am using Python MySQLDB, and I want to insert this into DATETIME field in Mysql . How do I do that with cursor.execute? A: To convert from a UNIX timestamp to a Python datetime object, use datetime.fromtimestamp() (documentation). >>> from datetime import datetime >>> datetime.fromtimestamp(0) datetime.datetime(1970, 1, 1, 1, 0) >>> datetime.fromtimestamp(1268816500) datetime.datetime(2010, 3, 17, 10, 1, 40) From Python datetime to UNIX timestamp: >>> import time >>> time.mktime(datetime(2010, 3, 17, 10, 1, 40).timetuple()) 1268816500.0 A: You can use the FROM_UNIXTIME MySQL function: #import MySQLdb as mysql import mysql.connector as mysql if __name__ == '__main__': cnx = mysql.connect(user='root') cur = cnx.cursor() cur.execute("SELECT FROM_UNIXTIME(%s)", (1268811665,)) print cur.fetchall() cur.close() cnx.close() The output (if you save the above to epoch.py): $ python epoch.py [(datetime.datetime(2010, 3, 17, 8, 41, 5),)] You can use the FROM_UNIXTIME in your INSERT or other DML SQL statements. A: Solved. I just did this: datetime.datetime.now() ...insert that into the column.
In Python, if I have a unix timestamp, how do I insert that into a MySQL datetime field?
I am using Python MySQLDB, and I want to insert this into DATETIME field in Mysql . How do I do that with cursor.execute?
[ "To convert from a UNIX timestamp to a Python datetime object, use datetime.fromtimestamp() (documentation).\n>>> from datetime import datetime\n>>> datetime.fromtimestamp(0)\ndatetime.datetime(1970, 1, 1, 1, 0)\n>>> datetime.fromtimestamp(1268816500)\ndatetime.datetime(2010, 3, 17, 10, 1, 40)\n\nFrom Python datetime to UNIX timestamp:\n>>> import time\n>>> time.mktime(datetime(2010, 3, 17, 10, 1, 40).timetuple())\n1268816500.0\n\n", "You can use the FROM_UNIXTIME MySQL function:\n#import MySQLdb as mysql\nimport mysql.connector as mysql\n\nif __name__ == '__main__':\n cnx = mysql.connect(user='root')\n cur = cnx.cursor()\n\n cur.execute(\"SELECT FROM_UNIXTIME(%s)\", (1268811665,))\n print cur.fetchall()\n cur.close()\n cnx.close()\n\nThe output (if you save the above to epoch.py):\n$ python epoch.py \n[(datetime.datetime(2010, 3, 17, 8, 41, 5),)]\n\nYou can use the FROM_UNIXTIME in your INSERT or other DML SQL statements.\n", "Solved.\nI just did this:\ndatetime.datetime.now() ...insert that into the column.\n" ]
[ 8, 3, 1 ]
[]
[]
[ "database", "date", "datetime", "mysql", "python" ]
stackoverflow_0002460491_database_date_datetime_mysql_python.txt
Q: Whats the best way to duplicate data in a django template? <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <h1>{% block title %}{% endblock %}</h1> </body> </html> This is my template, more or less. The h1 heading is always the same as the title tag. The above snippet of code is not valid because there can't be two blocks with the same name. How do I handle this without repeating myself? edit to clarify: I have a ton of child templates which are inherited from this one template, and so making a new {{title}} variable for each template is not a very good solution. Previously I had it set up like this: base.html: <title>{% block title %}{% endblock %}</title> then in base_view.html (extending base.html): <h1>{% block title %}{% endblock %}</h1> then in base_object.html (extending base_view.html): {% block title %}my title goes here{% endblock %} and it just worked somehow. I refactored my templates so theres just base.html, and base_object.html How can I get this functionality back? A: In base.html: <head> <title>{% block title %}{% endblock %}</title> </head> <body> <h1>{% block h1 %}{% endblock %}</h1> </body> Then, make another "base" layer on top of that called content_base.html (or something): {% extends "base.html" %} {% block h1 %}{% block title %}{% endblock %}{% endblock %} Now have all your other templates extend content_base.html. Whatever you put in block "title" in all your templates will go into both "title" and "h1" blocks in base.html. A: {% extends "base.html" %} {% with "Entry Title" as title %} {% block title %}{{ title }}{% endblock %} {% block h1 %}{{ title }}{% endblock %} {% endwith %} That could work if you're really worried about keeping title out of the views and not repeating yourself. A: It looks like your layout is solid. You have a base.html template that defines the basic structure and outer layout for each page in your app. You also have base_object.html that extends this template. You'd like each page to have a unique title and a matching h1 (I think). This best way to do this is to define two separate blocks in your base.html template. <html> <head> <title>{% block title %}Default Title{% endblock %}</title> </head> <body> <h1>{% block h1 %}{% endblock %}</h1> </body> </html> In your child templates, you need to override both of these if you'd like them to be identical. I know you feel this is counter-intuitive, but it is necessary due to the way template inheritance is handled in Django. Source: The Django template language Finally, note that you can't define multiple {% block %} tags with the same name in the same template. This limitation exists because a block tag works in "both" directions. That is, a block tag doesn't just provide a hole to fill -- it also defines the content that fills the hole in the parent. If there were two similarly-named {% block %} tags in a template, that template's parent wouldn't know which one of the blocks' content to use. The children look like this: {% extends "base.html" %} {% block title %}Title{% endblock %} {% block h1 %}Title{% endblock %} If this bothers you, you should set the title from the view for each object as a template variable. {% block title %}{{ title }}{% endblock %} {% block h1 %}{{ title }}{% endblock %} Django strives to keep as much logic out of the template layer as possible. Often a title is determined dynamically from the database, so the view layer is the perfect place to retrieve and set this information. You can still leave the title blank if you'd like to defer to the default title (perhaps set in base.html, or you can grab the name of the site from the django.contrib.sites package) Also {{ block.super }} may come in handy. This will allow you to combine the contents of the parent block with additional contents from the child. So you could define a title like "Stackoverflow.com" in the base, and set {% block title %}{{ block.super }} - Ask a Question{% endblock %} in the child to get a title like "Stackoverflow.com - Ask a Question" A: Pass a variable to your template, maybe called title. Then replace your title block with {{ title }}. To pass this into your template in your view make sure you have: def myview(request): t = loader.get_template("mypage.html") title = "My Title" c = Context({"title" : title }) HttpResponse(t.render(c)) Then in your template you will have: <html> <head> <title>{{ title }}</title> </head> <body> <h1>{{ title }}}</h1> </body> See also: How to repeat a "block" in a django template
Whats the best way to duplicate data in a django template?
<html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <h1>{% block title %}{% endblock %}</h1> </body> </html> This is my template, more or less. The h1 heading is always the same as the title tag. The above snippet of code is not valid because there can't be two blocks with the same name. How do I handle this without repeating myself? edit to clarify: I have a ton of child templates which are inherited from this one template, and so making a new {{title}} variable for each template is not a very good solution. Previously I had it set up like this: base.html: <title>{% block title %}{% endblock %}</title> then in base_view.html (extending base.html): <h1>{% block title %}{% endblock %}</h1> then in base_object.html (extending base_view.html): {% block title %}my title goes here{% endblock %} and it just worked somehow. I refactored my templates so theres just base.html, and base_object.html How can I get this functionality back?
[ "In base.html:\n<head>\n <title>{% block title %}{% endblock %}</title>\n</head>\n\n<body>\n <h1>{% block h1 %}{% endblock %}</h1>\n</body>\n\nThen, make another \"base\" layer on top of that called content_base.html (or something):\n{% extends \"base.html\" %}\n\n{% block h1 %}{% block title %}{% endblock %}{% endblock %}\n\nNow have all your other templates extend content_base.html. Whatever you put in block \"title\" in all your templates will go into both \"title\" and \"h1\" blocks in base.html.\n", "{% extends \"base.html\" %}\n\n{% with \"Entry Title\" as title %}\n {% block title %}{{ title }}{% endblock %}\n {% block h1 %}{{ title }}{% endblock %}\n{% endwith %}\n\nThat could work if you're really worried about keeping title out of the views and not repeating yourself.\n", "It looks like your layout is solid. You have a base.html template that defines the basic structure and outer layout for each page in your app. You also have base_object.html that extends this template.\nYou'd like each page to have a unique title and a matching h1 (I think). This best way to do this is to define two separate blocks in your base.html template.\n<html>\n <head>\n <title>{% block title %}Default Title{% endblock %}</title>\n </head>\n\n <body>\n <h1>{% block h1 %}{% endblock %}</h1>\n </body>\n</html>\n\nIn your child templates, you need to override both of these if you'd like them to be identical. I know you feel this is counter-intuitive, but it is necessary due to the way template inheritance is handled in Django.\nSource: The Django template language\n\nFinally, note that you can't define multiple {% block %} tags with the same name in the same template. This limitation exists because a block tag works in \"both\" directions. That is, a block tag doesn't just provide a hole to fill -- it also defines the content that fills the hole in the parent. If there were two similarly-named {% block %} tags in a template, that template's parent wouldn't know which one of the blocks' content to use.\n\nThe children look like this:\n{% extends \"base.html\" %}\n{% block title %}Title{% endblock %}\n{% block h1 %}Title{% endblock %}\n\nIf this bothers you, you should set the title from the view for each object as a template variable.\n{% block title %}{{ title }}{% endblock %}\n{% block h1 %}{{ title }}{% endblock %}\n\nDjango strives to keep as much logic out of the template layer as possible. Often a title is determined dynamically from the database, so the view layer is the perfect place to retrieve and set this information. You can still leave the title blank if you'd like to defer to the default title (perhaps set in base.html, or you can grab the name of the site from the django.contrib.sites package)\nAlso {{ block.super }} may come in handy. This will allow you to combine the contents of the parent block with additional contents from the child. So you could define a title like \"Stackoverflow.com\" in the base, and set\n{% block title %}{{ block.super }} - Ask a Question{% endblock %}\n\nin the child to get a title like \"Stackoverflow.com - Ask a Question\"\n", "Pass a variable to your template, maybe called title. Then replace your title block with {{ title }}. To pass this into your template in your view make sure you have: \ndef myview(request):\n t = loader.get_template(\"mypage.html\")\n title = \"My Title\"\n c = Context({\"title\" : title })\n HttpResponse(t.render(c))\n\nThen in your template you will have:\n<html>\n<head>\n <title>{{ title }}</title>\n</head>\n\n<body>\n <h1>{{ title }}}</h1>\n</body>\n\n\nSee also: How to repeat a \"block\" in a django template\n" ]
[ 24, 13, 8, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0001178743_django_django_templates_python.txt
Q: Is there a simple way to make lists behave as files (with ftplib) I'd like to use ftplib to upload program-generated data as lists. The nearest method I can see for doing this is ftp.storlines, but this requires a file object with a readlines() method. Obviously I could create a file, but this seems like overkill as the data isn't persistent. Is there anything that could do this?: session = ftp.new(...) upload = convertListToFileObject(mylist) session.storlines("STOR SOMETHING",upload) session.quit A: You could always use StringIO (documentation), it is a memory buffer that is a file-like object. from io import StringIO # version < 2.6: from StringIO import StringIO buffer = StringIO() buffer.writelines(mylist) buffer.seek(0) session.storlines("...", buffer) Note that the writelines method does not add line separators. So you need to make sure that each string in mylist ends with a \n. If the items in mylist do not end with a \n, you can do: buffer.writelines(line + '\n' for line in mylist)
Is there a simple way to make lists behave as files (with ftplib)
I'd like to use ftplib to upload program-generated data as lists. The nearest method I can see for doing this is ftp.storlines, but this requires a file object with a readlines() method. Obviously I could create a file, but this seems like overkill as the data isn't persistent. Is there anything that could do this?: session = ftp.new(...) upload = convertListToFileObject(mylist) session.storlines("STOR SOMETHING",upload) session.quit
[ "You could always use StringIO (documentation), it is a memory buffer that is a file-like object.\nfrom io import StringIO # version < 2.6: from StringIO import StringIO\n\nbuffer = StringIO()\nbuffer.writelines(mylist)\nbuffer.seek(0)\n\nsession.storlines(\"...\", buffer)\n\nNote that the writelines method does not add line separators. So you need to make sure that each string in mylist ends with a \\n. If the items in mylist do not end with a \\n, you can do:\nbuffer.writelines(line + '\\n' for line in mylist)\n\n" ]
[ 3 ]
[]
[]
[ "file_upload", "ftp", "iterator", "list", "python" ]
stackoverflow_0002461169_file_upload_ftp_iterator_list_python.txt
Q: django: search forms and redirect After processing form from POST I should redirect, to prevent user from hitting back. However, I am using form to determine search query on a database, so I need to either pass params to the redirected site or the result of a search. Or maybe there is some other good practice, how to solve this problem? Maybe in this situation I am allowed not to redirect (nothing happens, if user performs search again). A: Search queries should probably be GETs, rather than POSTs, because they are not changing anything - they are simply passing parameters to get certain information. POST should be reserved for forms that actually change things in the database, or result in a specific action (eg submitting an email). To reply to your comment, hiding parameters from URLs is not particularly good practice, but if you really think you need to, this is an instance where it's OK not to redirect after the form submission - again, because you're not affecting anything with the POST.
django: search forms and redirect
After processing form from POST I should redirect, to prevent user from hitting back. However, I am using form to determine search query on a database, so I need to either pass params to the redirected site or the result of a search. Or maybe there is some other good practice, how to solve this problem? Maybe in this situation I am allowed not to redirect (nothing happens, if user performs search again).
[ "Search queries should probably be GETs, rather than POSTs, because they are not changing anything - they are simply passing parameters to get certain information. POST should be reserved for forms that actually change things in the database, or result in a specific action (eg submitting an email).\nTo reply to your comment, hiding parameters from URLs is not particularly good practice, but if you really think you need to, this is an instance where it's OK not to redirect after the form submission - again, because you're not affecting anything with the POST.\n" ]
[ 3 ]
[]
[]
[ "django", "python", "redirect", "search_form" ]
stackoverflow_0002461364_django_python_redirect_search_form.txt
Q: Protocols/Interfaces in Ruby While coding in Ruby I did not really miss the type-orientedness of Java or C++ so far, but for some cases I think it is useful to have them. For Python there was a project PyProtocols which defined interfaces and protocols for objects. Does a similar initiative also exist for Ruby? I would like to be able to declare the expected parameters for some methods for some objects (for the entire code I find such think useless). It the method during the execution receives an unexpected input, it tries to adapt it or if it cannot, it throws an exception. Does something similar exist for Ruby? Introducing types for a type-less language like Ruby might sound freak, but I think types are sometimes useful. Thanks for help. A: Check project Ruby-Contract Not more work is happening on it. :( A: This might be interesting for the second part of your question: Type checking in ruby
Protocols/Interfaces in Ruby
While coding in Ruby I did not really miss the type-orientedness of Java or C++ so far, but for some cases I think it is useful to have them. For Python there was a project PyProtocols which defined interfaces and protocols for objects. Does a similar initiative also exist for Ruby? I would like to be able to declare the expected parameters for some methods for some objects (for the entire code I find such think useless). It the method during the execution receives an unexpected input, it tries to adapt it or if it cannot, it throws an exception. Does something similar exist for Ruby? Introducing types for a type-less language like Ruby might sound freak, but I think types are sometimes useful. Thanks for help.
[ "Check project Ruby-Contract \nNot more work is happening on it. :(\n", "This might be interesting for the second part of your question:\nType checking in ruby\n" ]
[ 1, 1 ]
[]
[]
[ "interface", "python", "ruby", "types" ]
stackoverflow_0002461320_interface_python_ruby_types.txt
Q: Python style question, function parameters Which is preferred def method(self): or def method( self ): With spaces in the parenthesis. A: Check out PEP 8. It says to do the first one. A: The common reference for Python style is PEP8, see: http://www.python.org/dev/peps/pep-0008/ To answer your question specifically, this is under "Pet Peeves": Avoid extraneous whitespace in the following situations: Immediately inside parentheses, brackets or braces. Yes: spam(ham[1], {eggs: 2}) No: spam( ham[ 1 ], { eggs: 2 } ) A: There's PEP 8 the Python Style Guide: http://www.python.org/dev/peps/pep-0008/ It suggests the former style, but note the introduction carefully. I find the latter to be visual nails-on-chalkboard, personally. A: http://www.python.org/dev/peps/pep-0008/ A: Python Style Guide No space around the inside of function signatures. Occasionally I put space inside the parens of a function call if the arguments are particularly hairy, but never on the definition. I don't think any language makes a habit of that, actually. A: I don't think you should blindly follow the PEP-8 style, like a vow upon a bible. The PEP8 is intended for code that goes in the python standard library, i.e. the modules you can import just after you've installed Python, but they have very different development constraints than most of the software I write. So I tend to think a lot about each "rule" (either from the PEP8, the pylint/pychecker ones, or the Google Style Guide) and see how it can apply to my code -- the pros and cons. As for your question, people usually don't use spaces inside parentheses, although I've seen it in some code by coworkers that like it, IMHO it detracts a little from readability, but it's a minor issue.
Python style question, function parameters
Which is preferred def method(self): or def method( self ): With spaces in the parenthesis.
[ "Check out PEP 8. It says to do the first one.\n", "The common reference for Python style is PEP8, see: http://www.python.org/dev/peps/pep-0008/\nTo answer your question specifically, this is under \"Pet Peeves\":\nAvoid extraneous whitespace in the following situations:\n\nImmediately inside parentheses, brackets or braces.\n\nYes: spam(ham[1], {eggs: 2})\nNo: spam( ham[ 1 ], { eggs: 2 } )\n\n\n", "There's PEP 8 the Python Style Guide:\nhttp://www.python.org/dev/peps/pep-0008/\nIt suggests the former style, but note the introduction carefully.\nI find the latter to be visual nails-on-chalkboard, personally.\n", "http://www.python.org/dev/peps/pep-0008/\n", "Python Style Guide\nNo space around the inside of function signatures. Occasionally I put space inside the parens of a function call if the arguments are particularly hairy, but never on the definition. I don't think any language makes a habit of that, actually.\n", "I don't think you should blindly follow the PEP-8 style, like a vow upon a bible.\nThe PEP8 is intended for code that goes in the python standard library, i.e. the modules you can import just after you've installed Python, but they have very different development constraints than most of the software I write.\nSo I tend to think a lot about each \"rule\" (either from the PEP8, the pylint/pychecker ones, or the Google Style Guide) and see how it can apply to my code -- the pros and cons.\nAs for your question, people usually don't use spaces inside parentheses, although I've seen it in some code by coworkers that like it, IMHO it detracts a little from readability, but it's a minor issue.\n" ]
[ 16, 9, 3, 1, 1, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0001313694_coding_style_python.txt
Q: idiomatic way to take groups of n items from a list in Python? Given a list A = [1 2 3 4 5 6] Is there any idiomatic (Pythonic) way to iterate over it as though it were B = [(1, 2) (3, 4) (5, 6)] other than indexing? That feels like a holdover from C: for a1,a2 in [ (A[i], A[i+1]) for i in range(0, len(A), 2) ]: I can't help but feel there should be some clever hack using itertools or slicing or something. (Of course, two at a time is just an example; I'd like a solution that works for any n.) Edit: related Iterate over a string 2 (or n) characters at a time in Python but even the cleanest solution (accepted, using zip) doesn't generalize well to higher n without a list comprehension and *-notation. A: From http://docs.python.org/library/itertools.html: from itertools import izip_longest def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) i = grouper(3,range(100)) i.next() (0, 1, 2)
idiomatic way to take groups of n items from a list in Python?
Given a list A = [1 2 3 4 5 6] Is there any idiomatic (Pythonic) way to iterate over it as though it were B = [(1, 2) (3, 4) (5, 6)] other than indexing? That feels like a holdover from C: for a1,a2 in [ (A[i], A[i+1]) for i in range(0, len(A), 2) ]: I can't help but feel there should be some clever hack using itertools or slicing or something. (Of course, two at a time is just an example; I'd like a solution that works for any n.) Edit: related Iterate over a string 2 (or n) characters at a time in Python but even the cleanest solution (accepted, using zip) doesn't generalize well to higher n without a list comprehension and *-notation.
[ "From http://docs.python.org/library/itertools.html:\nfrom itertools import izip_longest\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fillvalue, *args)\n\ni = grouper(3,range(100))\ni.next()\n(0, 1, 2)\n\n" ]
[ 11 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0002461484_iteration_python.txt
Q: Python: Class factory using user input as class names I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasses should depend on user input. There is a superclass "Unit", to which I can add attributes at runtime. This already works. def add_attr (cls, name, value): setattr(cls, name, value) class Unit(object): pass class Archer(Unit): pass myArcher = Archer() add_attr(Unit, 'strength', 5) print "Strenght ofmyarcher: " + str(myArcher.strength) Unit.strength = 2 print "Strenght ofmyarcher: " + str(myArcher.strength) This leads to the desired output: Strenght ofmyarcher: 5 Strenght ofmyarcher: 2 But now I don't want to predefine the subclass Archer, but I'd rather let the user decide how to call this subclass. I've tried something like this: class Meta(type, subclassname): def __new__(cls, subclassname, bases, dct): return type.__new__(cls, subclassname, Unit, dct) factory = Meta() factory.__new__("Soldier") but no luck. I guess I haven't really understood what new does here. What I want as a result here is class Soldier(Unit): pass being created by the factory. And if I call the factory with the argument "Knight", I'd like a class Knight, subclass of Unit, to be created. Any ideas? Many thanks in advance! Bye -Sano A: To create a class from a name, use the class statement and assign the name. Observe: def meta(name): class cls(Unit): pass cls.__name__ = name return cls Now I suppose I should explain myself, and so on. When you create a class using the class statement, it is done dynamically-- it is equivalent of calling type(). For example, the following two snippets do the same thing: class X(object): pass X = type("X", (object,), {}) The name of a class-- the first argument to type-- is assigned to __name__, and that's basically the end of that (the only time __name__ is itself used is probably in the default __repr__() implementation). To create a class with a dynamic name, you can in fact call type like so, or you can just change the class name afterward. The class syntax exists for a reason, though-- it's convenient, and it's easy to add to and change things later. If you wanted to add methods, for example, it would be class X(object): def foo(self): print "foo" def foo(self): print "foo" X = type("X", (object,), {'foo':foo}) and so on. So I would advise using the class statement-- if you had known you could do so from the beginning, you likely would have done so. Dealing with type and so on is a mess. (You should not, by the way, call type.__new__() by hand, only type()) A: Have a look at the type() builtin function. knight_class = type('Knight', (Unit,), {}) First parameter: Name of new class Second parameter: Tuple of parent classes Third parameter: dictionary of class attributes. But in your case, if the subclasses don't implement a different behaviour, maybe giving the Unit class a name attribute is sufficient.
Python: Class factory using user input as class names
I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasses should depend on user input. There is a superclass "Unit", to which I can add attributes at runtime. This already works. def add_attr (cls, name, value): setattr(cls, name, value) class Unit(object): pass class Archer(Unit): pass myArcher = Archer() add_attr(Unit, 'strength', 5) print "Strenght ofmyarcher: " + str(myArcher.strength) Unit.strength = 2 print "Strenght ofmyarcher: " + str(myArcher.strength) This leads to the desired output: Strenght ofmyarcher: 5 Strenght ofmyarcher: 2 But now I don't want to predefine the subclass Archer, but I'd rather let the user decide how to call this subclass. I've tried something like this: class Meta(type, subclassname): def __new__(cls, subclassname, bases, dct): return type.__new__(cls, subclassname, Unit, dct) factory = Meta() factory.__new__("Soldier") but no luck. I guess I haven't really understood what new does here. What I want as a result here is class Soldier(Unit): pass being created by the factory. And if I call the factory with the argument "Knight", I'd like a class Knight, subclass of Unit, to be created. Any ideas? Many thanks in advance! Bye -Sano
[ "To create a class from a name, use the class statement and assign the name. Observe:\ndef meta(name):\n class cls(Unit):\n pass\n\n cls.__name__ = name\n return cls\n\nNow I suppose I should explain myself, and so on. When you create a class using the class statement, it is done dynamically-- it is equivalent of calling type().\nFor example, the following two snippets do the same thing:\nclass X(object): pass\nX = type(\"X\", (object,), {})\n\nThe name of a class-- the first argument to type-- is assigned to __name__, and that's basically the end of that (the only time __name__ is itself used is probably in the default __repr__() implementation). To create a class with a dynamic name, you can in fact call type like so, or you can just change the class name afterward. The class syntax exists for a reason, though-- it's convenient, and it's easy to add to and change things later. If you wanted to add methods, for example, it would be\nclass X(object):\n def foo(self): print \"foo\"\n\ndef foo(self): print \"foo\"\nX = type(\"X\", (object,), {'foo':foo})\n\nand so on. So I would advise using the class statement-- if you had known you could do so from the beginning, you likely would have done so. Dealing with type and so on is a mess.\n(You should not, by the way, call type.__new__() by hand, only type())\n", "Have a look at the type() builtin function.\nknight_class = type('Knight', (Unit,), {})\n\n\nFirst parameter: Name of new class\nSecond parameter: Tuple of parent classes\nThird parameter: dictionary of class attributes.\n\nBut in your case, if the subclasses don't implement a different behaviour, maybe giving the Unit class a name attribute is sufficient.\n" ]
[ 14, 7 ]
[]
[]
[ "factory", "metaclass", "metaprogramming", "python" ]
stackoverflow_0002461751_factory_metaclass_metaprogramming_python.txt
Q: Logical python question - handling directories and files in them I'm using this function to extract files from .zip archive and store it on the server: def unzip_file_into_dir(file, dir): import sys, zipfile, os, os.path os.makedirs(dir, 0777) zfobj = zipfile.ZipFile(file) for name in zfobj.namelist(): if name.endswith('/'): os.mkdir(os.path.join(dir, name)) else: outfile = open(os.path.join(dir, name), 'wb') outfile.write(zfobj.read(name)) outfile.close() And the usage: unzip_file_into_dir('/var/zips/somearchive.zip', '/var/www/extracted_zip') somearchive.zip have this structure: somearchive.zip 1.jpeg 2.jpeg another.jpeg or, somethimes, this one: somearchive.zip somedir/ 1.jpeg 2.jpeg another.jpeg Question is: how do I modify my function, so that my extracted_zip catalog would always contain just images, not images in another subdirectory, even if images are stored in somedir inside an archive. A: Use outfile = open(os.path.join(dir, os.path.basename(name)), 'wb') to strip the path from the name of the ZIP entry. This way, only the filename is left and you don't get any directories. You must also comment out the os.mkdir() or replace it with pass.
Logical python question - handling directories and files in them
I'm using this function to extract files from .zip archive and store it on the server: def unzip_file_into_dir(file, dir): import sys, zipfile, os, os.path os.makedirs(dir, 0777) zfobj = zipfile.ZipFile(file) for name in zfobj.namelist(): if name.endswith('/'): os.mkdir(os.path.join(dir, name)) else: outfile = open(os.path.join(dir, name), 'wb') outfile.write(zfobj.read(name)) outfile.close() And the usage: unzip_file_into_dir('/var/zips/somearchive.zip', '/var/www/extracted_zip') somearchive.zip have this structure: somearchive.zip 1.jpeg 2.jpeg another.jpeg or, somethimes, this one: somearchive.zip somedir/ 1.jpeg 2.jpeg another.jpeg Question is: how do I modify my function, so that my extracted_zip catalog would always contain just images, not images in another subdirectory, even if images are stored in somedir inside an archive.
[ "Use\noutfile = open(os.path.join(dir, os.path.basename(name)), 'wb')\n\nto strip the path from the name of the ZIP entry. This way, only the filename is left and you don't get any directories. You must also comment out the os.mkdir() or replace it with pass.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0002462078_python.txt
Q: Feedback on using Google App Engine? Looking to do a very small, quick 'n dirty side project. I like the fact that the Google App Engine is running on Python with Django built right in - gives me an excuse to try that platform... but my question is this: Has anyone made use of the app engine for anything other than a toy problem? I see some good example apps out there, so I would assume this is good enough for the real deal, but wanted to get some feedback. Any other success/failure notes would be great. A: I have tried app engine for my small quake watch application http://quakewatch.appspot.com/ My purpose was to see the capabilities of app engine, so here are the main points: it doesn't come by default with Django, it has its own web framework which is pythonic has URL dispatcher like Django and it uses Django templates So if you have Django exp. you will find it easy to use But you can use any pure python framework and Django can be easily added see http://code.google.com/appengine/articles/django.html google-app-engine-django (http://code.google.com/p/google-app-engine-django/) project is excellent and works almost like working on a Django project You can not execute any long running process on server, what you do is reply to request and which should be quick otherwise appengine will kill it So if your app needs lots of backend processing appengine is not the best way otherwise you will have to do processing on a server of your own My quakewatch app has a subscription feature, it means I had to email latest quakes as they happend, but I can not run a background process in app engine to monitor new quakes solution here is to use a third part service like pingablity.com which can connect to one of your page and which executes the subscription emailer but here also you will have to take care that you don't spend much time here or break task into several pieces It provides Django like modeling capabilities but backend is totally different but for a new project it should not matter. But overall I think it is excellent for creating apps which do not need lot of background processing. Edit: Now task queues can be used for running batch processing or scheduled tasks Edit: after working/creating a real application on GAE for a year, now my opnion is that unless you are making a application which needs to scale to million and million of users, don't use GAE. Maintaining and doing trivial tasks in GAE is a headache due to distributed nature, to avoid deadline exceeded errors, count entities or do complex queries requires complex code, so small complex application should stick to LAMP. Edit: Models should be specially designed considering all the transactions you wish to have in future, because entities only in same entity group can be used in a transaction and it makes the process of updating two different groups a nightmare e.g. transfer money from user1 to user2 in transaction is impossible unless they are in same entity group, but making them same entity group may not be best for frequent update purposes.... read this http://blog.notdot.net/2009/9/Distributed-Transactions-on-App-Engine A: I am using GAE to host several high-traffic applications. Like on the order of 50-100 req/sec. It is great, I can't recommend it enough. My previous experience with web development was with Ruby (Rails/Merb). Learning Python was easy. I didn't mess with Django or Pylons or any other framework, just started from the GAE examples and built what I needed out of the basic webapp libraries that are provided. If you're used to the flexibility of SQL the datastore can take some getting used to. Nothing too traumatic! The biggest adjustment is moving away from JOINs. You have to shed the idea that normalizing is crucial. Ben A: One of the compelling reasons I have come across for using Google App Engine is its integration with Google Apps for your domain. Essentially it allows you to create custom, managed web applications that are restricted to the (controlled) logins of your domain. Most of my experience with this code was building a simple time/task tracking application. The template engine was simple and yet made a multi-page application very approachable. The login/user awareness api is similarly useful. I was able to make a public page/private page paradigm without too much issue. (a user would log in to see the private pages. An anonymous user was only shown the public page.) I was just getting into the datastore portion of the project when I got pulled away for "real work". I was able to accomplish a lot (it still is not done yet) in a very little amount of time. Since I had never used Python before, this was particularly pleasant (both because it was a new language for me, and also because the development was still fast despite the new language). I ran into very little that led me to believe that I wouldn't be able to accomplish my task. Instead I have a fairly positive impression of the functionality and features. That is my experience with it. Perhaps it doesn't represent more than an unfinished toy project, but it does represent an informed trial of the platform, and I hope that helps. A: The "App Engine running Django" idea is a bit misleading. App Engine replaces the entire Django model layer so be prepared to spend some time getting acclimated with App Engine's datastore which requires a different way of modeling and thinking about data. A: I used GAE to build http://www.muspy.com It's a bit more than a toy project but not overly complex either. I still depend on a few issues to be addressed by Google, but overall developing the website was an enjoyable experience. If you don't want to deal with hosting issues, server administration, etc, I can definitely recommend it. Especially if you already know Python and Django. A: I think App Engine is pretty cool for small projects at this point. There's a lot to be said for never having to worry about hosting. The API also pushes you in the direction of building scalable apps, which is good practice. app-engine-patch is a good layer between Django and App Engine, enabling the use of the auth app and more. Google have promised an SLA and pricing model by the end of 2008. Requests must complete in 10 seconds, sub-requests to web services required to complete in 5 seconds. This forces you to design a fast, lightweight application, off-loading serious processing to other platforms (e.g. a hosted service or an EC2 instance). More languages are coming soon! Google won't say which though :-). My money's on Java next. A: This question has been fully answered. Which is good. But one thing perhaps is worth mentioning. The google app engine has a plugin for the eclipse ide which is a joy to work with. If you already do your development with eclipse you are going to be so happy about that. To deploy on the google app engine's web site all I need to do is click one little button - with the airplane logo - super. A: Take a look the the sql game, it is very stable and actually pushed traffic limits at one point so that it was getting throttled by Google. I have seen nothing but good news about App Engine, other than hosting you app on servers someone else controls completely. A: I used GAE to build a simple application which accepts some parameters, formats and send email. It was extremely simple and fast. I also made some performance benchmarks on the GAE datastore and memcache services (http://dbaspects.blogspot.com/2010/01/memcache-vs-datastore-on-google-app.html ). It is not that fast. My opinion is that GAE is serious platform which enforce certain methodology. I think it will evolve to the truly scalable platform, where bad practices simply not allowed. A: I used GAE for my flash gaming site, Bearded Games. GAE is a great platform. I used Django templates which are so much easier than the old days of PHP. It comes with a great admin panel, and gives you really good logs. The datastore is different than a database like MySQL, but it's much easier to work with. Building the site was easy and straightforward and they have lots of helpful advice on the site. A: I used GAE and Django to build a Facebook application. I used http://code.google.com/p/app-engine-patch as my starting point as it has Django 1.1 support. I didn't try to use any of the manage.py commands because I assumed they wouldn't work, but I didn't even look into it. The application had three models and also used pyfacebook, but that was the extent of the complexity. I'm in the process of building a much more complicated application which I'm starting to blog about on http://brianyamabe.com.
Feedback on using Google App Engine?
Looking to do a very small, quick 'n dirty side project. I like the fact that the Google App Engine is running on Python with Django built right in - gives me an excuse to try that platform... but my question is this: Has anyone made use of the app engine for anything other than a toy problem? I see some good example apps out there, so I would assume this is good enough for the real deal, but wanted to get some feedback. Any other success/failure notes would be great.
[ "I have tried app engine for my small quake watch application\nhttp://quakewatch.appspot.com/\nMy purpose was to see the capabilities of app engine, so here are the main points:\n\nit doesn't come by default with Django, it has its own web framework which is pythonic has URL dispatcher like Django and it uses Django templates\nSo if you have Django exp. you will find it easy to use\n\n\nBut you can use any pure python framework and Django can be easily added see\nhttp://code.google.com/appengine/articles/django.html\ngoogle-app-engine-django (http://code.google.com/p/google-app-engine-django/) project is excellent and works almost like working on a Django project\n\nYou can not execute any long running process on server, what you do is reply to request and which should be quick otherwise appengine will kill it\nSo if your app needs lots of backend processing appengine is not the best way\notherwise you will have to do processing on a server of your own\nMy quakewatch app has a subscription feature, it means I had to email latest quakes as they happend, but I can not run a background process in app engine to monitor new quakes\nsolution here is to use a third part service like pingablity.com which can connect to one of your page and which executes the subscription emailer\nbut here also you will have to take care that you don't spend much time here\nor break task into several pieces\nIt provides Django like modeling capabilities but backend is totally different but for a new project it should not matter.\n\nBut overall I think it is excellent for creating apps which do not need lot of background processing.\nEdit:\nNow task queues can be used for running batch processing or scheduled tasks\nEdit:\nafter working/creating a real application on GAE for a year, now my opnion is that unless you are making a application which needs to scale to million and million of users, don't use GAE. Maintaining and doing trivial tasks in GAE is a headache due to distributed nature, to avoid deadline exceeded errors, count entities or do complex queries requires complex code, so small complex application should stick to LAMP.\nEdit:\nModels should be specially designed considering all the transactions you wish to have in future, because entities only in same entity group can be used in a transaction and it makes the process of updating two different groups a nightmare e.g. transfer money from user1 to user2 in transaction is impossible unless they are in same entity group, but making them same entity group may not be best for frequent update purposes....\nread this http://blog.notdot.net/2009/9/Distributed-Transactions-on-App-Engine\n", "I am using GAE to host several high-traffic applications. Like on the order of 50-100 req/sec. It is great, I can't recommend it enough.\nMy previous experience with web development was with Ruby (Rails/Merb). Learning Python was easy. I didn't mess with Django or Pylons or any other framework, just started from the GAE examples and built what I needed out of the basic webapp libraries that are provided.\nIf you're used to the flexibility of SQL the datastore can take some getting used to. Nothing too traumatic! The biggest adjustment is moving away from JOINs. You have to shed the idea that normalizing is crucial.\nBen\n", "One of the compelling reasons I have come across for using Google App Engine is its integration with Google Apps for your domain. Essentially it allows you to create custom, managed web applications that are restricted to the (controlled) logins of your domain. \nMost of my experience with this code was building a simple time/task tracking application. The template engine was simple and yet made a multi-page application very approachable. The login/user awareness api is similarly useful. I was able to make a public page/private page paradigm without too much issue. (a user would log in to see the private pages. An anonymous user was only shown the public page.)\nI was just getting into the datastore portion of the project when I got pulled away for \"real work\".\nI was able to accomplish a lot (it still is not done yet) in a very little amount of time. Since I had never used Python before, this was particularly pleasant (both because it was a new language for me, and also because the development was still fast despite the new language). I ran into very little that led me to believe that I wouldn't be able to accomplish my task. Instead I have a fairly positive impression of the functionality and features. \nThat is my experience with it. Perhaps it doesn't represent more than an unfinished toy project, but it does represent an informed trial of the platform, and I hope that helps.\n", "The \"App Engine running Django\" idea is a bit misleading. App Engine replaces the entire Django model layer so be prepared to spend some time getting acclimated with App Engine's datastore which requires a different way of modeling and thinking about data. \n", "I used GAE to build http://www.muspy.com\nIt's a bit more than a toy project but not overly complex either. I still depend on a few issues to be addressed by Google, but overall developing the website was an enjoyable experience.\nIf you don't want to deal with hosting issues, server administration, etc, I can definitely recommend it. Especially if you already know Python and Django.\n", "I think App Engine is pretty cool for small projects at this point. There's a lot to be said for never having to worry about hosting. The API also pushes you in the direction of building scalable apps, which is good practice.\n\napp-engine-patch is a good layer between Django and App Engine, enabling the use of the auth app and more.\nGoogle have promised an SLA and pricing model by the end of 2008.\nRequests must complete in 10 seconds, sub-requests to web services required to complete in 5 seconds. This forces you to design a fast, lightweight application, off-loading serious processing to other platforms (e.g. a hosted service or an EC2 instance).\nMore languages are coming soon! Google won't say which though :-). My money's on Java next.\n\n", "This question has been fully answered. Which is good. \nBut one thing perhaps is worth mentioning.\nThe google app engine has a plugin for the eclipse ide which is a joy to work with. \nIf you already do your development with eclipse you are going to be so happy about that. \nTo deploy on the google app engine's web site all I need to do is click one little button - with the airplane logo - super. \n", "Take a look the the sql game, it is very stable and actually pushed traffic limits at one point so that it was getting throttled by Google. I have seen nothing but good news about App Engine, other than hosting you app on servers someone else controls completely.\n", "I used GAE to build a simple application which accepts some parameters, formats and send email. It was extremely simple and fast. I also made some performance benchmarks on the GAE datastore and memcache services (http://dbaspects.blogspot.com/2010/01/memcache-vs-datastore-on-google-app.html ). It is not that fast. My opinion is that GAE is serious platform which enforce certain methodology. I think it will evolve to the truly scalable platform, where bad practices simply not allowed.\n", "I used GAE for my flash gaming site, Bearded Games. GAE is a great platform. I used Django templates which are so much easier than the old days of PHP. It comes with a great admin panel, and gives you really good logs. The datastore is different than a database like MySQL, but it's much easier to work with. Building the site was easy and straightforward and they have lots of helpful advice on the site.\n", "I used GAE and Django to build a Facebook application. I used http://code.google.com/p/app-engine-patch as my starting point as it has Django 1.1 support. I didn't try to use any of the manage.py commands because I assumed they wouldn't work, but I didn't even look into it. The application had three models and also used pyfacebook, but that was the extent of the complexity. I'm in the process of building a much more complicated application which I'm starting to blog about on http://brianyamabe.com.\n" ]
[ 63, 36, 23, 12, 7, 7, 6, 4, 4, 4, 3 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0000110186_django_google_app_engine_python.txt
Q: Running a python script in background from a CGI I have a python CGI which runs some script in the background and shows the stdout in the html page. I run the script when the user clicks some button in the page. My problem is when the script starts running the page becomes busy and the user can't use the other client side features in the page. What I want is: The script should run in background when the user clicks the button and should notify the CGI when run is complete. Then the CGI show should the stdout of the script run. How can this be done? A: well, short answer: you can't. medium answer: CGI sucks. long answer: CGI works by running your script and returning whatever your script prints to the browser. If your script is still running, the browser will be waiting. If your script launches a background job and returns data to the browser, then the background job can't notify the CGI script because it is already done. You must choose an alternate solution. Save the results of the background job to a file, database, or some other persistent storage, and make the user request that data, using another link in your page, which runs a different code that retrieves the saved results and display them. Another way is to use AJAX techniques in the browser. Write javascript code to do the request to the data in the background. So the browser can still be responsive with other page elements while the script is running.
Running a python script in background from a CGI
I have a python CGI which runs some script in the background and shows the stdout in the html page. I run the script when the user clicks some button in the page. My problem is when the script starts running the page becomes busy and the user can't use the other client side features in the page. What I want is: The script should run in background when the user clicks the button and should notify the CGI when run is complete. Then the CGI show should the stdout of the script run. How can this be done?
[ "well, short answer: you can't.\nmedium answer: CGI sucks.\nlong answer: CGI works by running your script and returning whatever your script prints to the browser. If your script is still running, the browser will be waiting. If your script launches a background job and returns data to the browser, then the background job can't notify the CGI script because it is already done.\nYou must choose an alternate solution. \nSave the results of the background job to a file, database, or some other persistent storage, and make the user request that data, using another link in your page, which runs a different code that retrieves the saved results and display them.\nAnother way is to use AJAX techniques in the browser. Write javascript code to do the request to the data in the background. So the browser can still be responsive with other page elements while the script is running.\n" ]
[ 2 ]
[]
[]
[ "backgroundworker", "cgi", "python" ]
stackoverflow_0002461964_backgroundworker_cgi_python.txt
Q: How do I create a python module from a fortran program with f2py? I am trying to read some smps files with python, and found a fortran implementation, so I thought I would give f2py a shot. The problem is that I have no experience with fortran. I have successfully installed gfortran and f2py on my Linux box and ran the example on thew f2py page, but I have some trouble compiling and running the large program. There are two files, one with a file reader wrapper and one with all the logic. They seem to call each other, but when I compile and link or try f2py, I get errors that they somehow can't find each other: f95 -c FILEWR~1.F f95 -c SMPSREAD.F90 f95 -o smpsread SMPSREAD.o FILEWR~1.o FILEWR~1.o In function `file_wrapper_' FILEWR~1.F(.text+0x3d) undefined reference to `chopen_' usrlibgcci486-linux-gnu4.4.1libgfortranbegin.a(fmain.o) In function `main' (.text+0x27) undefined reference to `MAIN__' collect2 ld returned 1 exit status I also tried changing the name to FILE_WRAPPER.F but that did not help. With f2py I found out I had to include a comment to get it to accept free format, and saved this as a new file and tried: f2py -c -m smpsread smpsread.f90 I get a lot of output and warnings, but the error seems to be this one: getctype: No C-type found in "{'typespec': 'type', 'attrspec': ['allocatable'], 'typename': 'node', 'dimension': [':']}", assuming void. The fortran 90 spms reader can be found here. Any help or suggestions appreciated. A: I would suggest skipping the fortran business altogether. http://myweb.dal.ca/gassmann/smps2.htm The MPS record layout is described here, and looks relatively simple to pick apart in Python. http://myweb.dal.ca/gassmann/smps2.htm#CoreMPSline You'll have to define appropriate Python classes (or namedtuples) for all of the data anyway. I don't think the Fortran is helping.
How do I create a python module from a fortran program with f2py?
I am trying to read some smps files with python, and found a fortran implementation, so I thought I would give f2py a shot. The problem is that I have no experience with fortran. I have successfully installed gfortran and f2py on my Linux box and ran the example on thew f2py page, but I have some trouble compiling and running the large program. There are two files, one with a file reader wrapper and one with all the logic. They seem to call each other, but when I compile and link or try f2py, I get errors that they somehow can't find each other: f95 -c FILEWR~1.F f95 -c SMPSREAD.F90 f95 -o smpsread SMPSREAD.o FILEWR~1.o FILEWR~1.o In function `file_wrapper_' FILEWR~1.F(.text+0x3d) undefined reference to `chopen_' usrlibgcci486-linux-gnu4.4.1libgfortranbegin.a(fmain.o) In function `main' (.text+0x27) undefined reference to `MAIN__' collect2 ld returned 1 exit status I also tried changing the name to FILE_WRAPPER.F but that did not help. With f2py I found out I had to include a comment to get it to accept free format, and saved this as a new file and tried: f2py -c -m smpsread smpsread.f90 I get a lot of output and warnings, but the error seems to be this one: getctype: No C-type found in "{'typespec': 'type', 'attrspec': ['allocatable'], 'typename': 'node', 'dimension': [':']}", assuming void. The fortran 90 spms reader can be found here. Any help or suggestions appreciated.
[ "I would suggest skipping the fortran business altogether.\nhttp://myweb.dal.ca/gassmann/smps2.htm\nThe MPS record layout is described here, and looks relatively simple to pick apart in Python.\nhttp://myweb.dal.ca/gassmann/smps2.htm#CoreMPSline\nYou'll have to define appropriate Python classes (or namedtuples) for all of the data anyway. \nI don't think the Fortran is helping.\n" ]
[ 0 ]
[]
[]
[ "f2py", "fortran", "python" ]
stackoverflow_0002462354_f2py_fortran_python.txt
Q: How to implement full text search in Django? I would like to implement a search function in a django blogging application. The status quo is that I have a list of strings supplied by the user and the queryset is narrowed down by each string to include only those objects that match the string. See: if request.method == "POST": form = SearchForm(request.POST) if form.is_valid(): posts = Post.objects.all() for string in form.cleaned_data['query'].split(): posts = posts.filter( Q(title__icontains=string) | Q(text__icontains=string) | Q(tags__name__exact=string) ) return archive_index(request, queryset=posts, date_field='date') Now, what if I didn't want do concatenate each word that is searched for by a logical AND but with a logical OR? How would I do that? Is there a way to do that with Django's own Queryset methods or does one have to fall back to raw SQL queries? In general, is it a proper solution to do full text search like this or would you recommend using a search engine like Solr, Whoosh or Xapian. What are their benefits? A: I suggest you to adopt a search engine. We've used Haystack search, a modular search application for django supporting many search engines (Solr, Xapian, Whoosh, etc...) Advantages: Faster perform search queries even without querying the database. Highlight searched terms "More like this" functionality Spelling suggestions Better ranking etc... Disadvantages: Search Indexes can grow in size pretty fast One of the best search engines (Solr) run as a Java servlet (Xapian does not) We're pretty happy with this solution and it's pretty easy to implement. A: Actually, the query you have posted does use OR rather than AND - you're using \ to separate the Q objects. AND would be &. In general, I would highly recommend using a proper search engine. We have had good success with Haystack on top of Solr - Haystack manages all the Solr configuration, and exposes a nice API very similar to Django's own ORM. A: Answer to your general question: Definitely use a proper application for this. With your query, you always examine the whole content of the fields (title, text, tags). You gain no benefit from indexes, etc. With a proper full text search engine (or whatever you call it), text (words) is (are) indexed every time you insert new records. So queries will be a lot faster especially when your database grows. A: SOLR is very easy to setup and integrate with Django. Haystack makes it even simpler. A: For full text search in Python, look at PyLucene. It allows for very complex queries. The main problem here is that you must find a way to tell your search engine which pages changed and update the index eventually. Alternatively, you can use Google Sitemaps to tell Google to index your site faster and then embed a custom query field in your site. The advantage here is that you just need to tell Google the changed pages and Google will do all the hard work (indexing, parsing the queries, etc). On top of that, most people are used to use Google to search plus it will keep your site current in the global Google searches, too. A: I think full text search on an application level is more a matter of what you have and how you expect it to scale. If you run a small site with low usage I think it might be more affordable to put some time into making an custom full text search rather than installing an application to perform the search for you. And application would create more dependency, maintenance and extra effort when storing data. By making your search yourself and you can build in nice custom features. Like for example, if your text exactly matches one title you can direct the user to that page instead of showing the results. Another would be to allow title: or author: prefixes to keywords. Here is a method I've used for generating relevant search results from a web query. import shlex class WeightedGroup: def __init__(self): # using a dictionary will make the results not paginate # but it will be a lot faster when storing data self.data = {} def list(self, max_len=0): # returns a sorted list of the items with heaviest weight first res = [] while len(self.data) != 0: nominated_weight = 0 for item, weight in self.data.iteritems(): if weight > nominated_weight: nominated = item nominated_weight = weight self.data.pop(nominated) res.append(nominated) if len(res) == max_len: return res return res def append(self, weight, item): if item in self.data: self.data[item] += weight else: self.data[item] = weight def search(searchtext): candidates = WeightedGroup() for arg in shlex.split(searchtext): # shlex understand quotes # Search TITLE # order by date so we get most recent posts query = Post.objects.filter_by(title__icontains=arg).order_by('-date') arg_hits = query.count() # count is cheap if arg_hits > 1000: continue # skip keywords which has too many hits # Each of these are expensive as it would transfer data # from the db and build a python object, for post in query[:50]: # so we limit it to 50 for example # more hits a keyword has the lesser it's relevant candidates.append(100.0 / arg_hits, post.post_id) # TODO add searchs for other areas # Weight might also be adjusted with number of hits within the text # or perhaps you can find other metrics to value an post higher, # like number of views # candidates can contain a lot of stuff now, show most relevant only sorted_result = Post.objects.filter_by(post_id__in=candidates.list(20))
How to implement full text search in Django?
I would like to implement a search function in a django blogging application. The status quo is that I have a list of strings supplied by the user and the queryset is narrowed down by each string to include only those objects that match the string. See: if request.method == "POST": form = SearchForm(request.POST) if form.is_valid(): posts = Post.objects.all() for string in form.cleaned_data['query'].split(): posts = posts.filter( Q(title__icontains=string) | Q(text__icontains=string) | Q(tags__name__exact=string) ) return archive_index(request, queryset=posts, date_field='date') Now, what if I didn't want do concatenate each word that is searched for by a logical AND but with a logical OR? How would I do that? Is there a way to do that with Django's own Queryset methods or does one have to fall back to raw SQL queries? In general, is it a proper solution to do full text search like this or would you recommend using a search engine like Solr, Whoosh or Xapian. What are their benefits?
[ "I suggest you to adopt a search engine.\nWe've used Haystack search, a modular search application for django supporting many search engines (Solr, Xapian, Whoosh, etc...)\nAdvantages:\n\nFaster\nperform search queries even without querying the database.\nHighlight searched terms\n\"More like this\" functionality\nSpelling suggestions\nBetter ranking\netc...\n\nDisadvantages:\n\nSearch Indexes can grow in size pretty fast\nOne of the best search engines (Solr) run as a Java servlet (Xapian does not)\n\nWe're pretty happy with this solution and it's pretty easy to implement.\n", "Actually, the query you have posted does use OR rather than AND - you're using \\ to separate the Q objects. AND would be &.\nIn general, I would highly recommend using a proper search engine. We have had good success with Haystack on top of Solr - Haystack manages all the Solr configuration, and exposes a nice API very similar to Django's own ORM.\n", "Answer to your general question: Definitely use a proper application for this.\nWith your query, you always examine the whole content of the fields (title, text, tags). You gain no benefit from indexes, etc.\nWith a proper full text search engine (or whatever you call it), text (words) is (are) indexed every time you insert new records. So queries will be a lot faster especially when your database grows.\n", "SOLR is very easy to setup and integrate with Django. Haystack makes it even simpler.\n", "For full text search in Python, look at PyLucene. It allows for very complex queries. The main problem here is that you must find a way to tell your search engine which pages changed and update the index eventually.\nAlternatively, you can use Google Sitemaps to tell Google to index your site faster and then embed a custom query field in your site. The advantage here is that you just need to tell Google the changed pages and Google will do all the hard work (indexing, parsing the queries, etc). On top of that, most people are used to use Google to search plus it will keep your site current in the global Google searches, too.\n", "I think full text search on an application level is more a matter of what you have and how you expect it to scale. If you run a small site with low usage I think it might be more affordable to put some time into making an custom full text search rather than installing an application to perform the search for you. And application would create more dependency, maintenance and extra effort when storing data. By making your search yourself and you can build in nice custom features. Like for example, if your text exactly matches one title you can direct the user to that page instead of showing the results. Another would be to allow title: or author: prefixes to keywords. \nHere is a method I've used for generating relevant search results from a web query.\nimport shlex\n\nclass WeightedGroup:\n def __init__(self): \n # using a dictionary will make the results not paginate\n # but it will be a lot faster when storing data \n self.data = {}\n\n def list(self, max_len=0):\n # returns a sorted list of the items with heaviest weight first\n res = []\n while len(self.data) != 0:\n nominated_weight = 0 \n for item, weight in self.data.iteritems():\n if weight > nominated_weight:\n nominated = item\n nominated_weight = weight\n self.data.pop(nominated)\n res.append(nominated)\n if len(res) == max_len:\n return res\n return res\n\n def append(self, weight, item):\n if item in self.data:\n self.data[item] += weight\n else:\n self.data[item] = weight\n\n\ndef search(searchtext):\n candidates = WeightedGroup()\n\n for arg in shlex.split(searchtext): # shlex understand quotes\n\n # Search TITLE\n # order by date so we get most recent posts\n query = Post.objects.filter_by(title__icontains=arg).order_by('-date')\n arg_hits = query.count() # count is cheap\n\n if arg_hits > 1000:\n continue # skip keywords which has too many hits\n\n # Each of these are expensive as it would transfer data\n # from the db and build a python object, \n for post in query[:50]: # so we limit it to 50 for example \n # more hits a keyword has the lesser it's relevant\n candidates.append(100.0 / arg_hits, post.post_id)\n\n # TODO add searchs for other areas\n # Weight might also be adjusted with number of hits within the text\n # or perhaps you can find other metrics to value an post higher,\n # like number of views\n\n # candidates can contain a lot of stuff now, show most relevant only\n sorted_result = Post.objects.filter_by(post_id__in=candidates.list(20))\n\n" ]
[ 16, 5, 4, 4, 2, 2 ]
[]
[]
[ "django", "django_queryset", "full_text_search", "python" ]
stackoverflow_0002461322_django_django_queryset_full_text_search_python.txt
Q: Python rounding issue I have come across a very strange issue in python. (Using python 2.4.x) In windows: >>> a = 2292.5 >>> print '%.0f' % a 2293 But in Solaris: >>> a = 2292.5 >>> print '%.0f' % a 2292 But this is the same in both windows and solaris: >>> a = 1.5 >>> print '%.0f' % a 2 Can someone explain this behavior? I'm guessing it's platform dependent on the way that python was compiled? A: The function ultimately in charge of performing that formatting is PyOS_snprintf (see the sources). As you surmise, that's unfortunately system-dependent, i.e., it relies on vsprintf, vsnprintf or other similar functions that are ultimately supplied by the platform's C runtime library (I don't recall if the C standard says anything about the '%f' formatting for floats that are "exactly midway" between two possible rounded values... but, whether the C standard is lax about this, or rather the C standard is strict but some C runtimes break it, ultimately is a pretty academic issue...). A: round() rounds toward the nearest even integer "%n.nf" works the same way as round() int() truncates towards zero "rounding a positive number to the nearest integer can be implemented by adding 0.5 and truncating" -- http://en.wikipedia.org/wiki/Rounding In Python you can do this with: math.trunc( n + 0.5 ) assuming n is positive of course... Where "round half to even" is not appropriate, i now use math.trunc( n + 0.5 ) where i used to use int(round(n)) A: I is plataform dependent. You can find the documentation here. It is good to user ceil or floor when you know what you want (to round up or down).
Python rounding issue
I have come across a very strange issue in python. (Using python 2.4.x) In windows: >>> a = 2292.5 >>> print '%.0f' % a 2293 But in Solaris: >>> a = 2292.5 >>> print '%.0f' % a 2292 But this is the same in both windows and solaris: >>> a = 1.5 >>> print '%.0f' % a 2 Can someone explain this behavior? I'm guessing it's platform dependent on the way that python was compiled?
[ "The function ultimately in charge of performing that formatting is PyOS_snprintf \n(see the sources). As you surmise, that's unfortunately system-dependent, i.e., it relies on vsprintf, vsnprintf or other similar functions that are ultimately supplied by the platform's C runtime library (I don't recall if the C standard says anything about the '%f' formatting for floats that are \"exactly midway\" between two possible rounded values... but, whether the C standard is lax about this, or rather the C standard is strict but some C runtimes break it, ultimately is a pretty academic issue...).\n", "round() rounds toward the nearest even integer\n\"%n.nf\" works the same way as round()\nint() truncates towards zero\n\"rounding a positive number to the nearest integer\ncan be implemented by adding 0.5 and truncating\"\n-- http://en.wikipedia.org/wiki/Rounding\nIn Python you can do this with: math.trunc( n + 0.5 )\nassuming n is positive of course...\nWhere \"round half to even\" is not appropriate, i now use\nmath.trunc( n + 0.5 ) where i used to use int(round(n)) \n", "I is plataform dependent. You can find the documentation here.\nIt is good to user ceil or floor when you know what you want (to round up or down).\n" ]
[ 10, 2, 0 ]
[]
[]
[ "python", "rounding" ]
stackoverflow_0002174081_python_rounding.txt
Q: Python: using a regular expression to match one line of HTML This simple Python method I put together just checks to see if Tomcat is running on one of our servers. import urllib2 import re import sys def tomcat_check(): tomcat_status = urllib2.urlopen('http://10.1.1.20:7880') results = tomcat_status.read() pattern = re.compile('<body>Tomcat is running...</body>',re.M|re.DOTALL) q = pattern.search(results) if q == []: notify_us() else: print ("Tomcat appears to be running") sys.exit() If this line is not found : <body>Tomcat is running...</body> It calls : notify_us() Which uses SMTP to send an email message to myself and another admin that Tomcat is no longer runnning on the server... I have not used the re module in Python before...so I am assuming there is a better way to do this... I am also open to a more graceful solution with Beautiful Soup ... but haven't used that either.. Just trying to keep this as simple as possible... A: Why use regex here at all? Why not just a simple string search?: if not '<body>Tomcat is running...</body>' in results: notify_us() A: if not 'Tomcat is running' in results: notify_us() A: There are lots of different methods: str.find() if results.find("Tomcat is running...") != -1: print "Tomcat appears to be running" else: notify_us() Using X in Y if "Tomcat is running..." in result: print "Tomcat appears to be running" else: notify_us() Using Regular Expressions if re.search(r"Tomcat is running\.\.\.", result): print "Tomcat appears to be running" else: notify_us() Personally, I prefer the membership operator to test if the string is in another string. A: Since you appear to be looking for a fixed string (not a regexp) that you have some control over and can be expected to be consistent, str.find() should do just fine. Or what Daniel said. A: As you have mentioned, regular expressions aren't suited for parsing XML like structures (at least, for more complex queries). I would do something like that: from lxml import etree import urllib2 def tomcat_check(host='127.0.0.1', port=7880): response = urllib2.urlopen('http://%s:%d' % (host, port)) html = etree.HTML(response.read()) return html.findtext('.//body') == 'Tomcat is running...' if tomcat_check('10.1.1.20'): print 'Tomcat is running...' else: # notify someone
Python: using a regular expression to match one line of HTML
This simple Python method I put together just checks to see if Tomcat is running on one of our servers. import urllib2 import re import sys def tomcat_check(): tomcat_status = urllib2.urlopen('http://10.1.1.20:7880') results = tomcat_status.read() pattern = re.compile('<body>Tomcat is running...</body>',re.M|re.DOTALL) q = pattern.search(results) if q == []: notify_us() else: print ("Tomcat appears to be running") sys.exit() If this line is not found : <body>Tomcat is running...</body> It calls : notify_us() Which uses SMTP to send an email message to myself and another admin that Tomcat is no longer runnning on the server... I have not used the re module in Python before...so I am assuming there is a better way to do this... I am also open to a more graceful solution with Beautiful Soup ... but haven't used that either.. Just trying to keep this as simple as possible...
[ "Why use regex here at all? Why not just a simple string search?:\nif not '<body>Tomcat is running...</body>' in results:\n notify_us()\n\n", "if not 'Tomcat is running' in results:\n notify_us()\n\n", "There are lots of different methods:\nstr.find()\nif results.find(\"Tomcat is running...\") != -1:\n print \"Tomcat appears to be running\"\nelse:\n notify_us()\n\nUsing X in Y\nif \"Tomcat is running...\" in result:\n print \"Tomcat appears to be running\"\nelse:\n notify_us()\n\nUsing Regular Expressions\nif re.search(r\"Tomcat is running\\.\\.\\.\", result):\n print \"Tomcat appears to be running\"\nelse:\n notify_us()\n\nPersonally, I prefer the membership operator to test if the string is in another string.\n", "Since you appear to be looking for a fixed string (not a regexp) that you have some control over and can be expected to be consistent, str.find() should do just fine. Or what Daniel said.\n", "As you have mentioned, regular expressions aren't suited for parsing XML like structures (at least, for more complex queries). I would do something like that:\nfrom lxml import etree\nimport urllib2\n\ndef tomcat_check(host='127.0.0.1', port=7880):\n response = urllib2.urlopen('http://%s:%d' % (host, port))\n html = etree.HTML(response.read())\n return html.findtext('.//body') == 'Tomcat is running...'\n\nif tomcat_check('10.1.1.20'):\n print 'Tomcat is running...'\nelse:\n # notify someone\n\n" ]
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0002463188_html_python_regex.txt
Q: Is there some good Twisted cheat sheets or reference cards? I'm recently started to learn Twisted framework and now looking for some cheat sheets/reference cards with basic Twisted stuff. Such as deferreds, callbacks, reactor, protocols, factories, transports, so on. At the moment found nothing neither on http://refcardz.dzone.com/ nor on http://www.cheat-sheets.org/ Any help appreciated. A: The closest thing I know of is Everything You Always Wanted to Know About Twisted It's not really a "cheat-sheet", but it is a concise introduction to most of the basic concepts.
Is there some good Twisted cheat sheets or reference cards?
I'm recently started to learn Twisted framework and now looking for some cheat sheets/reference cards with basic Twisted stuff. Such as deferreds, callbacks, reactor, protocols, factories, transports, so on. At the moment found nothing neither on http://refcardz.dzone.com/ nor on http://www.cheat-sheets.org/ Any help appreciated.
[ "The closest thing I know of is Everything You Always Wanted to Know About Twisted\nIt's not really a \"cheat-sheet\", but it is a concise introduction to most of the basic concepts.\n" ]
[ 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002431932_python_twisted.txt
Q: Good Sound processing/Analysis/Capturing Modules We are working on Sound processing and Analysis where we need to extract frequencies, pitches, octaves and other parameters of sound including dBPowerSpectrum Analysis. We also need to do this irrespective of the file formats or do the conversion between quite a file format(though conversion is not a very critical requirement if those parameters can be analyzed on most file formats). We also need to capture/record sound from Mic. We found a Python module called Snack which does almost everything we need, but the whole problem is that it requires tkinter to be installed. Since we are planning to write a Web client for this program, I feel installing tkinter and initializing and passing its object to Sound Processing module is an overhead. Can you please suggest us few good Sound Processing Module. We don't expect an all in one module. Its OK even if these functionalities are spread over several modules. Kindly suggest. Thanks in Advance A: See http://www.csounds.com/node/188 for a package that does much of this. A: For audio capture and playback I've liked PyAudio. It's cross-platform and pretty easy to use. A: You can use scikits audiolab to read in any file supported by libsndfile, and then use PyLab (NumPy and SciPy) to do the processing. I don't know of a way to read in live audio from the mic, though, which is why I was just looking at Snack myself. If there's a way to convert Snack sounds into numpy arrays, then that would work. If you use padsp ipython in Ubuntu, you can read in data from /dev/dsp, and it will actually be coming from PulseAudio's input. You can use the ossaudiodev module, though I haven't gotten this to work, or you can do some kind of ugly construction like: audio = numpy.fromfile('/dev/dsp'... but I guess you still need to use ossaudiodev to set up the sampling rate, format, etc. first.
Good Sound processing/Analysis/Capturing Modules
We are working on Sound processing and Analysis where we need to extract frequencies, pitches, octaves and other parameters of sound including dBPowerSpectrum Analysis. We also need to do this irrespective of the file formats or do the conversion between quite a file format(though conversion is not a very critical requirement if those parameters can be analyzed on most file formats). We also need to capture/record sound from Mic. We found a Python module called Snack which does almost everything we need, but the whole problem is that it requires tkinter to be installed. Since we are planning to write a Web client for this program, I feel installing tkinter and initializing and passing its object to Sound Processing module is an overhead. Can you please suggest us few good Sound Processing Module. We don't expect an all in one module. Its OK even if these functionalities are spread over several modules. Kindly suggest. Thanks in Advance
[ "See http://www.csounds.com/node/188 for a package that does much of this.\n", "For audio capture and playback I've liked PyAudio. It's cross-platform and pretty easy to use.\n", "You can use scikits audiolab to read in any file supported by libsndfile, and then use PyLab (NumPy and SciPy) to do the processing.\nI don't know of a way to read in live audio from the mic, though, which is why I was just looking at Snack myself. If there's a way to convert Snack sounds into numpy arrays, then that would work.\nIf you use padsp ipython in Ubuntu, you can read in data from /dev/dsp, and it will actually be coming from PulseAudio's input. You can use the ossaudiodev module, though I haven't gotten this to work, or you can do some kind of ugly construction like:\naudio = numpy.fromfile('/dev/dsp'...\n\nbut I guess you still need to use ossaudiodev to set up the sampling rate, format, etc. first.\n" ]
[ 2, 2, 1 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0000519851_audio_python.txt
Q: matplotlib: how to refresh figure.canvas I can't understand how to refresh FigureCanvasWxAgg instance. Here is the example: import wx import matplotlib from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.figure import Figure class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.NewId(), "Main") self.sizer = wx.BoxSizer(wx.VERTICAL) self.figure = Figure(figsize=(1,2)) self.axe = self.figure.add_subplot(111) self.figurecanvas = FigureCanvas(self, -1, self.figure) self.buttonPlot = wx.Button(self, wx.NewId(), "Plot") self.buttonClear = wx.Button(self, wx.NewId(), "Clear") self.sizer.Add(self.figurecanvas, proportion=1, border=5, flag=wx.ALL | wx.EXPAND) self.sizer.Add(self.buttonPlot, proportion=0, border=2, flag=wx.ALL) self.sizer.Add(self.buttonClear, proportion=0, border=2, flag=wx.ALL) self.SetSizer(self.sizer) self.figurecanvas.Bind(wx.EVT_LEFT_DCLICK, self.on_dclick) self.buttonPlot.Bind(wx.EVT_BUTTON, self.on_button_plot) self.buttonClear.Bind(wx.EVT_BUTTON, self.on_button_clear) self.subframe_opened = False def on_dclick(self, evt): self.subframe = SubFrame(self, self.figure) self.subframe.Show(True) self.subframe_opened = True def on_button_plot(self, evt): self.axe.plot(range(10), color='green') self.figurecanvas.draw() def on_button_clear(self, evt): if self.subframe_opened: self.subframe.Close() self.figure.set_canvas(self.figurecanvas) self.axe.clear() self.figurecanvas.draw() class SubFrame(wx.Frame): def __init__(self, parent, figure): wx.Frame.__init__(self, parent, wx.NewId(), "Sub") self.sizer = wx.BoxSizer(wx.VERTICAL) self.figurecanvas = FigureCanvas(self, -1, figure) self.sizer.Add(self.figurecanvas, proportion=1, border=5, flag=wx.ALL | wx.EXPAND) self.SetSizer(self.sizer) self.Bind(wx.EVT_CLOSE, self.on_close) def on_close(self, evt): self.GetParent().subframe_opened = False evt.Skip() class MyApp(wx.App): def OnInit(self): frame = MainFrame() frame.Show(True) self.SetTopWindow(frame) return True app = MyApp(0) app.MainLoop() I'm interested in the following sequence of operations: run a script resize the main frame press Plot button double click on plot press Clear button Now I get a mess on main frame plot. If I resize the frame it redraws properly. My question is what should I add to my code to do that without resizing? By a "mess" I mean something like this: http://img227.imageshack.us/img227/5407/mess.png Thanks in advance. A: As I said in the comments, I don't think that the figure canvas refresh is your problem, in fact I think it's doing exactly what it's supposed to (redrawing itself based on it's last state [ie as it was in your subplot]). I think your problem is more that the wxFrame is not refreshing. The easiest way to fix that would be to make it resize itself on your "Clear" event. Something like: def on_button_clear(self, evt): if self.subframe_opened: self.subframe.Close() self.figure.set_canvas(self.figurecanvas) self.axe.clear() self.figurecanvas.draw() self.SetSize((self.Size[0],self.figurecanvas.Size[1])) The set size would cause the frame and all the controls it contains to be redrawn. That said, I think sharing your figure between the two figurecanvas is dangerous. I was able to produce some serious errors by clicking/resizing things in different combinations. On occasion your figure would be garbage collected when the subframe was closed, making it unavailable to your main frame.
matplotlib: how to refresh figure.canvas
I can't understand how to refresh FigureCanvasWxAgg instance. Here is the example: import wx import matplotlib from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.figure import Figure class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.NewId(), "Main") self.sizer = wx.BoxSizer(wx.VERTICAL) self.figure = Figure(figsize=(1,2)) self.axe = self.figure.add_subplot(111) self.figurecanvas = FigureCanvas(self, -1, self.figure) self.buttonPlot = wx.Button(self, wx.NewId(), "Plot") self.buttonClear = wx.Button(self, wx.NewId(), "Clear") self.sizer.Add(self.figurecanvas, proportion=1, border=5, flag=wx.ALL | wx.EXPAND) self.sizer.Add(self.buttonPlot, proportion=0, border=2, flag=wx.ALL) self.sizer.Add(self.buttonClear, proportion=0, border=2, flag=wx.ALL) self.SetSizer(self.sizer) self.figurecanvas.Bind(wx.EVT_LEFT_DCLICK, self.on_dclick) self.buttonPlot.Bind(wx.EVT_BUTTON, self.on_button_plot) self.buttonClear.Bind(wx.EVT_BUTTON, self.on_button_clear) self.subframe_opened = False def on_dclick(self, evt): self.subframe = SubFrame(self, self.figure) self.subframe.Show(True) self.subframe_opened = True def on_button_plot(self, evt): self.axe.plot(range(10), color='green') self.figurecanvas.draw() def on_button_clear(self, evt): if self.subframe_opened: self.subframe.Close() self.figure.set_canvas(self.figurecanvas) self.axe.clear() self.figurecanvas.draw() class SubFrame(wx.Frame): def __init__(self, parent, figure): wx.Frame.__init__(self, parent, wx.NewId(), "Sub") self.sizer = wx.BoxSizer(wx.VERTICAL) self.figurecanvas = FigureCanvas(self, -1, figure) self.sizer.Add(self.figurecanvas, proportion=1, border=5, flag=wx.ALL | wx.EXPAND) self.SetSizer(self.sizer) self.Bind(wx.EVT_CLOSE, self.on_close) def on_close(self, evt): self.GetParent().subframe_opened = False evt.Skip() class MyApp(wx.App): def OnInit(self): frame = MainFrame() frame.Show(True) self.SetTopWindow(frame) return True app = MyApp(0) app.MainLoop() I'm interested in the following sequence of operations: run a script resize the main frame press Plot button double click on plot press Clear button Now I get a mess on main frame plot. If I resize the frame it redraws properly. My question is what should I add to my code to do that without resizing? By a "mess" I mean something like this: http://img227.imageshack.us/img227/5407/mess.png Thanks in advance.
[ "As I said in the comments, I don't think that the figure canvas refresh is your problem, in fact I think it's doing exactly what it's supposed to (redrawing itself based on it's last state [ie as it was in your subplot]). I think your problem is more that the wxFrame is not refreshing.\nThe easiest way to fix that would be to make it resize itself on your \"Clear\" event. Something like:\ndef on_button_clear(self, evt):\n if self.subframe_opened:\n self.subframe.Close()\n self.figure.set_canvas(self.figurecanvas)\n self.axe.clear()\n self.figurecanvas.draw() \n self.SetSize((self.Size[0],self.figurecanvas.Size[1]))\n\nThe set size would cause the frame and all the controls it contains to be redrawn.\nThat said, I think sharing your figure between the two figurecanvas is dangerous. I was able to produce some serious errors by clicking/resizing things in different combinations. On occasion your figure would be garbage collected when the subframe was closed, making it unavailable to your main frame.\n" ]
[ 16 ]
[]
[]
[ "matplotlib", "python", "wxpython" ]
stackoverflow_0002441906_matplotlib_python_wxpython.txt
Q: How can we change a wx.MenuBar background and foreground colour using wxpython? I want to change the wxpython menubar colours. How can I do it? A: There are two ways Hard way , write your own custom menu bar from PyControl, position it at top of window, and create popup windows for submenus. Easier way: you can use win32api to change system menu colors for your app. Here is an example showing that http://code.activestate.com/recipes/440507-changing-the-background-color-of-the-menu-bar-in-a/
How can we change a wx.MenuBar background and foreground colour using wxpython?
I want to change the wxpython menubar colours. How can I do it?
[ "There are two ways\n\nHard way , write your own custom menu bar from PyControl, position it at top of window, and create popup windows for submenus.\nEasier way: you can use win32api to change system menu colors for your app. Here is an example showing that http://code.activestate.com/recipes/440507-changing-the-background-color-of-the-menu-bar-in-a/\n\n" ]
[ 4 ]
[ "don't think it's doable -- it defaults to the platform's native look\n" ]
[ -1 ]
[ "python", "wxpython" ]
stackoverflow_0002439708_python_wxpython.txt
Q: Is it possible to put a wx.window (frame/panel) over a wx.MenuBar? I want to know if it's possible to put a frame or a panel over a menubar using wxpython? Thanks in advance! A: Your only chance is to write some Custom Menu, which could be bit difficult but doable. So basically instead of using system menu etc, you create windows inside your main frame which look like menu.
Is it possible to put a wx.window (frame/panel) over a wx.MenuBar?
I want to know if it's possible to put a frame or a panel over a menubar using wxpython? Thanks in advance!
[ "Your only chance is to write some Custom Menu, which could be bit difficult but doable. So basically instead of using system menu etc, you create windows inside your main frame which look like menu.\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002439677_python_wxpython.txt
Q: python FancyURLopener timeout is there a way to set connection timeout for FancyURLopener()? I'm using FancyURLopener.retrieve() to download a file, but sometimes it just stucks and that's all... I think this is because it's still trying to connect and it's not possible. So is there a way to set that timeout? Thanks for every reply A: If you want to use retrieve() with a timeout, you can set it in the socket module. import socket socket.setdefaulttimeout(5) Source: http://docs.python.org/py3k/howto/urllib2.html#sockets-and-layers A: Sorry, solved. I didn't realize that I could use something like this... fileName = string.split(url, '/')[-1] data = urllib2.urlopen(url, timeout = 5) //Connection timeout set to 5 secs newF = open(os.path.join(os.getcwd(), fileName), "wb") newF.write(data.read()) newF.close()
python FancyURLopener timeout
is there a way to set connection timeout for FancyURLopener()? I'm using FancyURLopener.retrieve() to download a file, but sometimes it just stucks and that's all... I think this is because it's still trying to connect and it's not possible. So is there a way to set that timeout? Thanks for every reply
[ "If you want to use retrieve() with a timeout, you can set it in the socket module.\nimport socket\nsocket.setdefaulttimeout(5)\n\nSource: http://docs.python.org/py3k/howto/urllib2.html#sockets-and-layers\n", "Sorry, solved.\nI didn't realize that I could use something like this...\nfileName = string.split(url, '/')[-1]\ndata = urllib2.urlopen(url, timeout = 5) //Connection timeout set to 5 secs\nnewF = open(os.path.join(os.getcwd(), fileName), \"wb\")\nnewF.write(data.read())\nnewF.close()\n\n" ]
[ 4, 1 ]
[]
[]
[ "python", "timeout", "urllib" ]
stackoverflow_0002464020_python_timeout_urllib.txt
Q: Absolute path of a file object This has been discussed on StackOverflow before - I am trying to find a good way to find the absolute path of a file object, but I need it to be robust to os.chdir(), so cannot use f = file('test') os.path.abspath(f.name) Instead, I was wondering whether the following is a good solution - basically extending the file class so that on opening, the absolute path of the file is saved: class File(file): def __init__(self, filename, *args, **kwargs): self.abspath = os.path.abspath(filename) file.__init__(self, filename, *args, **kwargs) Then one can do f = File('test','rb') os.chdir('some_directory') f.abspath # absolute path can be accessed like this Are there any risks with doing this? A: One significant risk is that, once the file is open, the process is dealing with that file by its file descriptor, not its path. On many operating systems, the file's path can be changed by some other process (by a mv operation in an unrelated process, say) and the file descriptor is still valid and refers to the same file. I often take advantage of this by, for example, beginning a download of a large file, then realising the destination file isn't where I want it to be, and hopping to a separate shell and moving it to the right location – while the download continues uninterrupted. So it is a bad idea to depend on the path remaining the same for the life of the process, when there's no such guarantee given by the operating system. A: It depends on what you need it for. As long as you understand the limitations--someone might move, rename, or hard-link the file in the interim--there are plenty of appropriate uses for this. You may want to delete the file when you're done with it or if something goes wrong while writing it (eg. gcc does this when writing files): f = File(path, "w+") try: ... except: try: os.unlink(f.abspath) except OSError: # nothing we can do if this fails pass raise If you just want to be able to identify the file in user messages, there's already file.name. It's impossible to use this (reliably) for anything else, unfortunately; there's no way to distinguish between a filename "<stdin>" and sys.stdin, for example. (You really shouldn't have to derive from a builtin class just to add attributes to it; that's just an ugly inconsistent quirk of Python...)
Absolute path of a file object
This has been discussed on StackOverflow before - I am trying to find a good way to find the absolute path of a file object, but I need it to be robust to os.chdir(), so cannot use f = file('test') os.path.abspath(f.name) Instead, I was wondering whether the following is a good solution - basically extending the file class so that on opening, the absolute path of the file is saved: class File(file): def __init__(self, filename, *args, **kwargs): self.abspath = os.path.abspath(filename) file.__init__(self, filename, *args, **kwargs) Then one can do f = File('test','rb') os.chdir('some_directory') f.abspath # absolute path can be accessed like this Are there any risks with doing this?
[ "One significant risk is that, once the file is open, the process is dealing with that file by its file descriptor, not its path. On many operating systems, the file's path can be changed by some other process (by a mv operation in an unrelated process, say) and the file descriptor is still valid and refers to the same file.\nI often take advantage of this by, for example, beginning a download of a large file, then realising the destination file isn't where I want it to be, and hopping to a separate shell and moving it to the right location – while the download continues uninterrupted.\nSo it is a bad idea to depend on the path remaining the same for the life of the process, when there's no such guarantee given by the operating system.\n", "It depends on what you need it for.\nAs long as you understand the limitations--someone might move, rename, or hard-link the file in the interim--there are plenty of appropriate uses for this. You may want to delete the file when you're done with it or if something goes wrong while writing it (eg. gcc does this when writing files):\nf = File(path, \"w+\")\ntry:\n ...\nexcept:\n try:\n os.unlink(f.abspath)\n except OSError: # nothing we can do if this fails\n pass\n raise\n\nIf you just want to be able to identify the file in user messages, there's already file.name. It's impossible to use this (reliably) for anything else, unfortunately; there's no way to distinguish between a filename \"<stdin>\" and sys.stdin, for example.\n(You really shouldn't have to derive from a builtin class just to add attributes to it; that's just an ugly inconsistent quirk of Python...)\n" ]
[ 14, 1 ]
[]
[]
[ "file", "filesystems", "python" ]
stackoverflow_0002458676_file_filesystems_python.txt
Q: Extract strings in python Basically, I want to extract the strings "AAA", "BBB", "CCC", "DDD" from a text file... ...... (other text goes here)..... <TD align="left" class=texttd><font class='textfont'>AAA</font></TD> ..... (useless text here)..... <TD align="left" class=texttd><font class='textfont'>BBB</font></TD> ....(more text)..... <TD align="left" class=texttd><font class='textfont'>CCC</font></TD> <TD align="left" class=texttd><font class='textfont'>DDD</font></TD> ......(more text)..... I want something like if I do:- data = foo("file.txt") I get:- data = ['AAA','BBB','CCC','DDD'] What is the best possible way? My file is not big... Basically, I want to extract "remaining upload data transfer" from this file which in HTML looks like THIS A: You could write a REGEX but it would be "parsing" the HTML to some extent. The problem with writing regular expressions for HTML is HTML is a mess. It's rarely perfect and this causes problems when you rely on it for data. I would personally use BeautifulSoup. It does do more than you're asking but also at superfraction of the effort. A: You want BeautifulSoup: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(your_file) soup.find("font", "textfont") A: def foo(): input_file = open("myfile.txt", 'r') input = ''.join(input_file.readlines()) looking_for = ['AAA', 'BBB', 'CCC', 'DDD'] have = [] for thing in looking_for: if thing in input: have.append(thing) return have A: In a case like this it's, attempt regex for it ( which will be really had ), use a prewritten library, or do it your self with a f = open() f.read() and your own parser. A: If you just want to get the data from inside all of the tags in the HTML document, while dropping all the tags themselves, you could do something like this: import HTMLParser class DataOnlyParser(HTMLParser.HTMLParser): def parse(self, text): self.result = [] self.feed(text) self.close() return self.result def handle_data(self, data): data = data.strip() if data: self.result.append(data) p = DataOnlyParser() data = """ <TD align="left" class=texttd><font class='textfont'>AAA</font></TD> <TD align="left" class=texttd><font class='textfont'>BBB</font></TD> <TD align="left" class=texttd><font class='textfont'>CCC</font></TD> <TD align="left" class=texttd><font class='textfont'>DDD</font></TD> """ print p.parse(data) # ['AAA', 'BBB', 'CCC', 'DDD'] If your selection criteria is more complex though, and/or if the input is malformed, you'd probably be better off with a library like lxml. You do NOT want to use regular expressions to "parse" html. See here.
Extract strings in python
Basically, I want to extract the strings "AAA", "BBB", "CCC", "DDD" from a text file... ...... (other text goes here)..... <TD align="left" class=texttd><font class='textfont'>AAA</font></TD> ..... (useless text here)..... <TD align="left" class=texttd><font class='textfont'>BBB</font></TD> ....(more text)..... <TD align="left" class=texttd><font class='textfont'>CCC</font></TD> <TD align="left" class=texttd><font class='textfont'>DDD</font></TD> ......(more text)..... I want something like if I do:- data = foo("file.txt") I get:- data = ['AAA','BBB','CCC','DDD'] What is the best possible way? My file is not big... Basically, I want to extract "remaining upload data transfer" from this file which in HTML looks like THIS
[ "You could write a REGEX but it would be \"parsing\" the HTML to some extent. The problem with writing regular expressions for HTML is HTML is a mess. It's rarely perfect and this causes problems when you rely on it for data.\nI would personally use BeautifulSoup. It does do more than you're asking but also at superfraction of the effort.\n", "You want BeautifulSoup:\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(your_file)\n\nsoup.find(\"font\", \"textfont\")\n\n", "def foo():\n input_file = open(\"myfile.txt\", 'r')\n input = ''.join(input_file.readlines())\n\n looking_for = ['AAA', 'BBB', 'CCC', 'DDD']\n have = []\n\n for thing in looking_for:\n if thing in input:\n have.append(thing)\n return have\n\n", "In a case like this it's, attempt regex for it ( which will be really had ), use a prewritten library, or do it your self with a f = open() f.read() and your own parser.\n", "If you just want to get the data from inside all of the tags in the HTML document, while dropping all the tags themselves, you could do something like this:\nimport HTMLParser\n\nclass DataOnlyParser(HTMLParser.HTMLParser):\n def parse(self, text):\n self.result = []\n self.feed(text)\n self.close()\n return self.result\n\n def handle_data(self, data):\n data = data.strip()\n if data:\n self.result.append(data)\n\np = DataOnlyParser()\n\ndata = \"\"\"\n<TD align=\"left\" class=texttd><font class='textfont'>AAA</font></TD>\n<TD align=\"left\" class=texttd><font class='textfont'>BBB</font></TD>\n<TD align=\"left\" class=texttd><font class='textfont'>CCC</font></TD>\n<TD align=\"left\" class=texttd><font class='textfont'>DDD</font></TD>\n\"\"\"\n\nprint p.parse(data)\n# ['AAA', 'BBB', 'CCC', 'DDD']\n\nIf your selection criteria is more complex though, and/or if the input is malformed, you'd probably be better off with a library like lxml.\nYou do NOT want to use regular expressions to \"parse\" html. See here.\n" ]
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "string", "text_extraction" ]
stackoverflow_0002464482_python_string_text_extraction.txt
Q: Print Tuple Index in Python This question falls into the "yes - this works, yes - this is ugly, yes - there is probably a better way" category. I want to use a regular expression to pull groups out of a match and then print the group number and the group value. It is to show someone how regular expressions work and to keep track of the values of each group. The code that works is: import re FundTypeGroups = re.match("([A-Z]0)(\d)([A-Z])","G02A").groups() print FundTypeGroups for FundTypeGroup in FundTypeGroups: print "%s: %s" % (FundTypeGroups.index(FundTypeGroup), FundTypeGroup) Is there a better way to print the index of each tuple entry? A: for index, group in enumerate(FundTypeGroups): print "%s: %s" % (index, group) (and the variables should not start with a capital letter...)
Print Tuple Index in Python
This question falls into the "yes - this works, yes - this is ugly, yes - there is probably a better way" category. I want to use a regular expression to pull groups out of a match and then print the group number and the group value. It is to show someone how regular expressions work and to keep track of the values of each group. The code that works is: import re FundTypeGroups = re.match("([A-Z]0)(\d)([A-Z])","G02A").groups() print FundTypeGroups for FundTypeGroup in FundTypeGroups: print "%s: %s" % (FundTypeGroups.index(FundTypeGroup), FundTypeGroup) Is there a better way to print the index of each tuple entry?
[ " for index, group in enumerate(FundTypeGroups):\n print \"%s: %s\" % (index, group)\n\n(and the variables should not start with a capital letter...)\n" ]
[ 3 ]
[]
[]
[ "indexing", "python", "tuples" ]
stackoverflow_0002464808_indexing_python_tuples.txt
Q: How to implement a master/watchdog script in python? I need it to open 10 processes, and each time one of them finishes I want to wait few seconds and start another one. It seems pretty simple, but somehow I can't get it to work. A: I'm not 100% clear on what you're trying to accomplish, but have you looked at the multiprocessing module, specifically using a pool of workers? A: I've done this same thing to process web statistics using a semaphore. Essentially, as processes are created, the semaphore is incremented. When they exit, it's decremented. The creation process is blocked when the semaphore blocks. This actually fires off threads, which run external processes down execution path a bit. Here's an example. thread_sem = threading.Semaphore(int(cfg.maxthreads)) for k,v in log_data.items(): thread_list.append(ProcessorThread(int(k), v, thread_sem)) thread_list[-1].start() And then in the constructor for ProcessorThread, I do this: def __init__(self, siteid, data, lock_object): threading.Thread.__init__(self) self.setDaemon(False) self.lock_object = lock_object self.data = data self.siteid = siteid self.lock_object.acquire() When the thread finishes it's task (whether successfully or not), the lock_object is released which allows for another process to begin. HTH
How to implement a master/watchdog script in python?
I need it to open 10 processes, and each time one of them finishes I want to wait few seconds and start another one. It seems pretty simple, but somehow I can't get it to work.
[ "I'm not 100% clear on what you're trying to accomplish, but have you looked at the multiprocessing module, specifically using a pool of workers?\n", "I've done this same thing to process web statistics using a semaphore. Essentially, as processes are created, the semaphore is incremented. When they exit, it's decremented. The creation process is blocked when the semaphore blocks. \nThis actually fires off threads, which run external processes down execution path a bit.\nHere's an example.\n\n\n thread_sem = threading.Semaphore(int(cfg.maxthreads))\n for k,v in log_data.items():\n thread_list.append(ProcessorThread(int(k), v, thread_sem))\n thread_list[-1].start()\n\n\nAnd then in the constructor for ProcessorThread, I do this:\n\n\n def __init__(self, siteid, data, lock_object):\n threading.Thread.__init__(self)\n self.setDaemon(False)\n self.lock_object = lock_object\n self.data = data\n self.siteid = siteid\n self.lock_object.acquire()\n\n\nWhen the thread finishes it's task (whether successfully or not), the lock_object is released which allows for another process to begin.\nHTH\n" ]
[ 2, 1 ]
[]
[]
[ "python", "subprocess", "watchdog" ]
stackoverflow_0002464704_python_subprocess_watchdog.txt
Q: Python or matplotlib limitation error I wrote an algorithm using python and matplotlib that generates histograms from some text input data. When the number of data input is approx. greater than 15000, I get in the (append) line of my code: mydata = [] for i in range(len(data)): mydata.append(string.atof(data[i])) the error: Traceback (most recent call last): File "get_histogram_picture.py", line 25, in <module> mydata.append(string.atof(data[i])) File "/usr/lib/python2.6/string.py", line 388, in atof return _float(s) ValueError: invalid literal for float(): -a can it be an error in python ? What is the solution ? Thanks A: That's a data parsing error: >>> float("-a") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for float(): -a Python data structure size if only limited by the available memory.
Python or matplotlib limitation error
I wrote an algorithm using python and matplotlib that generates histograms from some text input data. When the number of data input is approx. greater than 15000, I get in the (append) line of my code: mydata = [] for i in range(len(data)): mydata.append(string.atof(data[i])) the error: Traceback (most recent call last): File "get_histogram_picture.py", line 25, in <module> mydata.append(string.atof(data[i])) File "/usr/lib/python2.6/string.py", line 388, in atof return _float(s) ValueError: invalid literal for float(): -a can it be an error in python ? What is the solution ? Thanks
[ "That's a data parsing error:\n>>> float(\"-a\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: invalid literal for float(): -a\n\nPython data structure size if only limited by the available memory.\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002464863_matplotlib_python.txt
Q: Python: Matching & Stripping port number from socket data I have data coming in to a python server via a socket. Within this data is the string '<port>80</port>' or which ever port is being used. I wish to extract the port number into a variable. The data coming in is not XML, I just used the tag approach to identifying data for future XML use if needed. I do not wish to use an XML python library, but simply use something like regexp and strings. What would you recommend is the best way to match and strip this data? I am currently using this code with no luck: p = re.compile('<port>\w</port>') m = p.search(data) print m Thank you :) A: Regex can't parse XML and shouldn't be used to parse fake XML. You should do one of Use a serialization method that is nicer to work with to start with, such as JSON or an ini file with the ConfigParser module. Really use XML and not something that just sort of looks like XML and really parse it with something like lxml.etree. Just store the number in a file if this is the entirety of your configuration. This solution isn't really easier than just using JSON or something, but it's better than the current one. Implementing a bad solution now for future needs that you have no way of defining or accurately predicting is always a bad approach. You will be kept busy enough trying to write and maintain software now that there is no good reason to try to satisfy unknown future needs. I have never seen a case where "I'll put this in for later" has led to less headache later on, especially when I put it in by doing something completely wrong. YAGNI! As to what's wrong with your snippet other than using an entirely wrong approach, angled brackets have a meaning in regex. A: Though Mike Graham is correct, using regex for xml is not 'recommended', the following will work: (I have defined searchType as 'd' for numerals) searchStr = 'port' if searchType == 'd': retPattern = '(<%s>)(\d+)(</%s>)' else: retPattern = '(<%s>)(.+?)(</%s>)' searchPattern = re.compile(retPattern % (searchStr, searchStr)) found = searchPattern.search(searchStr) retVal = found.group(2) (note the complete lack of error checking, that is left as an exercise for the user)
Python: Matching & Stripping port number from socket data
I have data coming in to a python server via a socket. Within this data is the string '<port>80</port>' or which ever port is being used. I wish to extract the port number into a variable. The data coming in is not XML, I just used the tag approach to identifying data for future XML use if needed. I do not wish to use an XML python library, but simply use something like regexp and strings. What would you recommend is the best way to match and strip this data? I am currently using this code with no luck: p = re.compile('<port>\w</port>') m = p.search(data) print m Thank you :)
[ "Regex can't parse XML and shouldn't be used to parse fake XML. You should do one of\n\nUse a serialization method that is nicer to work with to start with, such as JSON or an ini file with the ConfigParser module.\nReally use XML and not something that just sort of looks like XML and really parse it with something like lxml.etree.\nJust store the number in a file if this is the entirety of your configuration. This solution isn't really easier than just using JSON or something, but it's better than the current one.\n\nImplementing a bad solution now for future needs that you have no way of defining or accurately predicting is always a bad approach. You will be kept busy enough trying to write and maintain software now that there is no good reason to try to satisfy unknown future needs. I have never seen a case where \"I'll put this in for later\" has led to less headache later on, especially when I put it in by doing something completely wrong. YAGNI!\nAs to what's wrong with your snippet other than using an entirely wrong approach, angled brackets have a meaning in regex.\n", "Though Mike Graham is correct, using regex for xml is not 'recommended', the following will work:\n(I have defined searchType as 'd' for numerals)\nsearchStr = 'port'\n\nif searchType == 'd':\n retPattern = '(<%s>)(\\d+)(</%s>)'\nelse:\n retPattern = '(<%s>)(.+?)(</%s>)'\n\nsearchPattern = re.compile(retPattern % (searchStr, searchStr))\nfound = searchPattern.search(searchStr)\nretVal = found.group(2)\n\n(note the complete lack of error checking, that is left as an exercise for the user)\n" ]
[ 1, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002464670_python_sockets.txt
Q: Working with multiple input and output files in Python I need to open multiple files (2 input and 2 output files), do complex manipulations on the lines from input files and then append results at the end of 2 output files. I am currently using the following approach: in_1 = open(input_1) in_2 = open(input_2) out_1 = open(output_1, "w") out_2 = open(output_2, "w") # Read one line from each 'in_' file # Do many operations on the DNA sequences included in the input files # Append one line to each 'out_' file in_1.close() in_2.close() out_1.close() out_2.close() The files are huge (each potentially approaching 1Go, that is why I am reading through these input files one at a time. I am guessing that this is not a very Pythonic way to do things. :) Would using the following form good? with open("file1") as f1: with open("file2") as f2: with open("file3") as f3: with open("file4") as f4: # Read one line from each 'in_' file # Do many operations on the DNA sequences... # Append one line to each 'out_' file If yes, could I do this while avoiding the highly indented code (commented part, which may itself contain indented lines. Unless, as suggested, I use appropriately defined functions beforehand)? Thanks for the insights! A: contextlib.nested() allows you to chain multiple context managers in a single statement: with contextlib.nested(open(...), open(...), ...) as (in_1, in_2, ...): ....
Working with multiple input and output files in Python
I need to open multiple files (2 input and 2 output files), do complex manipulations on the lines from input files and then append results at the end of 2 output files. I am currently using the following approach: in_1 = open(input_1) in_2 = open(input_2) out_1 = open(output_1, "w") out_2 = open(output_2, "w") # Read one line from each 'in_' file # Do many operations on the DNA sequences included in the input files # Append one line to each 'out_' file in_1.close() in_2.close() out_1.close() out_2.close() The files are huge (each potentially approaching 1Go, that is why I am reading through these input files one at a time. I am guessing that this is not a very Pythonic way to do things. :) Would using the following form good? with open("file1") as f1: with open("file2") as f2: with open("file3") as f3: with open("file4") as f4: # Read one line from each 'in_' file # Do many operations on the DNA sequences... # Append one line to each 'out_' file If yes, could I do this while avoiding the highly indented code (commented part, which may itself contain indented lines. Unless, as suggested, I use appropriately defined functions beforehand)? Thanks for the insights!
[ "contextlib.nested() allows you to chain multiple context managers in a single statement:\nwith contextlib.nested(open(...), open(...), ...) as (in_1, in_2, ...):\n ....\n\n" ]
[ 5 ]
[]
[]
[ "file", "python" ]
stackoverflow_0002465130_file_python.txt
Q: Verify key is correct using pyCrypto AES decryption How do I verify the correct key is being used to decrypt AES encrypted data using pyCrypto AES? cipher = AES.new(key, AES.MODE_CFB) cipher.decrypt(s) If an incorrect key is used, it still attempts to decrypt the data, obfuscating it more. Is there any test I can do to prove the data is being decrypted to the original state? A: You could use Cipher-based Message Authentication Code (CMAC) or maybe an HMAC (Hash-based Message Authentication Code) (if you have a hash function available). There are defined ways to combine encryption and authentication. See Authenticated Encryption (AE). A: I don't believe you can [tell if the key is correct], with the AES context alone. i.e. you can't, other than by verifying the format and/or some message digest value for the clear text after it is decoded, which implies that you know such structure or message digest. Although this is merely a consequence of the way the algorithm/protocol is established, one of the benefits of this is that this makes brute-force attacks on such ciphers more difficult because one needs to take the time and decode at least part of the message and also to pass it through a clear-text detector. The clear-text detector is some logic that has a-priori/guessed understanding of the nature of the cleartext, and which can tell if the data meets this expectation; for example a simple detector may check that the first 20 bytes are US ASCII). This is particularly useful with multiple encoding schemes like triple DES where one has no clue (well cryptanalysis geniuses may have a mild idea...) of what the intermediate "clear-texts" look like. Edit: to answer OP's questions in the notes Yes, if you are unsure of the key, you need to make a copy of the ciphertext before attempting to get it decoded. It will return as real gibberish (and not easily reversible, if at all) if it is decoded with the wrong key. To introduce a way of detecting the validity of the decoded message, for both binary and ASCII/text messages, you can use a variation on the the following "envellope" concept. Note: This may [mildly] weaken the strength of your cryptographic setup. This assumes that you have control or collaboration over the encoding process as well. This works for both ASCII and binary content The idea is simply to add a prefix (a "header"), and possibly a suffix ("trailer") to the message. To be cryptographically safer such a prefix should be long enough (say 500 bytes?) and have most of its content be random in nature. You then would need to insert the actual message in this "enveloppe" and assert the validity/integrity of the envelope after decription. Tentative example: 17 random bytes 2 bytes length of this header (allows to have a variable length header) 1 byte offset to "fingerprint" x random bytes fingerprint = a short binary (preferably) or ascii constant text "MyDataIsOk" [optionally: length of the payload and/or a CRC / MD5 / digest-of-sort for it] y random bytes followed by the actual message A simplistic (but a bit "dangerous" for the crypto) is simply to add, say, "MyDataIsGood123ABC" in front of the data. At decryption time you'd verify that the decrypted stream starts with these 16 bytes bytes, and you'd remove them to get the actual message. A: Take a look at this blog post, it includes example code for doing what you need (ie. CRC) Python symmetric encryption with CRC
Verify key is correct using pyCrypto AES decryption
How do I verify the correct key is being used to decrypt AES encrypted data using pyCrypto AES? cipher = AES.new(key, AES.MODE_CFB) cipher.decrypt(s) If an incorrect key is used, it still attempts to decrypt the data, obfuscating it more. Is there any test I can do to prove the data is being decrypted to the original state?
[ "You could use Cipher-based Message Authentication Code (CMAC) or maybe an HMAC (Hash-based Message Authentication Code) (if you have a hash function available).\nThere are defined ways to combine encryption and authentication. See Authenticated Encryption (AE).\n", "I don't believe you can [tell if the key is correct], with the AES context alone.\ni.e. you can't, other than by verifying the format and/or some message digest value for the clear text after it is decoded, which implies that you know such structure or message digest.\nAlthough this is merely a consequence of the way the algorithm/protocol is established, one of the benefits of this is that this makes brute-force attacks on such ciphers more difficult because one needs to take the time and decode at least part of the message and also to pass it through a clear-text detector. The clear-text detector is some logic that has a-priori/guessed understanding of the nature of the cleartext, and which can tell if the data meets this expectation; for example a simple detector may check that the first 20 bytes are US ASCII). This is particularly useful with multiple encoding schemes like triple DES where one has no clue (well cryptanalysis geniuses may have a mild idea...) of what the intermediate \"clear-texts\" look like.\nEdit: to answer OP's questions in the notes\nYes, if you are unsure of the key, you need to make a copy of the ciphertext before attempting to get it decoded. It will return as real gibberish (and not easily reversible, if at all) if it is decoded with the wrong key.\nTo introduce a way of detecting the validity of the decoded message, for both binary and ASCII/text messages, you can use a variation on the the following \"envellope\" concept.\nNote: This may [mildly] weaken the strength of your cryptographic setup.\nThis assumes that you have control or collaboration over the encoding process as well. This works for both ASCII and binary content\nThe idea is simply to add a prefix (a \"header\"), and possibly a suffix (\"trailer\") to the message. To be cryptographically safer such a prefix should be long enough (say 500 bytes?) and have most of its content be random in nature. You then would need to insert the actual message in this \"enveloppe\" and assert the validity/integrity of the envelope after decription. Tentative example:\n\n17 random bytes\n2 bytes length of this header (allows to have a variable length header)\n1 byte offset to \"fingerprint\"\nx random bytes\nfingerprint = a short binary (preferably) or ascii constant text \"MyDataIsOk\"\n[optionally: length of the payload and/or a CRC / MD5 / digest-of-sort for it]\ny random bytes\nfollowed by the actual message\n\nA simplistic (but a bit \"dangerous\" for the crypto) is simply to add, say, \"MyDataIsGood123ABC\" in front of the data. At decryption time you'd verify that the decrypted stream starts with these 16 bytes bytes, and you'd remove them to get the actual message.\n", "Take a look at this blog post, it includes example code for doing what you need (ie. CRC)\nPython symmetric encryption with CRC\n" ]
[ 8, 2, 0 ]
[]
[]
[ "aes", "cryptography", "encryption", "python" ]
stackoverflow_0001652127_aes_cryptography_encryption_python.txt
Q: Capture output from a mysql select statement using python Using Python2.4 I want to capture output from a mysql command. One caveat is that I need to pipe the SQL statement using an echo. echo 'SELECT user FROM mysql.user;' | mysql I see example using call, os.system, popen but what is best to use for my version of python and capturing the output in a tuple. Thanks A: The subprocess module is the most flexible tool for running commands and controlling the input and output. The following runs a command and captures the output as a list of lines: import subprocess p = subprocess.Popen(['/bin/bash', '-c', "echo 'select user from mysql.user;' | mysql" ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) lines = [line for line in p.stdout] On Windows, bash -c would be replaced with cmd /c.
Capture output from a mysql select statement using python
Using Python2.4 I want to capture output from a mysql command. One caveat is that I need to pipe the SQL statement using an echo. echo 'SELECT user FROM mysql.user;' | mysql I see example using call, os.system, popen but what is best to use for my version of python and capturing the output in a tuple. Thanks
[ "The subprocess module is the most flexible tool for running commands and controlling the input and output. The following runs a command and captures the output as a list of lines:\nimport subprocess\n\np = subprocess.Popen(['/bin/bash', '-c', \"echo 'select user from mysql.user;' | mysql\" ],\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\nlines = [line for line in p.stdout]\n\nOn Windows, bash -c would be replaced with cmd /c.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002464792_python.txt
Q: python on usb stick Is there any free and open-source option to run python from an usb-stick on Windows system (i.e. python installed on an usb-stick ) and can run on any Windows system just by pluging-in the usb-stick? A: Try Portable Python.
python on usb stick
Is there any free and open-source option to run python from an usb-stick on Windows system (i.e. python installed on an usb-stick ) and can run on any Windows system just by pluging-in the usb-stick?
[ "Try Portable Python.\n" ]
[ 13 ]
[]
[]
[ "portable_applications", "python" ]
stackoverflow_0002465593_portable_applications_python.txt
Q: Django file upload failing occasionally I am trying to port my first Django 1.0.2 application to run on OSX/Leopard with Apache + mod_python 3.3.1 + python 2.6.1 (all running in 64-bit mode) and I am experiencing an occasional error when uploading a file that was not present when testing with the Django development server. The code for the upload is similar to what described in the Django documentation: class UploadFileForm(forms.Form): file = forms.FileField() description = forms.CharField(max_length=100) notifygroup = forms.BooleanField(label='Notify Group?', required=False) def upload_file(request, date, meetingid ): print date, meetingid if request.method == 'POST': print 'before reloading the form...' form = UploadFileForm(request.POST, request.FILES) print 'after reloading the form' if form.is_valid(): try: handle_uploaded_file(request.FILES['file'], request.REQUEST['date'], request.REQUEST['description'], form.cleaned_data['notifygroup'], meetingid ) except: return render_to_response('uploaded.html', { 'message': 'Error! File not uploaded!' }) return HttpResponseRedirect('/myapp/uploaded/') else: form = UploadFileForm() return render_to_response('upload.html', {'form': form, 'date':date, 'meetingid':meetingid}) This code normally works correctly, but sometimes (say, once every 10 uploads) and after a fairly long waiting time, it fails with the following error: IOError at /myapp/upload/2009-01-03/1 Client read error (Timeout?) Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Exception Type: IOError Exception Value: Client read error (Timeout?) Exception Location: /Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py in read, line 406 Python Executable: /usr/sbin/httpd Python Version: 2.6.1 Python Path: ['/djangoapps/myapp/', '/djangoapps/', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python26.zip', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-darwin', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-tk', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-old', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages'] Server time: Sun, 4 Jan 2009 22:42:04 +0100 Environment: Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Django Version: 1.0.2 final Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'myapp.application1'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 86. response = callback(request, *callback_args, **callback_kwargs) File "/djangoapps/myapp/../myapp/application1/views.py" in upload_file 137. form = UploadFileForm(request.POST, request.FILES) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _get_post 113. self._load_post_and_files() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _load_post_and_files 87. self._post, self._files = self.parse_file_upload(self.META, self._req) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/__init__.py" in parse_file_upload 124. return parser.parse() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parse 134. for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __iter__ 607. for sub_stream in boundarystream: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 421. return LazyStream(BoundaryIter(self._stream, self._boundary)) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __init__ 447. unused_char = self._stream.read(1) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 300. out = ''.join(parts()) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parts 293. chunk = self.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 315. output = self._producer.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 376. data = self.flo.read(self.chunk_size) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 406. return self._file.read(num_bytes) Exception Type: IOError at /myapp/upload/2009-01-03/1 Exception Value: Client read error (Timeout?) I tried to run everything using mod_wsgi and no difference. Does anybody know what am I doing wrong? Thanks in advance for your help! ppdo ===== Updated: Though I succeeded uploading large files (60+ MB), when it fails it fails with no evident relationship with the size of the upload, i.e. it fails also with 10kB files that have successfully been uploaded before. A: Using mod_wsgi made the problem go away for Firefox. Limiting my research to an interaction problem between Apache and Safari, I stumbled upon this bug report for Apache https://bugs.webkit.org/show_bug.cgi?id=5760 that describes something very similar to what is happening and it is apparently still open. Reading this gave me the idea to try and disable the keepalive and, though I need to test it more extensively, it seems the problem is gone. A simple: BrowserMatch "Safari" nokeepalive in the Apache configuration did the trick. A: I would chase down the exception value Client read error (Timeout?) this seems odd enough. Try reading this thread A: How large is the file? It may take long enough to upload that the upload script times out, so try increasing the execution time for that script. A: Long time unanswered here, but having experienced this myself and tried a few things to resolve it. It seems in my case, it happened if someone canceled a download (or lost connection) during an upload. You can try this yourself to see if this is what is causing the "IOError: request data read error" for you: upload a large enough file that you can unplug your ethernet cable from your computer or router. Wait a bit and see if you get the error. I do everytime!
Django file upload failing occasionally
I am trying to port my first Django 1.0.2 application to run on OSX/Leopard with Apache + mod_python 3.3.1 + python 2.6.1 (all running in 64-bit mode) and I am experiencing an occasional error when uploading a file that was not present when testing with the Django development server. The code for the upload is similar to what described in the Django documentation: class UploadFileForm(forms.Form): file = forms.FileField() description = forms.CharField(max_length=100) notifygroup = forms.BooleanField(label='Notify Group?', required=False) def upload_file(request, date, meetingid ): print date, meetingid if request.method == 'POST': print 'before reloading the form...' form = UploadFileForm(request.POST, request.FILES) print 'after reloading the form' if form.is_valid(): try: handle_uploaded_file(request.FILES['file'], request.REQUEST['date'], request.REQUEST['description'], form.cleaned_data['notifygroup'], meetingid ) except: return render_to_response('uploaded.html', { 'message': 'Error! File not uploaded!' }) return HttpResponseRedirect('/myapp/uploaded/') else: form = UploadFileForm() return render_to_response('upload.html', {'form': form, 'date':date, 'meetingid':meetingid}) This code normally works correctly, but sometimes (say, once every 10 uploads) and after a fairly long waiting time, it fails with the following error: IOError at /myapp/upload/2009-01-03/1 Client read error (Timeout?) Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Exception Type: IOError Exception Value: Client read error (Timeout?) Exception Location: /Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py in read, line 406 Python Executable: /usr/sbin/httpd Python Version: 2.6.1 Python Path: ['/djangoapps/myapp/', '/djangoapps/', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python26.zip', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-darwin', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-tk', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-old', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages'] Server time: Sun, 4 Jan 2009 22:42:04 +0100 Environment: Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Django Version: 1.0.2 final Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'myapp.application1'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 86. response = callback(request, *callback_args, **callback_kwargs) File "/djangoapps/myapp/../myapp/application1/views.py" in upload_file 137. form = UploadFileForm(request.POST, request.FILES) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _get_post 113. self._load_post_and_files() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _load_post_and_files 87. self._post, self._files = self.parse_file_upload(self.META, self._req) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/__init__.py" in parse_file_upload 124. return parser.parse() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parse 134. for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __iter__ 607. for sub_stream in boundarystream: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 421. return LazyStream(BoundaryIter(self._stream, self._boundary)) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __init__ 447. unused_char = self._stream.read(1) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 300. out = ''.join(parts()) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parts 293. chunk = self.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 315. output = self._producer.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 376. data = self.flo.read(self.chunk_size) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 406. return self._file.read(num_bytes) Exception Type: IOError at /myapp/upload/2009-01-03/1 Exception Value: Client read error (Timeout?) I tried to run everything using mod_wsgi and no difference. Does anybody know what am I doing wrong? Thanks in advance for your help! ppdo ===== Updated: Though I succeeded uploading large files (60+ MB), when it fails it fails with no evident relationship with the size of the upload, i.e. it fails also with 10kB files that have successfully been uploaded before.
[ "Using mod_wsgi made the problem go away for Firefox. \nLimiting my research to an interaction problem between Apache and Safari, I stumbled upon this bug report for Apache https://bugs.webkit.org/show_bug.cgi?id=5760 that describes something very similar to what is happening and it is apparently still open. Reading this gave me the idea to try and disable the keepalive and, though I need to test it more extensively, it seems the problem is gone.\nA simple:\nBrowserMatch \"Safari\" nokeepalive \nin the Apache configuration did the trick.\n", "I would chase down the exception value \nClient read error (Timeout?)\n\nthis seems odd enough. Try reading this thread\n", "How large is the file? It may take long enough to upload that the upload script times out, so try increasing the execution time for that script.\n", "Long time unanswered here, but having experienced this myself and tried a few things to resolve it. It seems in my case, it happened if someone canceled a download (or lost connection) during an upload.\nYou can try this yourself to see if this is what is causing the \"IOError: request data read error\" for you: upload a large enough file that you can unplug your ethernet cable from your computer or router. Wait a bit and see if you get the error. I do everytime!\n" ]
[ 8, 1, 0, 0 ]
[]
[]
[ "apache", "django", "python" ]
stackoverflow_0000411902_apache_django_python.txt
Q: Stani's python editor- change syntax coloring Looking at Stani's Python IDE, it definitely comes bundled with tons of useful features. Except it doesn't let me do custom syntax coloring. From the Q&A on the author's site: "- changing colors is not supported unless you edit manually sm/wxp/stc.py" So I've attempted to check out that code myself in my quest for the perfect full-featured IDE. The stc.py file seems to be the author's modifications on Robin Dunn's original code for wxPython. Buried within all the event handling seems to be code that determines the colour of the various syntax. All I want to do is change the background colour to be black, change the black texts to white, and if everything else stills show up under these two new colours, i'm a happy coder. Has anyone tried this? Thanks edit: The lines around ~441 def SetStyles(self) are those lines it? edit^2: would someone be able to find the cursor blink color setting as well? Or is that something a little 'more' hard coded? edit^3: What I have so far , modifying the hex color values from line -441, in the function SetStyles. def SetStyles(self): # anti-aliasing if hasattr(self,'SetUseAntiAliasing'): self.SetUseAntiAliasing(True) #INDICATOR STYLES FOR ERRORS (self.errorMark) self.IndicatorSetStyle(2, wx_stc.STC_INDIC_SQUIGGLE) self.IndicatorSetForeground(2, wx.RED) #import dialogs.stcStyleEditor if 1:#dialogs.stcStyleEditor.SetStyles(self, self.config): self.StyleSetSpec(wx_stc.STC_P_DEFAULT, "face:%(mono)s,fore:#B0B0B0,size:%(size)d" % self.faces) self.StyleClearAll() # Global default styles for all languages B0B0B0= gray self.StyleSetSpec(wx_stc.STC_STYLE_DEFAULT, "face:%(mono)s,fore:#B0B0B0,back:#00000,size:%(size)d" % self.faces) self.StyleSetSpec(wx_stc.STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(mono)s,size:%(size)d" % self.faces) self.StyleSetSpec(wx_stc.STC_STYLE_CONTROLCHAR, "face:%(mono)s,fore:#B0B0B0" % self.faces) self.StyleSetSpec(wx_stc.STC_STYLE_BRACELIGHT, "fore:#B0B0B0,back:#0000FF,bold") self.StyleSetSpec(wx_stc.STC_STYLE_BRACEBAD, "fore:#B0B0B0,back:#FF0000,bold") # Python styles # White space self.StyleSetSpec(wx_stc.STC_P_DEFAULT, "face:%(mono)s,fore:#000000,back:#000000,size:%(size)d" % self.faces) # Comment self.StyleSetSpec(wx_stc.STC_P_COMMENTLINE, "face:%(mono)s,fore:#F70909,back:#000000,italic,size:%(size)d" % self.faces) # Number self.StyleSetSpec(wx_stc.STC_P_NUMBER, "face:%(mono)s,fore:#FFFFFF,size:%(size)d" % self.faces) # String self.StyleSetSpec(wx_stc.STC_P_STRING, "face:%(mono)s,fore:#34C640,size:%(size)d" % self.faces) # Single quoted string self.StyleSetSpec(wx_stc.STC_P_CHARACTER, "face:%(mono)s,fore:#43AB4E,size:%(size)d" % self.faces) # Keyword (Class, def, etc.) self.StyleSetSpec(wx_stc.STC_P_WORD, "face:%(mono)s,fore:#FF9100,bold,size:%(size)d" % self.faces) # Triple quotes self.StyleSetSpec(wx_stc.STC_P_TRIPLE, "face:%(mono)s,fore:#7F0000,size:%(size)d" % self.faces) # Triple double quotes self.StyleSetSpec(wx_stc.STC_P_TRIPLEDOUBLE, "face:%(mono)s,fore:#7F0000,size:%(size)d" % self.faces) # Class name definition (Name of the class) self.StyleSetSpec(wx_stc.STC_P_CLASSNAME, "face:%(mono)s,fore:#00AEFF,bold,size:%(size)d" % self.faces) # Function or method name definition (bright blue = #0011FF) self.StyleSetSpec(wx_stc.STC_P_DEFNAME, "face:%(mono)s,fore:#FFFF00,bold,size:%(size)d" % self.faces) # Operators (+ - /) self.StyleSetSpec(wx_stc.STC_P_OPERATOR, "face:%(mono)s,fore:#FFFFFF,bold,size:%(size)d" % self.faces) # Identifiers (this was all the same color - > self.SetTopWindow(self.frame)) self.StyleSetSpec(wx_stc.STC_P_IDENTIFIER, "fore:#FFFFFF") # Comment-blocks self.StyleSetSpec(wx_stc.STC_P_COMMENTBLOCK, "face:%(mono)s,fore:#990000,back:#C0C0C0,italic,size:%(size)d" % self.faces) # End of line where string is not closed self.StyleSetSpec(wx_stc.STC_P_STRINGEOL, "face:%(mono)s,fore:#B1CCB0,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % self.faces) this uses a black background and changes the other colors to be brighter. Questions Still Remaining: 1.The class identifiers ("self.", "classname.", etc) have the same color as the text after the '.', but this is how the original one is, don't think that can be changed (easily, anyway) 2. The mouse cursor position marker (blinking "|" ) is still black, which becomes invisible in the new background. 3. Does this application support mouse-overing variables and having a description of the variable's origins pop up?(like in pyscripter)? A: The code I referred to above basically solves the issue, so I'll close the issue.
Stani's python editor- change syntax coloring
Looking at Stani's Python IDE, it definitely comes bundled with tons of useful features. Except it doesn't let me do custom syntax coloring. From the Q&A on the author's site: "- changing colors is not supported unless you edit manually sm/wxp/stc.py" So I've attempted to check out that code myself in my quest for the perfect full-featured IDE. The stc.py file seems to be the author's modifications on Robin Dunn's original code for wxPython. Buried within all the event handling seems to be code that determines the colour of the various syntax. All I want to do is change the background colour to be black, change the black texts to white, and if everything else stills show up under these two new colours, i'm a happy coder. Has anyone tried this? Thanks edit: The lines around ~441 def SetStyles(self) are those lines it? edit^2: would someone be able to find the cursor blink color setting as well? Or is that something a little 'more' hard coded? edit^3: What I have so far , modifying the hex color values from line -441, in the function SetStyles. def SetStyles(self): # anti-aliasing if hasattr(self,'SetUseAntiAliasing'): self.SetUseAntiAliasing(True) #INDICATOR STYLES FOR ERRORS (self.errorMark) self.IndicatorSetStyle(2, wx_stc.STC_INDIC_SQUIGGLE) self.IndicatorSetForeground(2, wx.RED) #import dialogs.stcStyleEditor if 1:#dialogs.stcStyleEditor.SetStyles(self, self.config): self.StyleSetSpec(wx_stc.STC_P_DEFAULT, "face:%(mono)s,fore:#B0B0B0,size:%(size)d" % self.faces) self.StyleClearAll() # Global default styles for all languages B0B0B0= gray self.StyleSetSpec(wx_stc.STC_STYLE_DEFAULT, "face:%(mono)s,fore:#B0B0B0,back:#00000,size:%(size)d" % self.faces) self.StyleSetSpec(wx_stc.STC_STYLE_LINENUMBER, "back:#C0C0C0,face:%(mono)s,size:%(size)d" % self.faces) self.StyleSetSpec(wx_stc.STC_STYLE_CONTROLCHAR, "face:%(mono)s,fore:#B0B0B0" % self.faces) self.StyleSetSpec(wx_stc.STC_STYLE_BRACELIGHT, "fore:#B0B0B0,back:#0000FF,bold") self.StyleSetSpec(wx_stc.STC_STYLE_BRACEBAD, "fore:#B0B0B0,back:#FF0000,bold") # Python styles # White space self.StyleSetSpec(wx_stc.STC_P_DEFAULT, "face:%(mono)s,fore:#000000,back:#000000,size:%(size)d" % self.faces) # Comment self.StyleSetSpec(wx_stc.STC_P_COMMENTLINE, "face:%(mono)s,fore:#F70909,back:#000000,italic,size:%(size)d" % self.faces) # Number self.StyleSetSpec(wx_stc.STC_P_NUMBER, "face:%(mono)s,fore:#FFFFFF,size:%(size)d" % self.faces) # String self.StyleSetSpec(wx_stc.STC_P_STRING, "face:%(mono)s,fore:#34C640,size:%(size)d" % self.faces) # Single quoted string self.StyleSetSpec(wx_stc.STC_P_CHARACTER, "face:%(mono)s,fore:#43AB4E,size:%(size)d" % self.faces) # Keyword (Class, def, etc.) self.StyleSetSpec(wx_stc.STC_P_WORD, "face:%(mono)s,fore:#FF9100,bold,size:%(size)d" % self.faces) # Triple quotes self.StyleSetSpec(wx_stc.STC_P_TRIPLE, "face:%(mono)s,fore:#7F0000,size:%(size)d" % self.faces) # Triple double quotes self.StyleSetSpec(wx_stc.STC_P_TRIPLEDOUBLE, "face:%(mono)s,fore:#7F0000,size:%(size)d" % self.faces) # Class name definition (Name of the class) self.StyleSetSpec(wx_stc.STC_P_CLASSNAME, "face:%(mono)s,fore:#00AEFF,bold,size:%(size)d" % self.faces) # Function or method name definition (bright blue = #0011FF) self.StyleSetSpec(wx_stc.STC_P_DEFNAME, "face:%(mono)s,fore:#FFFF00,bold,size:%(size)d" % self.faces) # Operators (+ - /) self.StyleSetSpec(wx_stc.STC_P_OPERATOR, "face:%(mono)s,fore:#FFFFFF,bold,size:%(size)d" % self.faces) # Identifiers (this was all the same color - > self.SetTopWindow(self.frame)) self.StyleSetSpec(wx_stc.STC_P_IDENTIFIER, "fore:#FFFFFF") # Comment-blocks self.StyleSetSpec(wx_stc.STC_P_COMMENTBLOCK, "face:%(mono)s,fore:#990000,back:#C0C0C0,italic,size:%(size)d" % self.faces) # End of line where string is not closed self.StyleSetSpec(wx_stc.STC_P_STRINGEOL, "face:%(mono)s,fore:#B1CCB0,face:%(mono)s,back:#E0C0E0,eol,size:%(size)d" % self.faces) this uses a black background and changes the other colors to be brighter. Questions Still Remaining: 1.The class identifiers ("self.", "classname.", etc) have the same color as the text after the '.', but this is how the original one is, don't think that can be changed (easily, anyway) 2. The mouse cursor position marker (blinking "|" ) is still black, which becomes invisible in the new background. 3. Does this application support mouse-overing variables and having a description of the variable's origins pop up?(like in pyscripter)?
[ "The code I referred to above basically solves the issue, so I'll close the issue.\n" ]
[ 0 ]
[]
[]
[ "customization", "editor", "python", "syntax_highlighting" ]
stackoverflow_0002421793_customization_editor_python_syntax_highlighting.txt
Q: Custom keys for Google App Engine models (Python) First off, I'm relatively new to Google App Engine, so I'm probably doing something silly. Say I've got a model Foo: class Foo(db.Model): name = db.StringProperty() I want to use name as a unique key for every Foo object. How is this done? When I want to get a specific Foo object, I currently query the datastore for all Foo objects with the target unique name, but queries are slow (plus it's a pain to ensure that name is unique when each new Foo is created). There's got to be a better way to do this! Thanks. A: I've used the code below in a project before. It will work as long as the field on which you're basing your key name on is required. class NamedModel(db.Model): """A Model subclass for entities which automatically generate their own key names on creation. See documentation for _generate_key function for requirements.""" def __init__(self, *args, **kwargs): kwargs['key_name'] = _generate_key(self, kwargs) super(NamedModel, self).__init__(*args, **kwargs) def _generate_key(entity, kwargs): """Generates a key name for the given entity, which was constructed with the given keyword args. The entity must have a KEY_NAME property, which can either be a string or a callable. If KEY_NAME is a string, the keyword args are interpolated into it. If it's a callable, it is called, with the keyword args passed to it as a single dict.""" # Make sure the class has its KEY_NAME property set if not hasattr(entity, 'KEY_NAME'): raise RuntimeError, '%s entity missing KEY_NAME property' % ( entity.entity_type()) # Make a copy of the kwargs dict, so any modifications down the line don't # hurt anything kwargs = dict(kwargs) # The KEY_NAME must either be a callable or a string. If it's a callable, # we call it with the given keyword args. if callable(entity.KEY_NAME): return entity.KEY_NAME(kwargs) # If it's a string, we just interpolate the keyword args into the string, # ensuring that this results in a different string. elif isinstance(entity.KEY_NAME, basestring): # Try to create the key name, catching any key errors arising from the # string interpolation try: key_name = entity.KEY_NAME % kwargs except KeyError: raise RuntimeError, 'Missing keys required by %s entity\'s KEY_NAME '\ 'property (got %r)' % (entity.entity_type(), kwargs) # Make sure the generated key name is actually different from the # template if key_name == entity.KEY_NAME: raise RuntimeError, 'Key name generated for %s entity is same as '\ 'KEY_NAME template' % entity.entity_type() return key_name # Otherwise, the KEY_NAME is invalid else: raise TypeError, 'KEY_NAME of %s must be a string or callable' % ( entity.entity_type()) You could then modify your example model like so: class Foo(NamedModel): KEY_NAME = '%(name)s' name = db.StringProperty() Of course, this could be dramatically simplified in your case, changing the first line of the NamedModel's __init__ method to something like: kwargs['key_name'] = kwargs['name'] A: Here is a pretty thorough discussion of unqiueness with the AppEngine datastore: How do I define a unique property for a Model in Google App Engine?
Custom keys for Google App Engine models (Python)
First off, I'm relatively new to Google App Engine, so I'm probably doing something silly. Say I've got a model Foo: class Foo(db.Model): name = db.StringProperty() I want to use name as a unique key for every Foo object. How is this done? When I want to get a specific Foo object, I currently query the datastore for all Foo objects with the target unique name, but queries are slow (plus it's a pain to ensure that name is unique when each new Foo is created). There's got to be a better way to do this! Thanks.
[ "I've used the code below in a project before. It will work as long as the field on which you're basing your key name on is required.\nclass NamedModel(db.Model):\n \"\"\"A Model subclass for entities which automatically generate their own key\n names on creation. See documentation for _generate_key function for\n requirements.\"\"\"\n\n def __init__(self, *args, **kwargs):\n kwargs['key_name'] = _generate_key(self, kwargs)\n super(NamedModel, self).__init__(*args, **kwargs)\n\n\ndef _generate_key(entity, kwargs):\n \"\"\"Generates a key name for the given entity, which was constructed with\n the given keyword args. The entity must have a KEY_NAME property, which\n can either be a string or a callable.\n\n If KEY_NAME is a string, the keyword args are interpolated into it. If\n it's a callable, it is called, with the keyword args passed to it as a\n single dict.\"\"\"\n\n # Make sure the class has its KEY_NAME property set\n if not hasattr(entity, 'KEY_NAME'):\n raise RuntimeError, '%s entity missing KEY_NAME property' % (\n entity.entity_type())\n\n # Make a copy of the kwargs dict, so any modifications down the line don't\n # hurt anything\n kwargs = dict(kwargs)\n\n # The KEY_NAME must either be a callable or a string. If it's a callable,\n # we call it with the given keyword args.\n if callable(entity.KEY_NAME):\n return entity.KEY_NAME(kwargs)\n\n # If it's a string, we just interpolate the keyword args into the string,\n # ensuring that this results in a different string.\n elif isinstance(entity.KEY_NAME, basestring):\n # Try to create the key name, catching any key errors arising from the\n # string interpolation\n try:\n key_name = entity.KEY_NAME % kwargs\n except KeyError:\n raise RuntimeError, 'Missing keys required by %s entity\\'s KEY_NAME '\\\n 'property (got %r)' % (entity.entity_type(), kwargs)\n\n # Make sure the generated key name is actually different from the\n # template\n if key_name == entity.KEY_NAME:\n raise RuntimeError, 'Key name generated for %s entity is same as '\\\n 'KEY_NAME template' % entity.entity_type()\n\n return key_name\n\n # Otherwise, the KEY_NAME is invalid\n else:\n raise TypeError, 'KEY_NAME of %s must be a string or callable' % (\n entity.entity_type())\n\nYou could then modify your example model like so:\nclass Foo(NamedModel):\n KEY_NAME = '%(name)s'\n name = db.StringProperty()\n\nOf course, this could be dramatically simplified in your case, changing the first line of the NamedModel's __init__ method to something like:\nkwargs['key_name'] = kwargs['name']\n\n", "Here is a pretty thorough discussion of unqiueness with the AppEngine datastore:\nHow do I define a unique property for a Model in Google App Engine?\n" ]
[ 13, 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "primary_key", "python" ]
stackoverflow_0002465675_google_app_engine_google_cloud_datastore_primary_key_python.txt
Q: Call macro from Python script? One of our page templates is made up of a bunch of macros. These items are a bunch of html tables. Now, I want a couple of these tables in a Python script to create a PDF. Is there a way call a macro from a Python script and get back the HTML that is produced? If so, can you explain? Thanks Eric A: I'd probably use urllib.urlopen(url), pull the data from the page back to python and use BeautifulSoup to pull the table(s) out of the HTML... And then render that to PDF with XHTML2PDF (pisa.ho). There might be a simpler way but for me, this would be the least stressful approach. A: Maybe you could create a new template including (use-macro) just the macros you want to access from python and then use z3c.pt.pagetemplate.PageTemplateFile() to render it? Actually, it might be possible (and certainly easier) to use chameleon.zpt.template.PageTemplate('<div tal:use-macro="<your-macro-here>" />'), but I've never did this myself.
Call macro from Python script?
One of our page templates is made up of a bunch of macros. These items are a bunch of html tables. Now, I want a couple of these tables in a Python script to create a PDF. Is there a way call a macro from a Python script and get back the HTML that is produced? If so, can you explain? Thanks Eric
[ "I'd probably use urllib.urlopen(url), pull the data from the page back to python and use BeautifulSoup to pull the table(s) out of the HTML... And then render that to PDF with XHTML2PDF (pisa.ho).\nThere might be a simpler way but for me, this would be the least stressful approach.\n", "Maybe you could create a new template including (use-macro) just the macros you want to access from python and then use z3c.pt.pagetemplate.PageTemplateFile() to render it?\nActually, it might be possible (and certainly easier) to use chameleon.zpt.template.PageTemplate('<div tal:use-macro=\"<your-macro-here>\" />'), but I've never did this myself.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "zope" ]
stackoverflow_0002464442_python_zope.txt
Q: Will pywin32 extensions work on Windows 7? Will the pywin32 extensions work on Windows 7? If not, are there plans for Windows 7 extensions for Python? A: pywin32 extensions works fine on Windows 7.
Will pywin32 extensions work on Windows 7?
Will the pywin32 extensions work on Windows 7? If not, are there plans for Windows 7 extensions for Python?
[ "pywin32 extensions works fine on Windows 7.\n" ]
[ 1 ]
[]
[]
[ "python", "windows_7" ]
stackoverflow_0002466639_python_windows_7.txt
Q: RotatingFileHandler throws an exception when delay parameter is set When I run the following code under Python 2.6 import logging from logging.handlers import RotatingFileHandler rfh = RotatingFileHandler("testing.log", delay=True) logging.getLogger().addHandler(rfh) logging.warning("Boo!") then the last line throws AttributeError: RotatingFileHandler instance has no attribute 'level'. So I add the line rfh.setLevel(logging.DEBUG) before the call to addHandler, and then the last line throws AttributeError: RotatingFileHandler instance has no attribute 'filters'. So if I manually set filters to be an empty list, then it complains about not having the attribute lock, etc. When I remove the delay=True to leave it as the default value of False as documented here, the problem completely goes away. Am I missing something? How do I properly use the delay parameter of the RotatingFileHandler class? EDIT: Upon further analysis (presented in my own answer below), this looks like a bug, but I can't find a bug report on this in the Python bug tracker, even trying different search terms, so I guess I'll report it. However, if someone can locate the actual bug report, then I can avoid submitting a duplicate reporting and wasting the time of the Python developers. I'll hold off on reporting the bug for a few hours, and if someone posts an answer that has the current bug report, then I'll accept that answer for this question. A: I've investigated this issue: it was fixed in Python SVN r68829 dated 20 Jan, 2009. This was after the release of 2.6.1 but before the release of 2.6.2. Please upgrade to Python 2.6.2, or a later version. I've updated the bug you filed. BTW the original bug report filed was #5013, which you could have found by searching all issues (not just open ones) for RotatingFileHandler, like this (from this page). A: I think I've just figured this out: So it looks like one of the parent __init__ methods somewhere up the class hierarchy isn't getting called when delay is set. Indeed, examining the source code to the file logging/__init__.py in my Python install, I see the following code in the FileHandler.__init__ method: if delay: self.stream = None else: stream = self._open() StreamHandler.__init__(self, stream) It looks like the FileHandler.emit method checks for un-opened streams and finishes initialization when logging is performed: if self.stream is None: stream = self._open() StreamHandler.__init__(self, stream) StreamHandler.emit(self, record) So the problem is that in the BaseRotatingHandler.emit method, the shouldRollover and doRollover methods are called before emit-ing the record. This causes methods to be called which themselves assumed that the __init__ process has completed. This looks like a bug, so I'll report it as such if I can't find it having been already been reported.
RotatingFileHandler throws an exception when delay parameter is set
When I run the following code under Python 2.6 import logging from logging.handlers import RotatingFileHandler rfh = RotatingFileHandler("testing.log", delay=True) logging.getLogger().addHandler(rfh) logging.warning("Boo!") then the last line throws AttributeError: RotatingFileHandler instance has no attribute 'level'. So I add the line rfh.setLevel(logging.DEBUG) before the call to addHandler, and then the last line throws AttributeError: RotatingFileHandler instance has no attribute 'filters'. So if I manually set filters to be an empty list, then it complains about not having the attribute lock, etc. When I remove the delay=True to leave it as the default value of False as documented here, the problem completely goes away. Am I missing something? How do I properly use the delay parameter of the RotatingFileHandler class? EDIT: Upon further analysis (presented in my own answer below), this looks like a bug, but I can't find a bug report on this in the Python bug tracker, even trying different search terms, so I guess I'll report it. However, if someone can locate the actual bug report, then I can avoid submitting a duplicate reporting and wasting the time of the Python developers. I'll hold off on reporting the bug for a few hours, and if someone posts an answer that has the current bug report, then I'll accept that answer for this question.
[ "I've investigated this issue: it was fixed in Python SVN r68829 dated 20 Jan, 2009. This was after the release of 2.6.1 but before the release of 2.6.2.\nPlease upgrade to Python 2.6.2, or a later version.\nI've updated the bug you filed. BTW the original bug report filed was #5013, which you could have found by searching all issues (not just open ones) for RotatingFileHandler, like this (from this page).\n", "I think I've just figured this out:\nSo it looks like one of the parent __init__ methods somewhere up the class hierarchy isn't getting called when delay is set. Indeed, examining the source code to the file logging/__init__.py in my Python install, I see the following code in the FileHandler.__init__ method:\nif delay:\n self.stream = None\nelse:\n stream = self._open()\n StreamHandler.__init__(self, stream)\n\nIt looks like the FileHandler.emit method checks for un-opened streams and finishes initialization when logging is performed:\nif self.stream is None:\n stream = self._open()\n StreamHandler.__init__(self, stream)\nStreamHandler.emit(self, record)\n\nSo the problem is that in the BaseRotatingHandler.emit method, the shouldRollover and doRollover methods are called before emit-ing the record. This causes methods to be called which themselves assumed that the __init__ process has completed.\nThis looks like a bug, so I'll report it as such if I can't find it having been already been reported.\n" ]
[ 5, 0 ]
[]
[]
[ "handlers", "logging", "python" ]
stackoverflow_0002465073_handlers_logging_python.txt
Q: Best way to get back to using the power of lxml after having to use a regex to find something in an html document I am trying to rip some text out of a large number of html documents (numbers in the hundreds of thousands). The documents are really forms but they are prepared by a very large group of different organizations so there is significant variation in how they create the document. For example, the documents are divided into chapters. I might want to extract the contents of Chapter 5 from every document so I can analyze the content of the chapter. Initially I thought this would be easy but it turns out that the authors might use a set of non-nested tables throughout the document to hold the content so that Chapter n could be displayed using td tags inside a table. Or they might use other elements such as p tags H tags, div tags or any other block level element. After trying repeatedly to use lxml to help me identify the beginning and end of each chapter I have determined that it is a lot cleaner to use a regular expression because in every case, no matter what the enclosing html element is the chapter label is always in the form of >Chapter # It is a little more complicated in that there might be some white space or non-breaking space represented in different ways (  or   or just spaces). Nonetheless it was trivial to write a regular expression to identify the beginning of each section. (The beginning of one section is the end of the previous section.) But now I want to use lxml to get the text out. My thought is that I have really no choice but to walk along my string to find the close tag for the element that encloses the text I am using to find the relevant section. That is here is one example where the element holding the Chapter name is a div <div style="DISPLAY: block; MARGIN-LEFT: 0pt; TEXT-INDENT: 0pt; MARGIN-RIGHT: 0pt" align="left"><font style="DISPLAY: inline; FONT-WEIGHT: bold; FONT-SIZE: 10pt; FONT-FAMILY: Times New Roman">Chapter 1.&#160;&#160;&#160;Our Beginnings.</font></div> So I am imagining that I would begin at the location where I found the match for chapter 1 and set up a regular expressions to find the next </div|</td|</p|</h1 . . . So at this point I have identified the type of element holding my chapter heading I can use the same logic to find all of the text that is within that element that is set up a regular expression to help me mark from >Chapter 1.&#160;&#160;&#160;Our Beginnings.< So I have identified where my Chapter 1 begins I can do the same for chapter 2 (which is where Chapter 1 ends) Now I am imagining that I am going to snip the document beginning at the opening of the element that I identified as the element the indicates where chapter 1 begins and ending just before the opening of the element that I identified as the element that indicates where Chapter 2 begins. The string that I have identified will then be fed to lxml to use its power to get the content. I am going to all of this trouble because I have read over and over - never use a regular expression to extract content from html documents and I have not hit on a way to be as accurate with lxml to identify the starting and ending locations for the text I want to extract. For example, I can never be certain that the subtitle of Chapter 1 is Our Beginnings it could be Our Red Canary. Let me say that I spent two solid days trying with lxml to be confident that I had the beginning and ending elements and I could only be accurate <60% of the time but a very short regular expression has given me better than 95% success. I have a tendency to make things more complicated than necessary so I am wondering if anyone has seen or solved a similar problems and if they had an approach (not the details mind you) that they would like to offer. A: Sometimes there is not a straight path to getting the content when dealing with poorly or inconsistently written HTML. You might want to look at using lynx or one of the text-based browsers to dump the page content, either into a file, or to pipe it into your code, and then process it. Or, you can use lxml to load and parse the page, then extract the text using text_content() and go after the chapters via regex. Like they say, GIGO - garbage in, garbage out, and it's our job as developers to spin that garbage into gold. Doing so can get pretty messy. A: The simplest thing it sounds like you could possibly do is iterate over tree.getroot().iterdescendants() looking for a node with node.text that matches your desired regular expression. From that point, you can pass the node to a function that uses some ad-hoc heuristics to determine where the text is. (Maybe if iterdescendants on root is too slow you can use your regex approach and dive into etree to try and find a f(text_position) -> node function.) For example, if you find that the target was a //tr/td, you can pass it to some table-text-finding subroutine that looked into the next td in node.parent() to see if it has text that makes sense (approximately chapter-length, containing certain words, whatever). Likewise, you can make up some heuristics for finding the data in other tags like div and p. If you find yourself in an unknown tag like font you can try bubbling up a limited number of levels to find something you know how to handle -- you have to be cautious not to bubble up too far, or I imagine you might accidentally retrieve text from another chapter. The crux of the problem seems to be that you're mining data that's not presented programmatically in a programmatic way -- in these cases, human interaction is usually necessary to some degree. A: As I feared there is no systematic way to use lxml to identify and extract what I need. O h well I appreciate everyone chiming in. Note-this is not the fault of lxml, it is the fault of the inconsistent html coding. For instance. Because a chapter is a reasonable division of a document all the content in one chapter should be wrapped in some type of element. Probably the most flexible would be a div tag with the subsequent div being the next chapter. This would make a chapter a branch of the tree. Unfortunately while approximately 20% of the documents might be that well structured the others are not. I could test for each type of element that should hold my content (div, p) and grab all of its children and all of its siblings until I get to the next element of that type that has information that alerts me that we are at the end of the section (beginning of the next section). But this seems like too much work when I am good 95% of the time or more with a regular expression. Thanks for all of the answers and comments as always I learnded from them.
Best way to get back to using the power of lxml after having to use a regex to find something in an html document
I am trying to rip some text out of a large number of html documents (numbers in the hundreds of thousands). The documents are really forms but they are prepared by a very large group of different organizations so there is significant variation in how they create the document. For example, the documents are divided into chapters. I might want to extract the contents of Chapter 5 from every document so I can analyze the content of the chapter. Initially I thought this would be easy but it turns out that the authors might use a set of non-nested tables throughout the document to hold the content so that Chapter n could be displayed using td tags inside a table. Or they might use other elements such as p tags H tags, div tags or any other block level element. After trying repeatedly to use lxml to help me identify the beginning and end of each chapter I have determined that it is a lot cleaner to use a regular expression because in every case, no matter what the enclosing html element is the chapter label is always in the form of >Chapter # It is a little more complicated in that there might be some white space or non-breaking space represented in different ways (  or   or just spaces). Nonetheless it was trivial to write a regular expression to identify the beginning of each section. (The beginning of one section is the end of the previous section.) But now I want to use lxml to get the text out. My thought is that I have really no choice but to walk along my string to find the close tag for the element that encloses the text I am using to find the relevant section. That is here is one example where the element holding the Chapter name is a div <div style="DISPLAY: block; MARGIN-LEFT: 0pt; TEXT-INDENT: 0pt; MARGIN-RIGHT: 0pt" align="left"><font style="DISPLAY: inline; FONT-WEIGHT: bold; FONT-SIZE: 10pt; FONT-FAMILY: Times New Roman">Chapter 1.&#160;&#160;&#160;Our Beginnings.</font></div> So I am imagining that I would begin at the location where I found the match for chapter 1 and set up a regular expressions to find the next </div|</td|</p|</h1 . . . So at this point I have identified the type of element holding my chapter heading I can use the same logic to find all of the text that is within that element that is set up a regular expression to help me mark from >Chapter 1.&#160;&#160;&#160;Our Beginnings.< So I have identified where my Chapter 1 begins I can do the same for chapter 2 (which is where Chapter 1 ends) Now I am imagining that I am going to snip the document beginning at the opening of the element that I identified as the element the indicates where chapter 1 begins and ending just before the opening of the element that I identified as the element that indicates where Chapter 2 begins. The string that I have identified will then be fed to lxml to use its power to get the content. I am going to all of this trouble because I have read over and over - never use a regular expression to extract content from html documents and I have not hit on a way to be as accurate with lxml to identify the starting and ending locations for the text I want to extract. For example, I can never be certain that the subtitle of Chapter 1 is Our Beginnings it could be Our Red Canary. Let me say that I spent two solid days trying with lxml to be confident that I had the beginning and ending elements and I could only be accurate <60% of the time but a very short regular expression has given me better than 95% success. I have a tendency to make things more complicated than necessary so I am wondering if anyone has seen or solved a similar problems and if they had an approach (not the details mind you) that they would like to offer.
[ "Sometimes there is not a straight path to getting the content when dealing with poorly or inconsistently written HTML. \nYou might want to look at using lynx or one of the text-based browsers to dump the page content, either into a file, or to pipe it into your code, and then process it. Or, you can use lxml to load and parse the page, then extract the text using text_content() and go after the chapters via regex.\nLike they say, GIGO - garbage in, garbage out, and it's our job as developers to spin that garbage into gold. Doing so can get pretty messy.\n", "The simplest thing it sounds like you could possibly do is iterate over tree.getroot().iterdescendants() looking for a node with node.text that matches your desired regular expression. From that point, you can pass the node to a function that uses some ad-hoc heuristics to determine where the text is. (Maybe if iterdescendants on root is too slow you can use your regex approach and dive into etree to try and find a f(text_position) -> node function.)\nFor example, if you find that the target was a //tr/td, you can pass it to some table-text-finding subroutine that looked into the next td in node.parent() to see if it has text that makes sense (approximately chapter-length, containing certain words, whatever). Likewise, you can make up some heuristics for finding the data in other tags like div and p. If you find yourself in an unknown tag like font you can try bubbling up a limited number of levels to find something you know how to handle -- you have to be cautious not to bubble up too far, or I imagine you might accidentally retrieve text from another chapter.\nThe crux of the problem seems to be that you're mining data that's not presented programmatically in a programmatic way -- in these cases, human interaction is usually necessary to some degree.\n", "As I feared there is no systematic way to use lxml to identify and extract what I need. O h well I appreciate everyone chiming in. Note-this is not the fault of lxml, it is the fault of the inconsistent html coding. For instance. Because a chapter is a reasonable division of a document all the content in one chapter should be wrapped in some type of element. Probably the most flexible would be a div tag with the subsequent div being the next chapter. This would make a chapter a branch of the tree. Unfortunately while approximately 20% of the documents might be that well structured the others are not. \nI could test for each type of element that should hold my content (div, p) and grab all of its children and all of its siblings until I get to the next element of that type that has information that alerts me that we are at the end of the section (beginning of the next section). But this seems like too much work when I am good 95% of the time or more with a regular expression.\nThanks for all of the answers and comments as always I learnded from them.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "html_parsing", "lxml", "python", "regex" ]
stackoverflow_0002421396_html_parsing_lxml_python_regex.txt
Q: How to create a custom admin configuration panel in Django? I would like to create a configuration panel for the homepage of the web-app I'm designing with Django. This configuration panel should let me choose some basic options like highlighting some news, setting a showcase banner, and so on. Basically I don't need an app with different rows, but just a panel page with some configuration options. The automatically generated administration area created by Django doesn't seem to handle this feature as far as I can see, so I'm asking you for some directions. Any hint is highly appreciated. Thank you in advance. Matteo A: The admin area of Django features views and templates just like the rest of your Django site, so it's just a matter of customizing the relevant files. This should be a helpful read for you. In particular, the method that renders the index page can be found in django/contrib/admin/sites.py, and the actual index page can be found in django/contrib/admin/templates/admin. Instead of modifying these directly, you should make copies as the above link explains. From there it's just a matter of writing the relevant code to display the news section. You can make the news another app if you want, or you can even get the data from another website using XML or something else of your choice. A: it isnt eaxctly what you are looking for, but you might also be interested in something like django-admin-tools! A: The automatically generated administration area created by Django is for data maintenance. It provides forms to edit data in your models. If it doesn't "handle this feature", then it sounds like your "configuration panel" (configuration panel should let me choose some basic options like highlighting some news, setting a showcase banner, and so on) does not have any data model. If you define a model with basic options like highlighting some news, setting a showcase banner, and so on then the Django admin will update rows in the model. You can then use the model data to configure your application. If -- for some reason -- you don't want to put this in the database, then there will never be an automatically generated administration area created by Django.
How to create a custom admin configuration panel in Django?
I would like to create a configuration panel for the homepage of the web-app I'm designing with Django. This configuration panel should let me choose some basic options like highlighting some news, setting a showcase banner, and so on. Basically I don't need an app with different rows, but just a panel page with some configuration options. The automatically generated administration area created by Django doesn't seem to handle this feature as far as I can see, so I'm asking you for some directions. Any hint is highly appreciated. Thank you in advance. Matteo
[ "The admin area of Django features views and templates just like the rest of your Django site, so it's just a matter of customizing the relevant files.\nThis should be a helpful read for you.\nIn particular, the method that renders the index page can be found in django/contrib/admin/sites.py, and the actual index page can be found in django/contrib/admin/templates/admin. Instead of modifying these directly, you should make copies as the above link explains.\nFrom there it's just a matter of writing the relevant code to display the news section. You can make the news another app if you want, or you can even get the data from another website using XML or something else of your choice.\n", "it isnt eaxctly what you are looking for, but you might also be interested in something like django-admin-tools!\n", "The automatically generated administration area created by Django is for data maintenance.\nIt provides forms to edit data in your models.\nIf it doesn't \"handle this feature\", then it sounds like your \"configuration panel\" (configuration panel should let me choose some basic options like highlighting some news, setting a showcase banner, and so on) does not have any data model.\nIf you define a model with basic options like highlighting some news, setting a showcase banner, and so on then the Django admin will update rows in the model. You can then use the model data to configure your application.\nIf -- for some reason -- you don't want to put this in the database, then there will never be an automatically generated administration area created by Django.\n" ]
[ 2, 2, 0 ]
[]
[]
[ "admin", "django", "panel", "python" ]
stackoverflow_0002455018_admin_django_panel_python.txt
Q: How to upload 6000 record to Google Datastore from csv file http://code.google.com/appengine/docs/python/tools/uploadingdata.html is not clearly understand. Where i should call the bulkloader.py or appcfg.py? Should i import the csv file to local Google App Engine SDK first? How to keep the upload and download data process in existing application for datastore synchronization? A: Set Up remote_api, the docs have instructions for both java and python and then run bulkloader.py locally : bulkloader.py --dump --app_id=<app-id> --url=http://<appname>.appspot.com/remote_api --filename=<data-filename> if you are using the java sdk, you will need to install the python sdk.
How to upload 6000 record to Google Datastore from csv file
http://code.google.com/appengine/docs/python/tools/uploadingdata.html is not clearly understand. Where i should call the bulkloader.py or appcfg.py? Should i import the csv file to local Google App Engine SDK first? How to keep the upload and download data process in existing application for datastore synchronization?
[ "Set Up remote_api, the docs have instructions for both java and python and then run bulkloader.py locally :\nbulkloader.py --dump --app_id=<app-id> --url=http://<appname>.appspot.com/remote_api --filename=<data-filename>\n\nif you are using the java sdk, you will need to install the python sdk.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002466742_google_app_engine_google_cloud_datastore_python.txt
Q: What are some good ways to do intermachine locking? Our server cluster consists of 20 machines, each with 10 pids of 5 threads. We'd like some way to prevent any two threads, in any pid, on any machine, from modifying the same object at the same time. Our code's written in Python and runs on Linux, if that helps narrow things down. Also, it's a pretty rare case that two such threads want to do this, so we'd prefer something that optimizes the "only one thread needs this object" case to be really fast, even if it means that the "one thread has locked this object and another one needs it" case isn't great. What are some of the best practices? A: If you want to synchronize across machines you need a Distributed Lock Manager. I did some quick googling and came up with: Stackoverflow. Unfortunately they only suggest Java version, but it's a start. If you are trying to synchronize access to files: Your filesystem should already have some wort of locking service in place. If not consider changing it. A: I assume you came across this blog post http://amix.dk/blog/post/19386 during your googling? The author demonstrates a simple interface to memcachedb which it uses as a dummy distributed lock manager. It's a great idea, and memcache is probably one of the faster thing's you'll be able to interface with. Note that it does use the more recently added with statement. Here is an example usage from his blog post: from __future__ import with_statement import memcache from memcached_lock import dist_lock client = memcache.Client(['127.0.0.1:11211']) with dist_lock('test', client): print 'Is there anybody out there!?' A: if you can get the complete infrastructure for a distributed lock manager then go ahead and use that. But that infrastructure is not easy to setup! But here is a practical solution: -designate the node with the lowest ip address as the the master node (that means if the node with lowest ip address hangs, a new node with lowest ip address will become new master) -let all nodes contact the master node to get the lock on the object. -let the master node use native lock semantics to get the lock. this will simplify things unless you need complete clustering infrastructure and DLM to do the job. A: Write code using immutable objects. Write objects that implement the Singleton Pattern. Use a stable Distributed messaging technology such as IPC, webservices, or XML-RPC. I would take a look at Twisted. They got plenty of solutions for such task. I wouldn't use threads in Python esp with regards to the GIL, I would look at using Processes as working applications and use a comms technology as described above for intercommunications. Your singleton class could then appear in one of these applications and interfaced via comms technology of choice. Not a fast solution with all the interfacing, but if done correctly should be stable.
What are some good ways to do intermachine locking?
Our server cluster consists of 20 machines, each with 10 pids of 5 threads. We'd like some way to prevent any two threads, in any pid, on any machine, from modifying the same object at the same time. Our code's written in Python and runs on Linux, if that helps narrow things down. Also, it's a pretty rare case that two such threads want to do this, so we'd prefer something that optimizes the "only one thread needs this object" case to be really fast, even if it means that the "one thread has locked this object and another one needs it" case isn't great. What are some of the best practices?
[ "If you want to synchronize across machines you need a Distributed Lock Manager.\nI did some quick googling and came up with: Stackoverflow.\nUnfortunately they only suggest Java version, but it's a start.\nIf you are trying to synchronize access to files: Your filesystem should already have some wort of locking service in place. If not consider changing it.\n", "I assume you came across this blog post http://amix.dk/blog/post/19386 during your googling?\nThe author demonstrates a simple interface to memcachedb which it uses as a dummy distributed lock manager. It's a great idea, and memcache is probably one of the faster thing's you'll be able to interface with. Note that it does use the more recently added with statement. \nHere is an example usage from his blog post: \nfrom __future__ import with_statement\nimport memcache\nfrom memcached_lock import dist_lock\n\nclient = memcache.Client(['127.0.0.1:11211'])\nwith dist_lock('test', client):\n print 'Is there anybody out there!?'\n\n", "if you can get the complete infrastructure for a distributed lock manager then go ahead and use that. But that infrastructure is not easy to setup! But here is a practical solution:\n-designate the node with the lowest ip address as the the master node \n(that means if the node with lowest ip address hangs, a new node with lowest ip address will become new master)\n-let all nodes contact the master node to get the lock on the object. \n-let the master node use native lock semantics to get the lock.\nthis will simplify things unless you need complete clustering infrastructure and DLM to do the job.\n", "Write code using immutable objects. Write objects that implement the Singleton Pattern.\nUse a stable Distributed messaging technology such as IPC, webservices, or XML-RPC.\nI would take a look at Twisted. They got plenty of solutions for such task. \nI wouldn't use threads in Python esp with regards to the GIL, I would look at using Processes as working applications and use a comms technology as described above for intercommunications.\nYour singleton class could then appear in one of these applications and interfaced via comms technology of choice.\nNot a fast solution with all the interfacing, but if done correctly should be stable.\n" ]
[ 5, 3, 1, 0 ]
[ "There may be a better way of doing this, but i would use the Lock class from the threading module to access the \"protected\" objects in a with statement, here would be an example:\nfrom __future__ import with_statement \nfrom threading import Lock\n\nmylock = Lock()\nwith mylock.acquire():\n [ 'do things with protected data here' ]\n[ 'the rest of the code' ]\n\nfor more examples about Lock usages, have a look here.\nEdit: this solution isn't suitable for this question as threading.Lock is not distributed, sorry\n" ]
[ -4 ]
[ "linux", "multithreading", "mutex", "python" ]
stackoverflow_0002448984_linux_multithreading_mutex_python.txt
Q: slicing behaviour question of a list of lists I got a function like def f(): ... ... return [list1, list2] this returns a list of lists [[list1.item1,list1.item2,...],[list2.item1,list2.item2,...]] now when I do the following: for i in range(0,2):print f()[i][0:10] it works and print the lists sliced but if i do print f()[0:2][0:10] then it prints the lists ignoring the [0:10] slicing. Is there any way to make the second form work or do I have to loop every time to get the desired result? A: The second slice slices the sequence returned from the first slice, so yes, you will have to loop somehow in order to slice within: [x[0:10] for x in f()[0:2]] A: The reason why these two behave differently is because f()[0:2][0:10] works like this: f() gives you a list of lists. [0:2] gives you a list containing the first two elements in the list of lists. Since the elements in the list of lists are lists, this is also a list of lists. [0:10] gives you a list containing the first ten elements in the list of lists that was produced in step 2. In other words, f()[0:2][0:10] starts with a list of lists, then takes a sublist of that list of lists (which is also a list of lists), and then takes a sublist of the second list of lists (which is also a list of lists). In contrast, f()[i] actually extracts the i-th element out of your list of lists, which is just a simple list (not a list of lists). Then, when you apply [0:10], you are applying it to the simple list that you got from f()[i] and not to a list of lists. The bottom line is that any solution that gives the desired behavior will have to access a single array element like [i] at some point, rather than working only with slices like [i:j]. A: A pythonic loop would be: for list in f()[0:2]: print list[0:10] But depending on what you want to achieve, list comprehension might be even better. Or you make use of Pythons map() function: def print_sub(x): print x[0:10] map(print_sub, f()[0:2]) One way or the other, there is no way to not iterate over the list and achieve the desired result.
slicing behaviour question of a list of lists
I got a function like def f(): ... ... return [list1, list2] this returns a list of lists [[list1.item1,list1.item2,...],[list2.item1,list2.item2,...]] now when I do the following: for i in range(0,2):print f()[i][0:10] it works and print the lists sliced but if i do print f()[0:2][0:10] then it prints the lists ignoring the [0:10] slicing. Is there any way to make the second form work or do I have to loop every time to get the desired result?
[ "The second slice slices the sequence returned from the first slice, so yes, you will have to loop somehow in order to slice within:\n[x[0:10] for x in f()[0:2]]\n\n", "The reason why these two behave differently is because f()[0:2][0:10] works like this:\n\nf() gives you a list of lists.\n[0:2] gives you a list containing the first two elements in the list of lists. Since the elements in the list of lists are lists, this is also a list of lists.\n[0:10] gives you a list containing the first ten elements in the list of lists that was produced in step 2.\n\nIn other words, f()[0:2][0:10] starts with a list of lists, then takes a sublist of that list of lists (which is also a list of lists), and then takes a sublist of the second list of lists (which is also a list of lists).\nIn contrast, f()[i] actually extracts the i-th element out of your list of lists, which is just a simple list (not a list of lists). Then, when you apply [0:10], you are applying it to the simple list that you got from f()[i] and not to a list of lists.\nThe bottom line is that any solution that gives the desired behavior will have to access a single array element like [i] at some point, rather than working only with slices like [i:j].\n", "A pythonic loop would be:\nfor list in f()[0:2]:\n print list[0:10]\n\nBut depending on what you want to achieve, list comprehension might be even better.\nOr you make use of Pythons map() function:\ndef print_sub(x):\n print x[0:10]\n\nmap(print_sub, f()[0:2])\n\nOne way or the other, there is no way to not iterate over the list and achieve the desired result.\n" ]
[ 10, 7, 0 ]
[]
[]
[ "function", "python", "slice" ]
stackoverflow_0002466941_function_python_slice.txt
Q: Log errors to database with Django on Google App Engine Is there a project that can log errors in requests to Django on Google App Engine to the datastore (like django-db-log or django.crashlog)? Thanks! A: Use the built-in google.appengine.ext.ereporter module: A logging handler that records information about unique exceptions. 'Unique' in this case is defined as a given (exception class, location) tuple. Unique exceptions are logged to the datastore with an example stacktrace and an approximate count of occurrences, grouped by day and application version. A cron handler, in google.appengine.ext.ereporter.report_generator, constructs and emails a report based on the previous day's exceptions. See also: Using the ereporter module for easy error reporting. A: Check out Native Django on GAE. It's a non-relational port of Django to Google's App Engine. Another project, google-app-engine-django, looks like an intermediate "helper" to get you going, without the full port. A: I've created a project Django-GAE-log to solve this issue. Thoughts and input are welcome!
Log errors to database with Django on Google App Engine
Is there a project that can log errors in requests to Django on Google App Engine to the datastore (like django-db-log or django.crashlog)? Thanks!
[ "Use the built-in google.appengine.ext.ereporter module:\n\nA logging handler that records\n information about unique exceptions.\n'Unique' in this case is defined as a\n given (exception class, location)\n tuple. Unique exceptions are logged to\n the datastore with an example\n stacktrace and an approximate count of\n occurrences, grouped by day and\n application version.\nA cron handler, in\n google.appengine.ext.ereporter.report_generator,\n constructs and emails a report based\n on the previous day's exceptions.\n\nSee also: Using the ereporter module for easy error reporting.\n", "\nCheck out Native Django on GAE. It's a non-relational port of Django to Google's App Engine. \nAnother project,\ngoogle-app-engine-django, looks\nlike an intermediate \"helper\" to get\nyou going, without the full port.\n\n", "I've created a project Django-GAE-log to solve this issue. Thoughts and input are welcome!\n" ]
[ 3, 1, 0 ]
[]
[]
[ "django", "error_handling", "google_app_engine", "logging", "python" ]
stackoverflow_0002459246_django_error_handling_google_app_engine_logging_python.txt
Q: What does this code from AuthKit do? (where are these functions and methods defined?) I am trying to implement my own authentication method for AuthKit and am trying to figure out how some of the built-in methods work. In particular, I'm trying to figure out how to update the REMOTE_USER for environ correctly. This is how it is handled inside of authkit.authenticate.basic but it is pretty confusing. I cannot find anyplace where REMOTE_USER and AUTH_TYPE are defined. Is there something strange going on here and if so, what is it? def __call__(self, environ, start_response): environ['authkit.users'] = self.users result = self.authenticate(environ) if isinstance(result, str): AUTH_TYPE.update(environ, 'basic') REMOTE_USER.update(environ, result) return self.application(environ, start_response) There are actually a number of all uppercase things like this that I cannot find a definition for. For example, where does AUTHORIZATION come from below: def authenticate(self, environ): authorization = AUTHORIZATION(environ) if not authorization: return self.build_authentication() (authmeth, auth) = authorization.split(' ',1) if 'basic' != authmeth.lower(): return self.build_authentication() auth = auth.strip().decode('base64') username, password = auth.split(':',1) if self.authfunc(environ, username, password): return username return self.build_authentication() I feel like maybe I am missing some special syntax handling for the environ dict, but it is possible that there is something else really weird going on here that isn't immediately obvious to someone as new to Python as myself. A: Looking at that source I see it has an (evil) from paste.httpheaders import * that is one way otherwise-mysterious barenames could suddenly appear in the code (which is exactly why this idiom is a very, very bad practice). I can't be sure that's how those identifiers suddenly and inexplicably materialize, but it's a possibility.
What does this code from AuthKit do? (where are these functions and methods defined?)
I am trying to implement my own authentication method for AuthKit and am trying to figure out how some of the built-in methods work. In particular, I'm trying to figure out how to update the REMOTE_USER for environ correctly. This is how it is handled inside of authkit.authenticate.basic but it is pretty confusing. I cannot find anyplace where REMOTE_USER and AUTH_TYPE are defined. Is there something strange going on here and if so, what is it? def __call__(self, environ, start_response): environ['authkit.users'] = self.users result = self.authenticate(environ) if isinstance(result, str): AUTH_TYPE.update(environ, 'basic') REMOTE_USER.update(environ, result) return self.application(environ, start_response) There are actually a number of all uppercase things like this that I cannot find a definition for. For example, where does AUTHORIZATION come from below: def authenticate(self, environ): authorization = AUTHORIZATION(environ) if not authorization: return self.build_authentication() (authmeth, auth) = authorization.split(' ',1) if 'basic' != authmeth.lower(): return self.build_authentication() auth = auth.strip().decode('base64') username, password = auth.split(':',1) if self.authfunc(environ, username, password): return username return self.build_authentication() I feel like maybe I am missing some special syntax handling for the environ dict, but it is possible that there is something else really weird going on here that isn't immediately obvious to someone as new to Python as myself.
[ "Looking at that source I see it has an (evil)\nfrom paste.httpheaders import *\n\nthat is one way otherwise-mysterious barenames could suddenly appear in the code (which is exactly why this idiom is a very, very bad practice). I can't be sure that's how those identifiers suddenly and inexplicably materialize, but it's a possibility.\n" ]
[ 1 ]
[]
[]
[ "authkit", "python" ]
stackoverflow_0002467013_authkit_python.txt
Q: GAE - Getting TypeError requiring class instance be passed to class's own method I'm really new to programming... I set up a class to give supporting information for Google's User API user object. I store this info in the datastore using db.model. When I call the okstatus method of my user_info class using this code: elif user_info.okstatus(user): self.response.out.write("user allowed") I get this error: unbound method okstatus() must be called with user_info instance as first argument (got User instance instead) Here is my user_info class. class user_info: def auth_ctrlr(self, user): if self.status(user) == status_allowed: return ("<a href=\"%s\">Sign Out</a>)" % (users.create_login_url("/"))) else: return ("<a href=\"%s\">Sign In or Get an Account</a>)" % (users.create_logout_url("/"))) def status(self, user): match = sub_user.gql(qu_by_user_id, user.user_id) return match.string_status def group(self, user): match = sub_user.gql(qu_by_user_id, user.user_id) grp = group_names.gql(qu_by_user_id, match.groupID) return grp def okstatus(self, user): match = self.status(user) if match == status_allowed: return True My understanding is that the argument "self" inside the method's calling arguments describes it as a child to the class. I've tried everything I can think of and can't find any related info online. Can someone please tell me what I'm doing wrong? Thanks A: self must be an instance of the class. Since you never actually use it, you can simply make all of these methods into functions (and changing the self.status cases to just status). If you're a "class fetishist", and absolutely insist on keeping the functions as methods in a class (rather than the module top-level functions they "want" to be!-), then change the call site to elif user_info().okstatus(user): that is, make an instance of your user_info class, and call the method on it (the useless instance then immediately goes away, pointing out that these should really be functions;-).
GAE - Getting TypeError requiring class instance be passed to class's own method
I'm really new to programming... I set up a class to give supporting information for Google's User API user object. I store this info in the datastore using db.model. When I call the okstatus method of my user_info class using this code: elif user_info.okstatus(user): self.response.out.write("user allowed") I get this error: unbound method okstatus() must be called with user_info instance as first argument (got User instance instead) Here is my user_info class. class user_info: def auth_ctrlr(self, user): if self.status(user) == status_allowed: return ("<a href=\"%s\">Sign Out</a>)" % (users.create_login_url("/"))) else: return ("<a href=\"%s\">Sign In or Get an Account</a>)" % (users.create_logout_url("/"))) def status(self, user): match = sub_user.gql(qu_by_user_id, user.user_id) return match.string_status def group(self, user): match = sub_user.gql(qu_by_user_id, user.user_id) grp = group_names.gql(qu_by_user_id, match.groupID) return grp def okstatus(self, user): match = self.status(user) if match == status_allowed: return True My understanding is that the argument "self" inside the method's calling arguments describes it as a child to the class. I've tried everything I can think of and can't find any related info online. Can someone please tell me what I'm doing wrong? Thanks
[ "self must be an instance of the class. Since you never actually use it, you can simply make all of these methods into functions (and changing the self.status cases to just status).\nIf you're a \"class fetishist\", and absolutely insist on keeping the functions as methods in a class (rather than the module top-level functions they \"want\" to be!-), then change the call site to\nelif user_info().okstatus(user):\n\nthat is, make an instance of your user_info class, and call the method on it (the useless instance then immediately goes away, pointing out that these should really be functions;-).\n" ]
[ 1 ]
[]
[]
[ "class", "google_app_engine", "methods", "python", "typeerror" ]
stackoverflow_0002467201_class_google_app_engine_methods_python_typeerror.txt
Q: Looping Redirect with PyFacebook and Google App Engine I have a Python Facebook project hosted on Google App Engine and use the following code to handle initialization of the Facebook API using PyFacebook. # Facebook Initialization def initialize_facebook(f): # Redirection handler def redirect(self, url): logger.info('Redirecting the user to: ' + url) self.response.headers.add_header("Cache-Control", "max-age=0") self.response.headers.add_header("Pragma", "no-cache") self.response.out.write('<html><head><script>parent.location.replace(\'' + url + '\');</script></head></html>') return 'Moved temporarily' auth_token = request.params.get('auth_token', None) fbapi = Facebook(settings['FACEBOOK_API_KEY'], settings['FACEBOOK_SECRET_KEY'], auth_token=auth_token) if not fbapi: logger.error('Facebook failed to initialize') if fbapi.check_session(request) or auth_token: pass else: logger.info('User not logged into Facebook') return lambda a: redirect(a, fbapi.get_login_url()) if fbapi.added: pass else: logger.info('User does not have ' + settings['FACEBOOK_APP_NAME'] + ' added') return lambda a: redirect(a, fbapi.get_add_url()) # Return the validated API logger.info('Facebook successfully initialized') return lambda a: f(a, fbapi=fbapi) I'm trying to set it up so that I can drop this decorator on any page handler method and verify that the user has everything set up correctly. The issue is that when the redirect handler gets called, it starts an infinite loop of redirection. I tried using an HTTP 302 redirection in place of the JavaScript but that kept failing too. Does anyone know what I can do to fix this? I saw this similar question but there are no answers. A: I was just having the exact same thing happen to me today! What I think is happening is that fbapi.check_session() is not setting fbapi.added correctly. I don't think the Post-Add URL contains 'installed' anymore, but still has 'fb_sig_added'. The following change (github-esque code) in pyfacebook stopped the infinite redirect for me: 1244 | 1244 | if request.method == 'POST': 1245 | 1245 | params = self.validate_signature(request.POST) 1246 | 1246 | else: 1247 | | - if 'installed' in request.GET: | 1247 | + if 'installed' in request.GET or request.GET['fb_sig_added'] == '1': 1248 | 1248 | self.added = True A: The problem seems familiar. May you can use the solution from my question here: app-engine-patch and pyFacebook not working But that was with the decorator that comes with pyfacebook so it might be different.
Looping Redirect with PyFacebook and Google App Engine
I have a Python Facebook project hosted on Google App Engine and use the following code to handle initialization of the Facebook API using PyFacebook. # Facebook Initialization def initialize_facebook(f): # Redirection handler def redirect(self, url): logger.info('Redirecting the user to: ' + url) self.response.headers.add_header("Cache-Control", "max-age=0") self.response.headers.add_header("Pragma", "no-cache") self.response.out.write('<html><head><script>parent.location.replace(\'' + url + '\');</script></head></html>') return 'Moved temporarily' auth_token = request.params.get('auth_token', None) fbapi = Facebook(settings['FACEBOOK_API_KEY'], settings['FACEBOOK_SECRET_KEY'], auth_token=auth_token) if not fbapi: logger.error('Facebook failed to initialize') if fbapi.check_session(request) or auth_token: pass else: logger.info('User not logged into Facebook') return lambda a: redirect(a, fbapi.get_login_url()) if fbapi.added: pass else: logger.info('User does not have ' + settings['FACEBOOK_APP_NAME'] + ' added') return lambda a: redirect(a, fbapi.get_add_url()) # Return the validated API logger.info('Facebook successfully initialized') return lambda a: f(a, fbapi=fbapi) I'm trying to set it up so that I can drop this decorator on any page handler method and verify that the user has everything set up correctly. The issue is that when the redirect handler gets called, it starts an infinite loop of redirection. I tried using an HTTP 302 redirection in place of the JavaScript but that kept failing too. Does anyone know what I can do to fix this? I saw this similar question but there are no answers.
[ "I was just having the exact same thing happen to me today! What I think is happening is that fbapi.check_session() is not setting fbapi.added correctly. I don't think the Post-Add URL contains 'installed' anymore, but still has 'fb_sig_added'. The following change (github-esque code) in pyfacebook stopped the infinite redirect for me:\n\n1244 | 1244 | if request.method == 'POST':\n1245 | 1245 | params = self.validate_signature(request.POST)\n1246 | 1246 | else:\n1247 | | - if 'installed' in request.GET:\n | 1247 | + if 'installed' in request.GET or request.GET['fb_sig_added'] == '1':\n1248 | 1248 | self.added = True\n\n", "The problem seems familiar.\nMay you can use the solution from my question here:\napp-engine-patch and pyFacebook not working\nBut that was with the decorator that comes with pyfacebook so it might be different.\n" ]
[ 2, 0 ]
[]
[]
[ "google_app_engine", "pyfacebook", "python", "redirect" ]
stackoverflow_0002349368_google_app_engine_pyfacebook_python_redirect.txt
Q: How powerful is x3d for making animations? I want to make a rotating drillbit animation that shows the complete process of drilling. I am not really sure that it can be done using x3d. How good is x3d (along with python scripting, maybe) to make such animations? A: I am not really sure that it can be done using x3d. How good is x3d (along with python scripting, maybe) to make such animations? If you are running a modern - developer version browser, then you can visit my home page mid-awe.com to see what I did with X3DOM. The animation was very simple with the Flux/Vivaty studio tool and X3DOM are really all you need after the 3D model. I recommend Wings3D or Blender 2.5 to generate the VRML/X3D. Then import X3D -> Vivaty Studio for animation. Finally, export X3D non-compressed. Open the X3D (XML) copy contents to the conversion tool specified on the X3DOM website. (I tried to provide all of the links but this site stopped me - for good or bad you'll have to search for the tools I suggested)
How powerful is x3d for making animations?
I want to make a rotating drillbit animation that shows the complete process of drilling. I am not really sure that it can be done using x3d. How good is x3d (along with python scripting, maybe) to make such animations?
[ "\nI am not really sure that it can be\n done using x3d. How good is x3d (along\n with python scripting, maybe) to make\n such animations?\n\nIf you are running a modern - developer version browser, then you can visit my home page mid-awe.com to see what I did with X3DOM. The animation was very simple with the Flux/Vivaty studio tool and X3DOM are really all you need after the 3D model. \nI recommend Wings3D or Blender 2.5 to generate the VRML/X3D. Then import X3D -> Vivaty Studio for animation. Finally, export X3D non-compressed. \nOpen the X3D (XML) copy contents to the conversion tool specified on the X3DOM website.\n(I tried to provide all of the links but this site stopped me - for good or bad you'll have to search for the tools I suggested)\n" ]
[ 0 ]
[]
[]
[ "animation", "python", "x3d" ]
stackoverflow_0002021055_animation_python_x3d.txt
Q: I want to find the span tag beween the LI tag and its attributes but no luck I want to find the span tag beween the LI tag and its attributes. Trying with beautful soap but no luck. Details of my code. Is any one point me right methodlogy In this this code, my getId function should return me id = "0_False-2" Any one know right method? from BeautifulSoup import BeautifulSoup as bs import re html = '<ul>\ <li class="line">&nbsp;</li>\ <li class="folder-open-last" id="0">\ <img style="float: left;" class="trigger" src="/media/images/spacer.gif" border="0">\ <span class="text" id="0_False">NOC</span><ul style="display: block;"><li class="line">&nbsp;</li><li class="doc" id="1"><span class="active text" id="0_False-1">PNQAIPMS1</span></li><li class="line">&nbsp;</li><li class="doc-last" id="2"><span class="text" id="0_False-2">PNQAIPMS2</span></li><li class="line-last"></li></ul></li><li class="line-last"></li>\ </ul>' def getId(html, txt): soup = bs(html) soup.findAll('ul',recursive=False) head = soup.contents[0] temp = head elements = {} while True: # It temp is None that means no HTML tags are available if temp == None: break #print temp if re.search('li', str( temp)) != None: attr = str(temp.attrs).encode('ascii','ignore') attr = attr.replace(' ', '') attr = attr.replace('[', '') attr = attr.replace(']', '') attr = attr.replace(')', '') attr = attr.replace('(', '') attr = attr.replace('u\'', '') attr = attr.replace('\'', '') attr = attr.split(',') span = str(temp.text) if span == txt: return attr[3] temp = temp.next else: temp = temp.next id = getId(html,"PNQAIPMS2") print "ID = " + id A: I am sure someone can show you the BS way, but here's my approach. Just plain old Python string manipulation. html = '<ul>\ <li class="line">&nbsp;</li>\ <li class="folder-open-last" id="0">\ <img style="float: left;" class="trigger" src="/media/images/spacer.gif" border="0">\ <span class="text" id="0_False">NOC</span><ul style="display: block;"><li class="line">&nbsp;</li><li class="doc" id="1"><span class="active text" id="0_False-1">PNQAIPMS1</span></li><li class="line">&nbsp;</li><li class="doc-last" id="2"><span class="text" id="0_False-2">PNQAIPMS2</span></li><li class="line-last"></li></ul></li><li class="line-last"></li>\ </ul>' def getId( html, txt): for LI in html.split("</li>"): if "span" in LI: for CL in LI.split("span"): if "class" in CL and "id" in CL and "text" in CL and txt in CL: return CL.split("id=")[-1].split('">')[0].replace('"',"") print "id for PNQAIPMS2: " , getId(html,"PNQAIPMS2") print "id for NOC: ",getId(html, "NOC") print "id for PNQAIPMS1: ",getId(html, "PNQAIPMS1") output $ ./python.py id for PNQAIPMS2: 0_False-2 id for NOC: 0_False id for PNQAIPMS1: 0_False-1
I want to find the span tag beween the LI tag and its attributes but no luck
I want to find the span tag beween the LI tag and its attributes. Trying with beautful soap but no luck. Details of my code. Is any one point me right methodlogy In this this code, my getId function should return me id = "0_False-2" Any one know right method? from BeautifulSoup import BeautifulSoup as bs import re html = '<ul>\ <li class="line">&nbsp;</li>\ <li class="folder-open-last" id="0">\ <img style="float: left;" class="trigger" src="/media/images/spacer.gif" border="0">\ <span class="text" id="0_False">NOC</span><ul style="display: block;"><li class="line">&nbsp;</li><li class="doc" id="1"><span class="active text" id="0_False-1">PNQAIPMS1</span></li><li class="line">&nbsp;</li><li class="doc-last" id="2"><span class="text" id="0_False-2">PNQAIPMS2</span></li><li class="line-last"></li></ul></li><li class="line-last"></li>\ </ul>' def getId(html, txt): soup = bs(html) soup.findAll('ul',recursive=False) head = soup.contents[0] temp = head elements = {} while True: # It temp is None that means no HTML tags are available if temp == None: break #print temp if re.search('li', str( temp)) != None: attr = str(temp.attrs).encode('ascii','ignore') attr = attr.replace(' ', '') attr = attr.replace('[', '') attr = attr.replace(']', '') attr = attr.replace(')', '') attr = attr.replace('(', '') attr = attr.replace('u\'', '') attr = attr.replace('\'', '') attr = attr.split(',') span = str(temp.text) if span == txt: return attr[3] temp = temp.next else: temp = temp.next id = getId(html,"PNQAIPMS2") print "ID = " + id
[ "I am sure someone can show you the BS way, but here's my approach. Just plain old Python string manipulation.\nhtml = '<ul>\\\n<li class=\"line\">&nbsp;</li>\\\n<li class=\"folder-open-last\" id=\"0\">\\\n<img style=\"float: left;\" class=\"trigger\" src=\"/media/images/spacer.gif\" border=\"0\">\\\n<span class=\"text\" id=\"0_False\">NOC</span><ul style=\"display: block;\"><li class=\"line\">&nbsp;</li><li class=\"doc\" id=\"1\"><span class=\"active text\" id=\"0_False-1\">PNQAIPMS1</span></li><li class=\"line\">&nbsp;</li><li class=\"doc-last\" id=\"2\"><span class=\"text\" id=\"0_False-2\">PNQAIPMS2</span></li><li class=\"line-last\"></li></ul></li><li class=\"line-last\"></li>\\\n</ul>'\n\n\ndef getId( html, txt):\n for LI in html.split(\"</li>\"):\n if \"span\" in LI:\n for CL in LI.split(\"span\"):\n if \"class\" in CL and \"id\" in CL and \"text\" in CL and txt in CL:\n return CL.split(\"id=\")[-1].split('\">')[0].replace('\"',\"\")\n\nprint \"id for PNQAIPMS2: \" , getId(html,\"PNQAIPMS2\")\nprint \"id for NOC: \",getId(html, \"NOC\")\nprint \"id for PNQAIPMS1: \",getId(html, \"PNQAIPMS1\")\n\noutput\n$ ./python.py\nid for PNQAIPMS2: 0_False-2\nid for NOC: 0_False\nid for PNQAIPMS1: 0_False-1\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0002468278_beautifulsoup_html_python.txt
Q: Generating a list of values a regex COULD match in Python I'm trying to use a regex as an input, and from there generate all the possible values that the regex would match. So, for example, if the regex is "three-letter words starting with a, and ending in c," then the code would generate a list with the values [aac, abc, acc, adc, a1c....]. Is there an easy way to do this? I'm using python. A: Here's a brute force solution that should work. It has a running time of O(L^max_length) (where L is the size of the alphabet), so use it at your own risk. def all_matching_strings(alphabet, max_length, regex): """Find the list of all strings over 'alphabet' of length up to 'max_length' that match 'regex'""" if max_length == 0: return L = len(alphabet) for N in range(1, max_length+1): indices = [0]*N for z in xrange(L**N): r = ''.join(alphabet[i] for i in indices) if regex.match(r): yield(r) i = 0 indices[i] += 1 while (i<N) and (indices[i]==L): indices[i] = 0 i += 1 if i<N: indices[i] += 1 return example usage: alphabet = 'abcdef1234567890' import re regex = re.compile('f*[1-3]+$') for r in all_matching_strings(alphabet, 5, regex): print r which would output all strings up to length 5, starting with a sequence of f's, and then a non empty sequence of 1-3, then ending: 1 2 3 f1 11 21 31 f2 12 22 32 f3 13 23 33 ff1 [more output omitted...] A: You don't want to do this. Most of the result sets will be huge, and some will be infinite. Instead use a sequence of test vectors and apply the regex against each in turn: vectors = ( 'foo', 'bar', ... ) for result in (re.match(someregex, entry) for entry in vectors): ... A: The set of matching strings is infinite if and only if there is a quantifier (+ or *) in your regexp. Your question doesn't seem to aim at those patterns. I rather believe that the product function from itertools might help here. You might for instance introduce a special character indicating an arbitrary letter (e.g. an underscore), then build a pattern like this patt = 'a_c' and define your alphabet youralphabet = 'abcde...' and define a function generating all possible instances like this def genInstances(patt): elems = [c if c != '_' else youralphabet for c in patt] return itertools.product(*elems) You may then extend this approach to match real regexp by parsing your pattern for \d or [a-zA-Z] or whatever. A: Some regular expressions match a finite number of input strings, but many (most?) match an infinite number of input strings. It's kind of like asking 'given the python language grammar, generate all possible python programs'. You probably could write a program to list them all in sequence if you tried (though it would take infinite time to run), but are you sure you want to? Why would you want to? I'm pretty sure the regular expression engine in the standard library does not expose a way to generate the output you want. You'd have to get lower level access to the internal data structures, or implement some DFA engine thing-a-ma-bob yourself.
Generating a list of values a regex COULD match in Python
I'm trying to use a regex as an input, and from there generate all the possible values that the regex would match. So, for example, if the regex is "three-letter words starting with a, and ending in c," then the code would generate a list with the values [aac, abc, acc, adc, a1c....]. Is there an easy way to do this? I'm using python.
[ "Here's a brute force solution that should work. It has a running time of O(L^max_length) (where L is the size of the alphabet), so use it at your own risk.\ndef all_matching_strings(alphabet, max_length, regex):\n\"\"\"Find the list of all strings over 'alphabet' of length up to 'max_length' that match 'regex'\"\"\"\n\nif max_length == 0: return \n\nL = len(alphabet)\nfor N in range(1, max_length+1):\n indices = [0]*N\n for z in xrange(L**N):\n r = ''.join(alphabet[i] for i in indices)\n if regex.match(r): \n yield(r)\n\n i = 0\n indices[i] += 1\n while (i<N) and (indices[i]==L):\n indices[i] = 0\n i += 1\n if i<N: indices[i] += 1\n\nreturn\n\nexample usage:\nalphabet = 'abcdef1234567890'\nimport re\nregex = re.compile('f*[1-3]+$')\nfor r in all_matching_strings(alphabet, 5, regex): \n print r\n\nwhich would output all strings up to length 5, starting with a sequence of f's, and then a non empty sequence of 1-3, then ending:\n1\n2\n3\nf1\n11\n21\n31\nf2\n12\n22\n32\nf3\n13\n23\n33\nff1\n[more output omitted...]\n\n", "You don't want to do this. Most of the result sets will be huge, and some will be infinite. Instead use a sequence of test vectors and apply the regex against each in turn:\nvectors = (\n 'foo',\n 'bar',\n ...\n)\n\nfor result in (re.match(someregex, entry) for entry in vectors):\n ...\n\n", "The set of matching strings is infinite if and only if there is a quantifier (+ or *) in your regexp. Your question doesn't seem to aim at those patterns. I rather believe that the product function from itertools might help here.\nYou might for instance introduce a special character indicating an arbitrary letter (e.g. an underscore), then build a pattern like this\npatt = 'a_c'\n\nand define your alphabet\nyouralphabet = 'abcde...'\n\nand define a function generating all possible instances like this\ndef genInstances(patt):\n elems = [c if c != '_' else youralphabet for c in patt]\n return itertools.product(*elems)\n\nYou may then extend this approach to match real regexp by parsing your pattern for \\d or [a-zA-Z] or whatever.\n", "Some regular expressions match a finite number of input strings, but many (most?) match an infinite number of input strings. It's kind of like asking 'given the python language grammar, generate all possible python programs'. You probably could write a program to list them all in sequence if you tried (though it would take infinite time to run), but are you sure you want to? Why would you want to?\nI'm pretty sure the regular expression engine in the standard library does not expose a way to generate the output you want. You'd have to get lower level access to the internal data structures, or implement some DFA engine thing-a-ma-bob yourself.\n" ]
[ 8, 4, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002465719_python_regex.txt
Q: I want to select the distinct value from models field and then update them (django) I have models... class Item(models.Model): name = models.CharField('Item Name', max_length = 30) item_code = models.CharField(max_length = 10) color = models.CharField(max_length = 150, null = True, blank = True) size = models.CharField(max_length = 30, null = True, blank = True) fabric_code = models.CharField(max_length = 30, null = True, blank = True) I have values in Item. In the Item model name field has the similar values (but the other values of record are changed). I want to select the name field values distinctly (ie similar values select only ones) in one box (like combo box). What kind of form or views can I use? A: I don't really understand your question. Do you want to select distinct values for name, as in Item.objects.values('name').distinct() A: if you want to change a widget choices items, use something like this : choices_list = Item.objects.values_list('name','name').distinct() form_item = forms.ModelChoiceField(label = 'Select Item', choices = choices_list) As said in the django field docs : choices : An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.
I want to select the distinct value from models field and then update them (django)
I have models... class Item(models.Model): name = models.CharField('Item Name', max_length = 30) item_code = models.CharField(max_length = 10) color = models.CharField(max_length = 150, null = True, blank = True) size = models.CharField(max_length = 30, null = True, blank = True) fabric_code = models.CharField(max_length = 30, null = True, blank = True) I have values in Item. In the Item model name field has the similar values (but the other values of record are changed). I want to select the name field values distinctly (ie similar values select only ones) in one box (like combo box). What kind of form or views can I use?
[ "I don't really understand your question. Do you want to select distinct values for name, as in\nItem.objects.values('name').distinct()\n\n", "if you want to change a widget choices items, use something like this :\nchoices_list = Item.objects.values_list('name','name').distinct()\nform_item = forms.ModelChoiceField(label = 'Select Item', choices = choices_list)\n\nAs said in the django field docs :\nchoices : An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002462962_django_django_models_python.txt
Q: Remove linebreak at specific position in textfile I have a large textfile, which has linebreaks at column 80 due to console width. Many of the lines in the textfile are not 80 characters long, and are not affected by the linebreak. In pseudocode, this is what I want: Iterate through lines in file If line matches this regex pattern: ^(.{80})\n(.+) Replace this line with a new string consisting of match.group(1) and match.group(2). Just remove the linebreak from this line. If line doesn't match the regex, skip! Maybe I don't need regex to do this? A: Here's some code which should to the trick def remove_linebreaks(textfile, position=81): """ textfile : an file opened in 'r' mode position : the index on a line at which \n must be removed return a string with the \n at position removed """ fixed_lines = [] for line in textfile: if len(line) == position: line = line[:position] fixed_lines.append(line) return ''.join(fixed_lines) Note that compared to your pseudo code, this will merge any number of consecutive folded lines. A: f=open("file") for line in f: if len(line)==81: n=f.next() line=line.rstrip()+n print line.rstrip() f.close() A: Consider this. def merge_lines( line_iter ): buffer = '' for line in line_iter: if len(line) <= 80: yield buffer + line buffer= '' else: buffer += line[:-1] # remove '\n' with open('myFile','r') as source: with open('copy of myFile','w') as destination: for line in merge_lines( source ): destination.write(line) I find that an explicit generator function makes it much easier to test and debug the essential logic of the script without having to create mock filesystems or do lots of fancy setup and teardown for testing. A: Here is an example of how to use regular expressions to archive this. But regular expressions aren't the best solution everywhere and in this case, i think not using regular expressions is more efficient. Anyway, here is the solution: text = re.sub(r'(?<=^.{80})\n', '', text) You can also use the your regular expression when you call re.sub with a callable: text = re.sub(r'^(.{80})\n(.+)', lambda m: m.group(1)+m.group(2), text)
Remove linebreak at specific position in textfile
I have a large textfile, which has linebreaks at column 80 due to console width. Many of the lines in the textfile are not 80 characters long, and are not affected by the linebreak. In pseudocode, this is what I want: Iterate through lines in file If line matches this regex pattern: ^(.{80})\n(.+) Replace this line with a new string consisting of match.group(1) and match.group(2). Just remove the linebreak from this line. If line doesn't match the regex, skip! Maybe I don't need regex to do this?
[ "Here's some code which should to the trick\ndef remove_linebreaks(textfile, position=81):\n \"\"\"\n textfile : an file opened in 'r' mode\n position : the index on a line at which \\n must be removed\n\n return a string with the \\n at position removed\n \"\"\"\n fixed_lines = []\n for line in textfile:\n if len(line) == position:\n line = line[:position]\n fixed_lines.append(line)\n return ''.join(fixed_lines)\n\nNote that compared to your pseudo code, this will merge any number of consecutive folded lines. \n", "f=open(\"file\")\nfor line in f:\n if len(line)==81:\n n=f.next()\n line=line.rstrip()+n\n print line.rstrip()\nf.close()\n\n", "Consider this.\ndef merge_lines( line_iter ):\n buffer = ''\n for line in line_iter:\n if len(line) <= 80:\n yield buffer + line\n buffer= ''\n else:\n buffer += line[:-1] # remove '\\n'\n\nwith open('myFile','r') as source:\n with open('copy of myFile','w') as destination:\n for line in merge_lines( source ):\n destination.write(line)\n\nI find that an explicit generator function makes it much easier to test and debug the essential logic of the script without having to create mock filesystems or do lots of fancy setup and teardown for testing.\n", "Here is an example of how to use regular expressions to archive this. But regular expressions aren't the best solution everywhere and in this case, i think not using regular expressions is more efficient. Anyway, here is the solution:\ntext = re.sub(r'(?<=^.{80})\\n', '', text)\n\nYou can also use the your regular expression when you call re.sub with a callable:\ntext = re.sub(r'^(.{80})\\n(.+)', lambda m: m.group(1)+m.group(2), text)\n\n" ]
[ 1, 1, 1, 0 ]
[]
[]
[ "line_breaks", "python", "regex" ]
stackoverflow_0002468460_line_breaks_python_regex.txt
Q: How do I run Javascript tests in Windmill when using test_windmill for Django? I'm using the Windmill test system and have it running using test_windmill for Django which works fine for the Python tests. I'd like this to run a suite of Javascript tests also whilst the Django test server is running. I've used the run_js_tests call from the Windmill shell which works fine but I can't find a way to have this run as part of the Python tests. Does anyone know how to do this? Thanks Rob A: Ok, so couldn't find out how to do this so I'm running the website under Apache and using the windmill standard jstests parameter to run the Javascript tests against this.
How do I run Javascript tests in Windmill when using test_windmill for Django?
I'm using the Windmill test system and have it running using test_windmill for Django which works fine for the Python tests. I'd like this to run a suite of Javascript tests also whilst the Django test server is running. I've used the run_js_tests call from the Windmill shell which works fine but I can't find a way to have this run as part of the Python tests. Does anyone know how to do this? Thanks Rob
[ "Ok, so couldn't find out how to do this so I'm running the website under Apache and using the windmill standard jstests parameter to run the Javascript tests against this.\n" ]
[ 0 ]
[]
[]
[ "automated_tests", "django", "python", "unit_testing", "windmill" ]
stackoverflow_0002373446_automated_tests_django_python_unit_testing_windmill.txt
Q: Finding the version of an application from Python? Basically i am trying to find out what version of ArcGIS the user currently has installed, i looked through the registry and couldn't find anything related to a version string. However i know it is stored, within the .exe. I've done a fair bit of googling, and can't find anything really worth it. I tried using the GetFileVersionInfo, and i seem to get a random mishmash of stuff. Any ideas? EDIT Sigh.... Turns out pywin32 is not always installed on all machines. Does anyone know if its possible to do the same thing via ctypes? Also this is only for windows. A: If you prefer not to do this using pywin32, you would be able to do this with ctypes, for sure. The trick will be decoding that silly file version structure that comes back. There's one old mailing list post that is doing what you're asking. Unfortunately, I don't have a windows box handy to test this myself, right now. But if it doesn't work, it should at least give you a good start. Here's the code, in case those 2006 archives vanish sometime: import array from ctypes import * def get_file_info(filename, info): """ Extract information from a file. """ # Get size needed for buffer (0 if no info) size = windll.version.GetFileVersionInfoSizeA(filename, None) # If no info in file -> empty string if not size: return '' # Create buffer res = create_string_buffer(size) # Load file informations into buffer res windll.version.GetFileVersionInfoA(filename, None, size, res) r = c_uint() l = c_uint() # Look for codepages windll.version.VerQueryValueA(res, '\\VarFileInfo\\Translation', byref(r), byref(l)) # If no codepage -> empty string if not l.value: return '' # Take the first codepage (what else ?) codepages = array.array('H', string_at(r.value, l.value)) codepage = tuple(codepages[:2].tolist()) # Extract information windll.version.VerQueryValueA(res, ('\\StringFileInfo\\%04x%04x\\' + info) % codepage, byref(r), byref(l)) return string_at(r.value, l.value) print get_file_info(r'C:\WINDOWS\system32\calc.exe', 'FileVersion') -- Ok - back near a windows box. Have actually tried this code now. "Works for me". >>> print get_file_info(r'C:\WINDOWS\system32\calc.exe', 'FileVersion') 6.1.7600.16385 (win7_rtm.090713-1255) A: there's a gnu linux utility called 'strings' that prints the printable characters in any file(binary or non-binary), try using that and look for a version number like pattern on windows, you can get strings here http://unxutils.sourceforge.net/
Finding the version of an application from Python?
Basically i am trying to find out what version of ArcGIS the user currently has installed, i looked through the registry and couldn't find anything related to a version string. However i know it is stored, within the .exe. I've done a fair bit of googling, and can't find anything really worth it. I tried using the GetFileVersionInfo, and i seem to get a random mishmash of stuff. Any ideas? EDIT Sigh.... Turns out pywin32 is not always installed on all machines. Does anyone know if its possible to do the same thing via ctypes? Also this is only for windows.
[ "If you prefer not to do this using pywin32, you would be able to do this with ctypes, for sure.\nThe trick will be decoding that silly file version structure that comes back.\nThere's one old mailing list post that is doing what you're asking. Unfortunately, I don't have a windows box handy to test this myself, right now. But if it doesn't work, it should at least give you a good start.\nHere's the code, in case those 2006 archives vanish sometime:\nimport array\nfrom ctypes import *\n\ndef get_file_info(filename, info):\n \"\"\"\n Extract information from a file.\n \"\"\"\n # Get size needed for buffer (0 if no info)\n size = windll.version.GetFileVersionInfoSizeA(filename, None)\n # If no info in file -> empty string\n if not size:\n return ''\n # Create buffer\n res = create_string_buffer(size)\n # Load file informations into buffer res\n windll.version.GetFileVersionInfoA(filename, None, size, res)\n r = c_uint()\n l = c_uint()\n # Look for codepages\n windll.version.VerQueryValueA(res, '\\\\VarFileInfo\\\\Translation',\n byref(r), byref(l))\n # If no codepage -> empty string\n if not l.value:\n return ''\n # Take the first codepage (what else ?)\n codepages = array.array('H', string_at(r.value, l.value))\n codepage = tuple(codepages[:2].tolist())\n # Extract information\n windll.version.VerQueryValueA(res, ('\\\\StringFileInfo\\\\%04x%04x\\\\'\n+ info) % codepage, byref(r), byref(l))\n return string_at(r.value, l.value)\n\nprint get_file_info(r'C:\\WINDOWS\\system32\\calc.exe', 'FileVersion')\n\n--\nOk - back near a windows box. Have actually tried this code now. \"Works for me\".\n>>> print get_file_info(r'C:\\WINDOWS\\system32\\calc.exe', 'FileVersion')\n6.1.7600.16385 (win7_rtm.090713-1255)\n\n", "there's a gnu linux utility called 'strings' that prints the printable characters in any file(binary or non-binary), try using that and look for a version number like pattern\non windows, you can get strings here http://unxutils.sourceforge.net/\n" ]
[ 2, 0 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0002270345_python_winapi.txt
Q: What are good Python and/or Django deployment solutions? For now I use some mix between virtual_env, pip and Fabric. This allows to: install required libs; generate dynamic content; isolate installation; push everything through ssh. It works well, I just want to know if there are other tools around. The only problem I could think of is that it's a lot of to set up every time. It doesn't solve database / media files migration issues either, but maybe I should just open another question for this specific subject. Eventually, I don't know how to automatize the server setup. I'd love to have a tool to let me configure Apache/Lighttp/Cherokee and MySQL automatically. Related : How django projects can be deployed with minimal installation works? A: Fabric is the best solution for you. You can do everything you need using Fabric.
What are good Python and/or Django deployment solutions?
For now I use some mix between virtual_env, pip and Fabric. This allows to: install required libs; generate dynamic content; isolate installation; push everything through ssh. It works well, I just want to know if there are other tools around. The only problem I could think of is that it's a lot of to set up every time. It doesn't solve database / media files migration issues either, but maybe I should just open another question for this specific subject. Eventually, I don't know how to automatize the server setup. I'd love to have a tool to let me configure Apache/Lighttp/Cherokee and MySQL automatically. Related : How django projects can be deployed with minimal installation works?
[ "Fabric is the best solution for you. You can do everything you need using Fabric.\n" ]
[ 1 ]
[]
[]
[ "deployment", "python" ]
stackoverflow_0002441661_deployment_python.txt
Q: merge excel cells using pyExcelerator I want to merge two cells in excel using pyExcelerator , ws.write_merge(r1=0,r2=1,c1=0, c2=0, label='test1', style=style1) #merge cell1(row=0, column=0) with cell2(row=1, column=0) Why the errors happen? AssertionErrors,0 < 0 errors A: Because the package author put an assertion in Cell.py that would blow up if he ever tried to write a MULBLANKS record with too few columns. Your one-column-wide merged cells block stepped on the mine. Suggestion: Instead of pyExcelerator, use xlwt. xlwt is a fork of pyExcelerator, with many bugs fixed (including this one) and several enhancements. pyExcelerator is believed not to be under maintenance. xlwt will run almost all code that works on pyExcelerator. The exceptions are not in demand by xlwt users. This site will lead you to the download site and inform you about the sibling xlrd and xlutils packages. Disclosure: I'm the maintainer of xlwt and author of xlrd. Update This bug is mentioned in the pyExcelerator tracker on sourceforge. However the suggested fix is not one that I would recommend. Just get xlwt.
merge excel cells using pyExcelerator
I want to merge two cells in excel using pyExcelerator , ws.write_merge(r1=0,r2=1,c1=0, c2=0, label='test1', style=style1) #merge cell1(row=0, column=0) with cell2(row=1, column=0) Why the errors happen? AssertionErrors,0 < 0 errors
[ "Because the package author put an assertion in Cell.py that would blow up if he ever tried to write a MULBLANKS record with too few columns. Your one-column-wide merged cells block stepped on the mine.\nSuggestion: Instead of pyExcelerator, use xlwt. xlwt is a fork of pyExcelerator, with many bugs fixed (including this one) and several enhancements. pyExcelerator is believed not to be under maintenance. xlwt will run almost all code that works on pyExcelerator. The exceptions are not in demand by xlwt users.\nThis site will lead you to the download site and inform you about the sibling xlrd and xlutils packages.\nDisclosure: I'm the maintainer of xlwt and author of xlrd.\nUpdate This bug is mentioned in the pyExcelerator tracker on sourceforge. However the suggested fix is not one that I would recommend. Just get xlwt.\n" ]
[ 3 ]
[]
[]
[ "pyexcelerator", "python", "xlwt" ]
stackoverflow_0002469167_pyexcelerator_python_xlwt.txt
Q: Default value for file path in function gives SyntaxError. Work around? for this, import os.path def f(data_file_path=os.path.join(os.getcwd(),'temp'),type): ... return data I get this, SyntaxError: non-default argument follows default argument Is there a way to make this work or do I have to define a variable such as, rawdata_path = os.path.join(os.getcwd(),'temp') and then plug that into the function? A: Move type before data_file_path def f(type,data_file_path=os.path.join(os.getcwd(),'temp')): Assigning values in the function parameter called default arguments, those should come afther non-default arguments A: You have to switch the order of the arguments. Mandatory arguments (without default values) must come before arguments with set default values. A: Rearrange the parameters: def f(type, data_file_path=os.path.join(os.getcwd(),'temp')): pass The reason for this is, that arguments with default values can be omitted. But of you call f('foo'), it is not know if you want to set the type and omit data_file_path or not. A: Arguments with a default value should be placed after all arguments without a default value. Change it to: import os.path def f(type, data_file_path=os.path.join(os.getcwd(),'temp')): ... return data A: Never mind. SyntaxError: non-default argument follows default argument refers to the order of the arguments so, def f(type,data_file_path=os.path.join(os.getcwd(),'temp')): works! me newbie
Default value for file path in function gives SyntaxError. Work around?
for this, import os.path def f(data_file_path=os.path.join(os.getcwd(),'temp'),type): ... return data I get this, SyntaxError: non-default argument follows default argument Is there a way to make this work or do I have to define a variable such as, rawdata_path = os.path.join(os.getcwd(),'temp') and then plug that into the function?
[ "Move type before data_file_path\ndef f(type,data_file_path=os.path.join(os.getcwd(),'temp')):\n\nAssigning values in the function parameter called default arguments, those should come afther non-default arguments\n", "You have to switch the order of the arguments. Mandatory arguments (without default values) must come before arguments with set default values. \n", "Rearrange the parameters:\ndef f(type, data_file_path=os.path.join(os.getcwd(),'temp')):\n pass\n\nThe reason for this is, that arguments with default values can be omitted.\nBut of you call f('foo'), it is not know if you want to set the type and omit data_file_path or not.\n", "Arguments with a default value should be placed after all arguments without a default value.\nChange it to:\nimport os.path\n\ndef f(type, data_file_path=os.path.join(os.getcwd(),'temp')):\n ...\n return data\n\n", "Never mind.\nSyntaxError: non-default argument follows default argument \n\nrefers to the order of the arguments so,\ndef f(type,data_file_path=os.path.join(os.getcwd(),'temp')):\n\nworks!\nme newbie\n" ]
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "default_value", "function", "python" ]
stackoverflow_0002469538_default_value_function_python.txt
Q: Talking to printer from Python CGI I have a Python CGI. I want to print the data in the page. There will be a print button and when the user clicks teh button, I need to do some processing and send the data to the printer. I similarly want to implement 'Export to excel'. Please let me know how to do these A: Do you want to print to the user's printer, or the server's? If it's the user's, this is a job for client-side Javascript, not CGI.
Talking to printer from Python CGI
I have a Python CGI. I want to print the data in the page. There will be a print button and when the user clicks teh button, I need to do some processing and send the data to the printer. I similarly want to implement 'Export to excel'. Please let me know how to do these
[ "Do you want to print to the user's printer, or the server's? If it's the user's, this is a job for client-side Javascript, not CGI.\n" ]
[ 1 ]
[]
[]
[ "cgi", "excel", "printing", "python" ]
stackoverflow_0002469368_cgi_excel_printing_python.txt
Q: Calculating a range of an exact number of values in Python I'm building a range between two numbers (floats) and I'd like this range to be of an exact fixed length (no more, no less). range and arange work with steps, instead. To put things into pseudo Python, this is what I'd like to achieve: start_value = -7.5 end_value = 0.1 my_range = my_range_function(star_value, end_value, length=6) print my_range [-7.50,-5.98,-4.46,-2.94,-1.42,0.10] This is essentially equivalent to the R function seq which can specify a sequence of a given length. Is this possible in Python? Thanks. A: Use linspace() from NumPy. >>> from numpy import linspace >>> linspace(-7.5, 0.1, 6) array([-7.5 , -5.98, -4.46, -2.94, -1.42, 0.1]) >>> linspace(-7.5, 0.1, 6).tolist() [-7.5, -5.9800000000000004, -4.46, -2.9399999999999995, -1.4199999999999999, 0.10000000000000001] It should be the most efficient and accurate. A: See Recipe 66472: frange(), a range function with float increments (Python) with various float implementations, their pros and cons. Alternatively, if precision is important to you, work with decimal.Decimal instead of float (convert to and then back) as answered in Python decimal range() step value. A: def my_function(start, end, length): len = length - 1 incr = (end-start) / len r = [ start ] for i in range(len): r.append ( r[i] + incr ) return r A: How about this: def my_range_function(start, end, length): if length <= 1: return [ start ] step = (end - start) / (length - 1) return [(start + i * step) for i in xrange(length)] For your sample range, it returns: [-7.5, -5.9800000000000004, -4.46, -2.9399999999999995, -1.4199999999999999, 0.099999999999999645] Of course it's full of round errors, but that's what you get when working with floats. A: In order to handle the rounding errors, the following code utilizes Python's decimal module. You can set the rounding; for this sample I've set it to two decimal points via round_setting = '.01'. In order to handle any rounding errors, the last step is adjusted to the remainder. Code #!/usr/bin/env python # encoding: utf-8 from __future__ import print_function import math import decimal start_value = -7.5 end_value = 0.1 num_of_steps = 6 def my_range(start_value, end_value, num_of_steps): round_setting = '.01' start_decimal = decimal.Decimal(str(start_value)).quantize( decimal.Decimal(round_setting)) end_decimal = decimal.Decimal(str(end_value)).quantize( decimal.Decimal(round_setting)) num_of_steps_decimal = decimal.Decimal(str(num_of_steps)).quantize( decimal.Decimal(round_setting)) step_decimal = ((end_decimal - start_decimal) / num_of_steps_decimal).quantize(decimal.Decimal(round_setting)) # Change the last step in case there are rounding errors last_step_decimal = (end_decimal - ((num_of_steps - 1) * step_decimal) - start_decimal).quantize(decimal.Decimal(round_setting)) print('Start value = ', start_decimal) print('End value = ', end_decimal) print('Number of steps = ', num_of_steps) print('Normal step for range = ', step_decimal) print('Last step used for range = ', last_step_decimal) my_range(start_value, end_value, num_of_steps) Output $ ./fixed_range.py Start value = -7.50 End value = 0.10 Number of steps = 6 Normal step for range = 1.27 Last step used for range = 1.25 From there you can use the normal step and the last step to create your list.
Calculating a range of an exact number of values in Python
I'm building a range between two numbers (floats) and I'd like this range to be of an exact fixed length (no more, no less). range and arange work with steps, instead. To put things into pseudo Python, this is what I'd like to achieve: start_value = -7.5 end_value = 0.1 my_range = my_range_function(star_value, end_value, length=6) print my_range [-7.50,-5.98,-4.46,-2.94,-1.42,0.10] This is essentially equivalent to the R function seq which can specify a sequence of a given length. Is this possible in Python? Thanks.
[ "Use linspace() from NumPy.\n>>> from numpy import linspace\n>>> linspace(-7.5, 0.1, 6)\narray([-7.5 , -5.98, -4.46, -2.94, -1.42, 0.1])\n>>> linspace(-7.5, 0.1, 6).tolist()\n[-7.5, -5.9800000000000004, -4.46, -2.9399999999999995, -1.4199999999999999, 0.10000000000000001]\n\nIt should be the most efficient and accurate.\n", "See Recipe 66472: frange(), a range function with float increments (Python) with various float implementations, their pros and cons.\nAlternatively, if precision is important to you, work with decimal.Decimal instead of float (convert to and then back) as answered in Python decimal range() step value.\n", "def my_function(start, end, length):\n len = length - 1\n incr = (end-start) / len\n r = [ start ]\n for i in range(len):\n r.append ( r[i] + incr )\n return r\n\n", "How about this:\ndef my_range_function(start, end, length):\n if length <= 1: return [ start ]\n step = (end - start) / (length - 1)\n return [(start + i * step) for i in xrange(length)]\n\nFor your sample range, it returns:\n[-7.5, -5.9800000000000004, -4.46,\n -2.9399999999999995, -1.4199999999999999, 0.099999999999999645]\n\nOf course it's full of round errors, but that's what you get when working with floats.\n", "In order to handle the rounding errors, the following code utilizes Python's decimal module. You can set the rounding; for this sample I've set it to two decimal points via round_setting = '.01'. In order to handle any rounding errors, the last step is adjusted to the remainder.\nCode\n#!/usr/bin/env python\n# encoding: utf-8\nfrom __future__ import print_function\nimport math\nimport decimal\n\n\nstart_value = -7.5\nend_value = 0.1\nnum_of_steps = 6\n\ndef my_range(start_value, end_value, num_of_steps):\n round_setting = '.01'\n start_decimal = decimal.Decimal(str(start_value)).quantize(\n decimal.Decimal(round_setting))\n end_decimal = decimal.Decimal(str(end_value)).quantize(\n decimal.Decimal(round_setting))\n num_of_steps_decimal = decimal.Decimal(str(num_of_steps)).quantize(\n decimal.Decimal(round_setting))\n step_decimal = ((end_decimal - start_decimal) / \n num_of_steps_decimal).quantize(decimal.Decimal(round_setting))\n # Change the last step in case there are rounding errors\n last_step_decimal = (end_decimal - ((num_of_steps - 1) * step_decimal) -\n start_decimal).quantize(decimal.Decimal(round_setting))\n print('Start value = ', start_decimal)\n print('End value = ', end_decimal)\n print('Number of steps = ', num_of_steps)\n print('Normal step for range = ', step_decimal)\n print('Last step used for range = ', last_step_decimal)\n\nmy_range(start_value, end_value, num_of_steps)\n\nOutput\n$ ./fixed_range.py \nStart value = -7.50\nEnd value = 0.10\nNumber of steps = 6\nNormal step for range = 1.27\nLast step used for range = 1.25\n\nFrom there you can use the normal step and the last step to create your list.\n" ]
[ 6, 4, 2, 1, 1 ]
[]
[]
[ "list", "python", "range" ]
stackoverflow_0002469461_list_python_range.txt
Q: Django store regular expression in DB which then gets evaluated on page I want to store a number of url patterns in my django model which a user can provide parameters to which will create a url. For example I might store these 3 urls in my db where %s is the variable parameter provided by the user: www.thisissomewebsite.com?param=%s www.anotherurl/%s/ www.lastexample.co.uk?param1=%s&fixedparam=2 As you can see from these examples the parameter can appear anywhere in the string and not in a fixed position. I have 2 models, one holds the urls and one holds the variables: class URLPatterns(models.Model): pattern = models.CharField(max_length=255) class URLVariables(models.Model): pattern = models.ForeignKey(URLPatterns) param = models.CharField(max_length=255) What would be the best way to generate these urls by replacing the %s with the variable in the database. would it just be a simple replace on the string e.g: urlvariable = URLVariable.objects.get(pk=1) pattern = url.pattern url = pattern.replace("%s", urlvariable.param) or is there a better way? EDIT It would also be nice if the user could choose to store either a single variable or a list of variables which would then replace a number of variables in the string e.g. u = URLPatterns(pattern='www.url?param=%s&param2=%s&param3=%s') v = URLVariables(pattern=u, param='[2,6,3]') url = SOME WAY TO REPLACE THE 3 %s WITH THE 3 VARIABLES IN THE ARRAY (this would need to be converted from a string in someway) Thanks A: ast.literal_eval() can be used to parse a string into a Python value or structure. If it's a list then just pass it to tuple() before using string interpolation. A: >>> param = [2, 6, 3] >>> pattern = 'www.url?param=%s&param2=%s&param3=%s' >>> url = pattern % tuple(param) >>> url 'www.url?param=2&param2=6&param3=3' if param is a string like '[2,6,3]' you can use ast.literal_eval() or json.loads(): >>> ast.literal_eval('[2,6,3]') [2, 6, 3] or >>> json.loads(param) [2, 6, 3] or >>> simplejson.loads(param) [2, 6, 3] A: You can do this: pattern="www.url?param=%s&param2=%s&param3=%s" params = "[1, 2, 3]" url = pattern % tuple(s.strip('[] ') for s in params.split(',')) or use ast.literal_eval(params) as Ignacio suggests.
Django store regular expression in DB which then gets evaluated on page
I want to store a number of url patterns in my django model which a user can provide parameters to which will create a url. For example I might store these 3 urls in my db where %s is the variable parameter provided by the user: www.thisissomewebsite.com?param=%s www.anotherurl/%s/ www.lastexample.co.uk?param1=%s&fixedparam=2 As you can see from these examples the parameter can appear anywhere in the string and not in a fixed position. I have 2 models, one holds the urls and one holds the variables: class URLPatterns(models.Model): pattern = models.CharField(max_length=255) class URLVariables(models.Model): pattern = models.ForeignKey(URLPatterns) param = models.CharField(max_length=255) What would be the best way to generate these urls by replacing the %s with the variable in the database. would it just be a simple replace on the string e.g: urlvariable = URLVariable.objects.get(pk=1) pattern = url.pattern url = pattern.replace("%s", urlvariable.param) or is there a better way? EDIT It would also be nice if the user could choose to store either a single variable or a list of variables which would then replace a number of variables in the string e.g. u = URLPatterns(pattern='www.url?param=%s&param2=%s&param3=%s') v = URLVariables(pattern=u, param='[2,6,3]') url = SOME WAY TO REPLACE THE 3 %s WITH THE 3 VARIABLES IN THE ARRAY (this would need to be converted from a string in someway) Thanks
[ "ast.literal_eval() can be used to parse a string into a Python value or structure. If it's a list then just pass it to tuple() before using string interpolation.\n", ">>> param = [2, 6, 3]\n>>> pattern = 'www.url?param=%s&param2=%s&param3=%s'\n>>> url = pattern % tuple(param)\n>>> url\n'www.url?param=2&param2=6&param3=3'\n\nif param is a string like '[2,6,3]' you can use ast.literal_eval() or json.loads():\n>>> ast.literal_eval('[2,6,3]')\n[2, 6, 3]\n\nor\n>>> json.loads(param)\n[2, 6, 3]\n\nor\n>>> simplejson.loads(param)\n[2, 6, 3]\n\n", "You can do this:\npattern=\"www.url?param=%s&param2=%s&param3=%s\"\nparams = \"[1, 2, 3]\"\n\nurl = pattern % tuple(s.strip('[] ') for s in params.split(','))\n\nor use ast.literal_eval(params) as Ignacio suggests.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "django", "python", "replace" ]
stackoverflow_0002469640_django_python_replace.txt
Q: How do I get javascript results using selenium? I have the following code: from selenium import selenium selenium = selenium("localhost", 4444, "*chrome", "http://some_site.com/") selenium.start() sel = selenium sel.open("/") sel.type("ctl00_ContentPlaceHolder1_SuburbTownTextBox", "Adelaide,SA,5000") sel.click("ctl00_ContentPlaceHolder1_SearchImageButton") #text = sel.get_body_text() text = sel.get_html_source() print(text) The click executes a javascript file which then produces results on the same page. Obviously print(text) will only print the orignal html source. How do I get to the results of the javascript? A: try this to get the content of a html element with id=your-id : sel.get_eval("this.browserbot.getCurrentWindow().document.getElementById('your-id').innerHTML"
How do I get javascript results using selenium?
I have the following code: from selenium import selenium selenium = selenium("localhost", 4444, "*chrome", "http://some_site.com/") selenium.start() sel = selenium sel.open("/") sel.type("ctl00_ContentPlaceHolder1_SuburbTownTextBox", "Adelaide,SA,5000") sel.click("ctl00_ContentPlaceHolder1_SearchImageButton") #text = sel.get_body_text() text = sel.get_html_source() print(text) The click executes a javascript file which then produces results on the same page. Obviously print(text) will only print the orignal html source. How do I get to the results of the javascript?
[ "try this to get the content of a html element with id=your-id :\nsel.get_eval(\"this.browserbot.getCurrentWindow().document.getElementById('your-id').innerHTML\"\n\n" ]
[ 4 ]
[]
[]
[ "javascript", "python", "selenium" ]
stackoverflow_0002469701_javascript_python_selenium.txt
Q: Python objects as userdata in ctypes callback functions The C function myfunc operates on a larger chunk of data. The results are returned in chunks to a callback function: int myfunc(const char *data, int (*callback)(char *result, void *userdata), void *userdata); Using ctypes, it's no big deal to call myfunc from Python code, and to have the results being returned to a Python callback function. This callback work fine. myfunc = mylib.myfunc myfunc.restype = c_int myfuncFUNCTYPE = CFUNCTYPE(STRING, c_void_p) myfunc.argtypes = [POINTER(c_char), callbackFUNCTYPE, c_void_p] def mycb(result, userdata): print result return True input="A large chunk of data." myfunc(input, myfuncFUNCTYPE(mycb), 0) But, is there any way to give a Python object (say a list) as userdata to the callback function? In order to store away the result chunks, I'd like to do e.g.: def mycb(result, userdata): userdata.append(result) userdata=[] But I have no idea how to cast the Python list to a c_void_p, so that it can be used in the call to myfunc. My current workaround is to implement a linked list as a ctypes structure, which is quite cumbersome. A: I guess you could use the Python C API to do that... maybe you could use a PyObject pointer. edit: As the op pointed out in the comments, there's already a py_object type readily available in ctypes, so the solution is to create first a ctypes.py_object object from the python list and then casting it to c_void_p to pass it as an argument to the C function (I think this step might be unnecessary as a parameter typed as void* should accept any pointer, and it would be faster to pass just a byref). In the callback, the reverse steps are done (casting from the void pointer to a pointer to py_object and then getting the value of the contents). A workaround could be to use a closure for your callback function so it already knows in which list it has to append the items... myfunc = mylib.myfunc myfunc.restype = c_int myfuncFUNCTYPE = CFUNCTYPE(STRING) myfunc.argtypes = [POINTER(c_char), callbackFUNCTYPE] def mycb(result, userdata): userdata.append(result) input="A large chunk of data." userdata = [] myfunc(input, myfuncFUNCTYPE(lambda x: mycb(x, userdata)))
Python objects as userdata in ctypes callback functions
The C function myfunc operates on a larger chunk of data. The results are returned in chunks to a callback function: int myfunc(const char *data, int (*callback)(char *result, void *userdata), void *userdata); Using ctypes, it's no big deal to call myfunc from Python code, and to have the results being returned to a Python callback function. This callback work fine. myfunc = mylib.myfunc myfunc.restype = c_int myfuncFUNCTYPE = CFUNCTYPE(STRING, c_void_p) myfunc.argtypes = [POINTER(c_char), callbackFUNCTYPE, c_void_p] def mycb(result, userdata): print result return True input="A large chunk of data." myfunc(input, myfuncFUNCTYPE(mycb), 0) But, is there any way to give a Python object (say a list) as userdata to the callback function? In order to store away the result chunks, I'd like to do e.g.: def mycb(result, userdata): userdata.append(result) userdata=[] But I have no idea how to cast the Python list to a c_void_p, so that it can be used in the call to myfunc. My current workaround is to implement a linked list as a ctypes structure, which is quite cumbersome.
[ "I guess you could use the Python C API to do that... maybe you could use a PyObject pointer.\nedit: As the op pointed out in the comments, there's already a py_object type readily available in ctypes, so the solution is to create first a ctypes.py_object object from the python list and then casting it to c_void_p to pass it as an argument to the C function (I think this step might be unnecessary as a parameter typed as void* should accept any pointer, and it would be faster to pass just a byref). In the callback, the reverse steps are done (casting from the void pointer to a pointer to py_object and then getting the value of the contents).\nA workaround could be to use a closure for your callback function so it already knows in which list it has to append the items...\nmyfunc = mylib.myfunc\nmyfunc.restype = c_int\nmyfuncFUNCTYPE = CFUNCTYPE(STRING)\nmyfunc.argtypes = [POINTER(c_char), callbackFUNCTYPE]\n\n\ndef mycb(result, userdata):\n userdata.append(result)\n\ninput=\"A large chunk of data.\"\nuserdata = []\nmyfunc(input, myfuncFUNCTYPE(lambda x: mycb(x, userdata)))\n\n" ]
[ 4 ]
[]
[]
[ "callback", "ctypes", "python", "user_data" ]
stackoverflow_0002469975_callback_ctypes_python_user_data.txt
Q: How to check if two object are overlapping in a Canvas widget? Say I have objects within the Canvas with a tags 'stopped' and 'flying'. How do I check if any of this objects overlap each other? A: You can use the method find_overlapping find_overlapping(x1, y1, x2, y2) => tuple Returns a tuple of all items that overlap the given rectangle, or that are completely enclosed by it. And then loop through the result list looking for your tag.
How to check if two object are overlapping in a Canvas widget?
Say I have objects within the Canvas with a tags 'stopped' and 'flying'. How do I check if any of this objects overlap each other?
[ "You can use the method find_overlapping\nfind_overlapping(x1, y1, x2, y2) => tuple\n\n\nReturns a tuple of all items that overlap the given rectangle, or that are \ncompletely enclosed by it.\n\n\nAnd then loop through the result list looking for your tag.\n" ]
[ 2 ]
[]
[]
[ "overlap", "python", "tkinter_canvas" ]
stackoverflow_0002470022_overlap_python_tkinter_canvas.txt
Q: Open-source implementation of Mersenne Twister in Python? Is there any good open-source implementation of Mersenne Twister and other good random number generators in Python available? I would like to use in for teaching math and comp sci majors? I am also looking for the corresponding theoretical support. Edit: Source code of Mersenne Twister is readily available in various languages such as C (random.py) or pseudocode (Wikipedia) but I could not find one in Python. A: Mersenne Twister is an implementation that is used by standard python library. You can see it in random.py file in your python distribution. On my system (Ubuntu 9.10) it is in /usr/lib/python2.6, on Windows it should be in C:\Python26\Lib A: Found following port: #!/usr/bin/python ## a C -> python translation of MT19937, original license below ## ## A C-program for MT19937: Real number version ## genrand() generates one pseudorandom real number (double) ## which is uniformly distributed on [0,1]-interval, for each ## call. sgenrand(seed) set initial values to the working area ## of 624 words. Before genrand(), sgenrand(seed) must be ## called once. (seed is any 32-bit integer except for 0). ## Integer generator is obtained by modifying two lines. ## Coded by Takuji Nishimura, considering the suggestions by ## Topher Cooper and Marc Rieffel in July-Aug. 1997. ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Library General Public ## License as published by the Free Software Foundation; either ## version 2 of the License, or (at your option) any later ## version. ## This library is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ## See the GNU Library General Public License for more details. ## You should have received a copy of the GNU Library General ## Public License along with this library; if not, write to the ## Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA ## 02111-1307 USA ## Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. ## Any feedback is very welcome. For any question, comments, ## see http://www.math.keio.ac.jp/matumoto/emt.html or email ## matumoto@math.keio.ac.jp import sys # Period parameters N = 624 M = 397 MATRIX_A = 0x9908b0dfL # constant vector a UPPER_MASK = 0x80000000L # most significant w-r bits LOWER_MASK = 0x7fffffffL # least significant r bits # Tempering parameters TEMPERING_MASK_B = 0x9d2c5680L TEMPERING_MASK_C = 0xefc60000L def TEMPERING_SHIFT_U(y): return (y >> 11) def TEMPERING_SHIFT_S(y): return (y << 7) def TEMPERING_SHIFT_T(y): return (y << 15) def TEMPERING_SHIFT_L(y): return (y >> 18) mt = [] # the array for the state vector mti = N+1 # mti==N+1 means mt[N] is not initialized # initializing the array with a NONZERO seed def sgenrand(seed): # setting initial seeds to mt[N] using # the generator Line 25 of Table 1 in # [KNUTH 1981, The Art of Computer Programming # Vol. 2 (2nd Ed.), pp102] global mt, mti mt = [] mt.append(seed & 0xffffffffL) for i in xrange(1, N + 1): mt.append((69069 * mt[i-1]) & 0xffffffffL) mti = i # end sgenrand def genrand(): global mt, mti mag01 = [0x0L, MATRIX_A] # mag01[x] = x * MATRIX_A for x=0,1 y = 0 if mti >= N: # generate N words at one time if mti == N+1: # if sgenrand() has not been called, sgenrand(4357) # a default initial seed is used for kk in xrange((N-M) + 1): y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK) mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1] for kk in xrange(kk, N): y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK) mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1] y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK) mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1] mti = 0 y = mt[mti] mti += 1 y ^= TEMPERING_SHIFT_U(y) y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C y ^= TEMPERING_SHIFT_L(y) return ( float(y) / 0xffffffffL ) # reals def main(): sgenrand(4357) # any nonzero integer can be used as a seed for j in xrange(100): sys.stdout.write('%5f ' % genrand()) if (j%8) == 7: print print main() Not very pythonic but works
Open-source implementation of Mersenne Twister in Python?
Is there any good open-source implementation of Mersenne Twister and other good random number generators in Python available? I would like to use in for teaching math and comp sci majors? I am also looking for the corresponding theoretical support. Edit: Source code of Mersenne Twister is readily available in various languages such as C (random.py) or pseudocode (Wikipedia) but I could not find one in Python.
[ "Mersenne Twister is an implementation that is used by standard python library. You can see it in random.py file in your python distribution.\nOn my system (Ubuntu 9.10) it is in /usr/lib/python2.6, on Windows it should be in C:\\Python26\\Lib\n", "Found following port:\n#!/usr/bin/python\n\n## a C -> python translation of MT19937, original license below ##\n\n## A C-program for MT19937: Real number version\n## genrand() generates one pseudorandom real number (double)\n## which is uniformly distributed on [0,1]-interval, for each\n## call. sgenrand(seed) set initial values to the working area\n## of 624 words. Before genrand(), sgenrand(seed) must be\n## called once. (seed is any 32-bit integer except for 0).\n## Integer generator is obtained by modifying two lines.\n## Coded by Takuji Nishimura, considering the suggestions by\n## Topher Cooper and Marc Rieffel in July-Aug. 1997.\n\n## This library is free software; you can redistribute it and/or\n## modify it under the terms of the GNU Library General Public\n## License as published by the Free Software Foundation; either\n## version 2 of the License, or (at your option) any later\n## version.\n## This library is distributed in the hope that it will be useful,\n## but WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n## See the GNU Library General Public License for more details.\n## You should have received a copy of the GNU Library General\n## Public License along with this library; if not, write to the\n## Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA\n## 02111-1307 USA\n\n## Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura.\n## Any feedback is very welcome. For any question, comments,\n## see http://www.math.keio.ac.jp/matumoto/emt.html or email\n## matumoto@math.keio.ac.jp\n\n\nimport sys\n\n# Period parameters\nN = 624\nM = 397\nMATRIX_A = 0x9908b0dfL # constant vector a\nUPPER_MASK = 0x80000000L # most significant w-r bits\nLOWER_MASK = 0x7fffffffL # least significant r bits\n\n# Tempering parameters\nTEMPERING_MASK_B = 0x9d2c5680L\nTEMPERING_MASK_C = 0xefc60000L\n\ndef TEMPERING_SHIFT_U(y):\n return (y >> 11)\n\ndef TEMPERING_SHIFT_S(y):\n return (y << 7)\n\ndef TEMPERING_SHIFT_T(y):\n return (y << 15)\n\ndef TEMPERING_SHIFT_L(y):\n return (y >> 18)\n\nmt = [] # the array for the state vector\nmti = N+1 # mti==N+1 means mt[N] is not initialized\n\n# initializing the array with a NONZERO seed\ndef sgenrand(seed):\n # setting initial seeds to mt[N] using\n # the generator Line 25 of Table 1 in\n # [KNUTH 1981, The Art of Computer Programming\n # Vol. 2 (2nd Ed.), pp102]\n\n global mt, mti\n\n mt = []\n\n mt.append(seed & 0xffffffffL)\n for i in xrange(1, N + 1):\n mt.append((69069 * mt[i-1]) & 0xffffffffL)\n\n mti = i\n# end sgenrand\n\n\ndef genrand():\n global mt, mti\n\n mag01 = [0x0L, MATRIX_A]\n # mag01[x] = x * MATRIX_A for x=0,1\n y = 0\n\n if mti >= N: # generate N words at one time\n if mti == N+1: # if sgenrand() has not been called,\n sgenrand(4357) # a default initial seed is used\n\n for kk in xrange((N-M) + 1):\n y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK)\n mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1]\n\n for kk in xrange(kk, N):\n y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK)\n mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1]\n\n y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK)\n mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1]\n\n mti = 0\n\n y = mt[mti]\n mti += 1\n y ^= TEMPERING_SHIFT_U(y)\n y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B\n y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C\n y ^= TEMPERING_SHIFT_L(y)\n\n return ( float(y) / 0xffffffffL ) # reals\n\n\ndef main():\n sgenrand(4357) # any nonzero integer can be used as a seed\n for j in xrange(100):\n sys.stdout.write('%5f ' % genrand())\n if (j%8) == 7:\n print\n print\n\nmain()\n\nNot very pythonic but works\n" ]
[ 7, 5 ]
[]
[]
[ "mersenne_twister", "open_source", "python", "random" ]
stackoverflow_0002469031_mersenne_twister_open_source_python_random.txt
Q: OpenCV performance in different languages I'm doing some prototyping with OpenCV for a hobby project involving processing of real time camera data. I wonder if it is worth the effort to reimplement this in C or C++ when I have it all figured out or if no significant performance boost can be expected. The program basically chains OpenCV functions, so the main part of the work should be done in native code anyway. A: You've answered your own question pretty well. Most of the expensive computations should be within the OpenCV library, and thus independent of the language you use. If you're really concerned about efficiency, you could profile your code and confirm that this is indeed the case. If need be, your custom processing functions, if any, could be coded in C/C++ and exposed in python through the method of your choice (eg: boost-python), to follow the same approach. But in my experience, python works just fine as a "composition" tool for such a use. A: OpenCV used to utilize IPP, which is very fast. However, OpenCV 2.0 does not. You might customize your OpenCV using IPP, for example color conversion routines.
OpenCV performance in different languages
I'm doing some prototyping with OpenCV for a hobby project involving processing of real time camera data. I wonder if it is worth the effort to reimplement this in C or C++ when I have it all figured out or if no significant performance boost can be expected. The program basically chains OpenCV functions, so the main part of the work should be done in native code anyway.
[ "You've answered your own question pretty well. Most of the expensive computations should be within the OpenCV library, and thus independent of the language you use. \nIf you're really concerned about efficiency, you could profile your code and confirm that this is indeed the case. If need be, your custom processing functions, if any, could be coded in C/C++ and exposed in python through the method of your choice (eg: boost-python), to follow the same approach.\nBut in my experience, python works just fine as a \"composition\" tool for such a use.\n", "OpenCV used to utilize IPP, which is very fast. However, OpenCV 2.0 does not. You might customize your OpenCV using IPP, for example color conversion routines. \n" ]
[ 5, 0 ]
[]
[]
[ "c", "c++", "opencv", "performance", "python" ]
stackoverflow_0002432792_c_c++_opencv_performance_python.txt
Q: Error -3 while decompressing data: incorrect header check I have .zip file which contain csv data. I am reading .zip file using <input type = "file" name = "select_file"/> I want to decompress that .zip file and read csv data. file_data = self.request.get('select_file') file_str = zlib.decompress(file_data) #file_data_list = file_str.split('\n') #file_Reader = csv.reader(file_data_list,quoting=csv.QUOTE_NONE ) I am expecting csv data in file_str but I am getting error. error :: Error -3 while decompressing data: incorrect header check What I have to use? A: Try making a zipfile.ZipFile object instead -- as the first argument, you need an open file-like object, so first make one out of your file_data bytes with cStringIO.
Error -3 while decompressing data: incorrect header check
I have .zip file which contain csv data. I am reading .zip file using <input type = "file" name = "select_file"/> I want to decompress that .zip file and read csv data. file_data = self.request.get('select_file') file_str = zlib.decompress(file_data) #file_data_list = file_str.split('\n') #file_Reader = csv.reader(file_data_list,quoting=csv.QUOTE_NONE ) I am expecting csv data in file_str but I am getting error. error :: Error -3 while decompressing data: incorrect header check What I have to use?
[ "Try making a zipfile.ZipFile object instead -- as the first argument, you need an open file-like object, so first make one out of your file_data bytes with cStringIO.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002470389_python.txt
Q: Can a python webapp be bundled into a single file for deployment? Is it possible for a python webapp to be bundled (gzipped?) into a single file, along with any required resources (js/css files) & modules (including modules like lxml which are mostly C-based), for easy deployment onto a linux webserver? A: Yes. You can create a windows executable using py2exe. A better way to manage deployment is to package your app with a setup.py file, listing all needed dependencies, and listing non-python support files in the MANIFEST.in file. Then you can package it into a bundle using setup.py sdist, and install it with pip. See Tarek Ziade's Hitchhiker's Guide to Packaging for more details. A: For standalones ,you could try : OS X : py2app For Windows py2exe. Not sure if this would apply to your 'webapp' though. A: PyInstaller is perhaps the best cross-platform packager (in the SVN trunk version: 1.3, the latest packaged release, is very old and crufty -- no idea why my friends who took over maintenance over a year ago and did so many enhancements keep resisting my entreaties to make another release, already!-) -- you can package for Windows, Linux or Mac, and it directly supports many popular third-party packages too.
Can a python webapp be bundled into a single file for deployment?
Is it possible for a python webapp to be bundled (gzipped?) into a single file, along with any required resources (js/css files) & modules (including modules like lxml which are mostly C-based), for easy deployment onto a linux webserver?
[ "Yes. You can create a windows executable using py2exe. A better way to manage deployment is to package your app with a setup.py file, listing all needed dependencies, and listing non-python support files in the MANIFEST.in file. Then you can package it into a bundle using setup.py sdist, and install it with pip. See Tarek Ziade's Hitchhiker's Guide to Packaging for more details.\n", "For standalones ,you could try : \nOS X : py2app\nFor Windows py2exe.\nNot sure if this would apply to your 'webapp' though.\n", "PyInstaller is perhaps the best cross-platform packager (in the SVN trunk version: 1.3, the latest packaged release, is very old and crufty -- no idea why my friends who took over maintenance over a year ago and did so many enhancements keep resisting my entreaties to make another release, already!-) -- you can package for Windows, Linux or Mac, and it directly supports many popular third-party packages too.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "deployment", "python" ]
stackoverflow_0002470182_deployment_python.txt
Q: python union of 2 nested lists with index I want to get the union of 2 nested lists plus an index to the common values. I have two lists like A = [[1,2,3],[4,5,6],[7,8,9]] and B = [[1,2,3,4],[3,3,5,7]] but the length of each list is about 100 000. To A belongs an index vector with len(A): I = [2,3,4] What I want is to find all sublists in B where the first 3 elements are equal to a sublist in A. In this example I want to get B[0] returned ([1,2,3,4]) because its first three elements are equal to A[0]. In addition, I also want the index to A[0] in this example, that is I[0]. I tried different things, but nothing worked so far :( First I tried this: Common = [] for i in range(len(B)): if B[i][:3] in A: id = [I[x] for x,y in enumerate(A) if y == B[i][:3]][0] ctdCommon.append([int(id)] + B[i]) But that takes ages, or never finishes Then I transformed A and B into sets and took the union from both, which was very quick, but then I don't know how to get the corresponding indices Does anyone have an idea? A: Create an auxiliary dict (work is O(len(A)) -- assuming the first three items of a sublist in A uniquely identify it (otherwise you need a dict of lists): aud = dict((tuple(a[:3]), i) for i, a in enumerate(A)) Use said dict to loop once on B (work is O(len(B))) to get B sublists and A indices: result = [(b, aud[tuple(b[:3])]) for b in B if tuple(b[:3]) in aud]
python union of 2 nested lists with index
I want to get the union of 2 nested lists plus an index to the common values. I have two lists like A = [[1,2,3],[4,5,6],[7,8,9]] and B = [[1,2,3,4],[3,3,5,7]] but the length of each list is about 100 000. To A belongs an index vector with len(A): I = [2,3,4] What I want is to find all sublists in B where the first 3 elements are equal to a sublist in A. In this example I want to get B[0] returned ([1,2,3,4]) because its first three elements are equal to A[0]. In addition, I also want the index to A[0] in this example, that is I[0]. I tried different things, but nothing worked so far :( First I tried this: Common = [] for i in range(len(B)): if B[i][:3] in A: id = [I[x] for x,y in enumerate(A) if y == B[i][:3]][0] ctdCommon.append([int(id)] + B[i]) But that takes ages, or never finishes Then I transformed A and B into sets and took the union from both, which was very quick, but then I don't know how to get the corresponding indices Does anyone have an idea?
[ "Create an auxiliary dict (work is O(len(A)) -- assuming the first three items of a sublist in A uniquely identify it (otherwise you need a dict of lists):\naud = dict((tuple(a[:3]), i) for i, a in enumerate(A))\n\nUse said dict to loop once on B (work is O(len(B))) to get B sublists and A indices:\nresult = [(b, aud[tuple(b[:3])]) for b in B if tuple(b[:3]) in aud]\n\n" ]
[ 1 ]
[]
[]
[ "dataset", "list", "nested", "python", "union" ]
stackoverflow_0002470764_dataset_list_nested_python_union.txt
Q: Artificial Intelligence in online game using Google App Engine I am currently in the planning stages of a game for google app engine, but cannot wrap my head around how I am going to handle AI. I intend to have persistant NPCs that will move about the map, but short of writing a program that generates the same XML requests I use to control player actions, than run it on another server I am stuck on how to do it. I have looked at the Task Queue feature, but due to long running processes not being an option on the App engine, I am a little stuck. I intend to run multiple server instances with 200+ persistant NPC entities that I will need to update. Most action is slowly roaming around based on player movements/concentrations, and attacking close range players...(you can probably guess the type of game im developing) A: Will your game be turn based or real time? Either way, I think you have 2 options to look into. One is to use the Cron feature so you can schedule NPC updates at regular intervals, the other is to stick a "update NPCs" task into the Task Queue every time a human player moves. A: If the game is turn based then it would probably be best to avoid the Cron task and just update the NPCs every time the player moves. I'm not sure how big of a map you are planning on but you may consider even having the player object find the NPCs that are close to it and call their AI routine. That way NPCs that are out of range of a player wouldn't move at all which may save on resources. Not sure if that matter though. A: Bear in mind that you can also break up your updates into multiple requests (internally): do a bit of work, redirect to the same handler but different state; do more work; etc. (I'm failing somehow to comment on Peter Recore's answer, which is where this really belongs.) I see that the free service only allows 100k task queue calls/day, so 1 task/NPC would probably use up your resources way too fast. Cron job to do some work/create task queues to update NPCs in appropriately-sized groups? Anyway, just some thoughts; good luck.
Artificial Intelligence in online game using Google App Engine
I am currently in the planning stages of a game for google app engine, but cannot wrap my head around how I am going to handle AI. I intend to have persistant NPCs that will move about the map, but short of writing a program that generates the same XML requests I use to control player actions, than run it on another server I am stuck on how to do it. I have looked at the Task Queue feature, but due to long running processes not being an option on the App engine, I am a little stuck. I intend to run multiple server instances with 200+ persistant NPC entities that I will need to update. Most action is slowly roaming around based on player movements/concentrations, and attacking close range players...(you can probably guess the type of game im developing)
[ "Will your game be turn based or real time?\nEither way, I think you have 2 options to look into. One is to use the Cron feature so you can schedule NPC updates at regular intervals, the other is to stick a \"update NPCs\" task into the Task Queue every time a human player moves.\n", "If the game is turn based then it would probably be best to avoid the Cron task and just update the NPCs every time the player moves. I'm not sure how big of a map you are planning on but you may consider even having the player object find the NPCs that are close to it and call their AI routine. That way NPCs that are out of range of a player wouldn't move at all which may save on resources. Not sure if that matter though.\n", "Bear in mind that you can also break up your updates into multiple requests (internally): do a bit of work, redirect to the same handler but different state; do more work; etc. (I'm failing somehow to comment on Peter Recore's answer, which is where this really belongs.)\nI see that the free service only allows 100k task queue calls/day, so 1 task/NPC would probably use up your resources way too fast. Cron job to do some work/create task queues to update NPCs in appropriately-sized groups? \nAnyway, just some thoughts; good luck.\n" ]
[ 3, 2, 2 ]
[]
[]
[ "artificial_intelligence", "google_app_engine", "python" ]
stackoverflow_0002465056_artificial_intelligence_google_app_engine_python.txt
Q: Problems with installing jcc and pylucene I'm trying to install pylucene on Windows XP. I installed JDK on C:\Programme\Java\jdk1.6.0_18 . I also installed Visual Studio C++ Express to have a C++ compiler. As first step I'm trying to integrate jcc into python2.6 through the command: C:\Python26\python.exe setup.py build This gives me the following result: C:\Installfiles\pylucene-3.0.1-1\jcc>C:\Python26\python.exe setup.py build Traceback (most recent call last): File "setup.py", line 332, in <module> main('--debug' in sys.argv) File "setup.py", line 289, in main raise type(e), "%s: %s" %(e, args) WindowsError: [Error 2] Das System kann die angegebene Datei nicht finden: ['jav ac.exe', '-d', 'jcc/classes', 'java/org/apache/jcc/PythonVM.java', 'java/org/apa che/jcc/PythonException.java'] Other information: In systems I set: Uservariables: CLASSPATH C:\Programme\Java\jdk1.6.0_18\bin\javac.exe System Variables Path %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem; C:\Programme\Java\jdk1.6.0_18\bin Where does the error come from and what do I have to do to overcome it? A: Is there really a space in "jav ac.exe", as shown in the error message? Can setup.py just call javac.exe (is the java binaries directory in the PATH?) Disclaimer: I've built jcc and pylucene on mac os x and linux, but not on windows.
Problems with installing jcc and pylucene
I'm trying to install pylucene on Windows XP. I installed JDK on C:\Programme\Java\jdk1.6.0_18 . I also installed Visual Studio C++ Express to have a C++ compiler. As first step I'm trying to integrate jcc into python2.6 through the command: C:\Python26\python.exe setup.py build This gives me the following result: C:\Installfiles\pylucene-3.0.1-1\jcc>C:\Python26\python.exe setup.py build Traceback (most recent call last): File "setup.py", line 332, in <module> main('--debug' in sys.argv) File "setup.py", line 289, in main raise type(e), "%s: %s" %(e, args) WindowsError: [Error 2] Das System kann die angegebene Datei nicht finden: ['jav ac.exe', '-d', 'jcc/classes', 'java/org/apache/jcc/PythonVM.java', 'java/org/apa che/jcc/PythonException.java'] Other information: In systems I set: Uservariables: CLASSPATH C:\Programme\Java\jdk1.6.0_18\bin\javac.exe System Variables Path %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem; C:\Programme\Java\jdk1.6.0_18\bin Where does the error come from and what do I have to do to overcome it?
[ "Is there really a space in \"jav ac.exe\", as shown in the error message? Can setup.py just call javac.exe (is the java binaries directory in the PATH?)\nDisclaimer: I've built jcc and pylucene on mac os x and linux, but not on windows.\n" ]
[ 0 ]
[]
[]
[ "java", "jcc", "pylucene", "python" ]
stackoverflow_0002468872_java_jcc_pylucene_python.txt
Q: convert string of millisecond into datetime in python I am a newbie in Python. I want to subtract interval time from my log file, but the problem is I cannot convert millisecond string of log file into datetime format. For example, I have 15:55:05.12345 and I want to remove 5.12345 seconds from this string, and show result of 15.55.00.00000 in Python. How can I do that? Currently, I am using python 2.5. Thank you in advance. Sorry, I meant I want to subtract value for example, remove 00:00:05.1000 so, i should get 15:55:00:02345 A: >>> import datetime >>> s = '15:55:05.12345' >>> datetime.datetime.strptime(s.rpartition('.')[0], '%H:%M:%S').strftime('%H.%M.00.00000') '15.55.00.00000' edit after clarification: there is no way to do this with Python standard library, only working directly with strings: >>> s[:6]+ '00' + s[-6:] '15:55:00.12345' A: I see that you need to subtract from the value, so I would use timedelta objects because you can do math with those. >>> value = '15:55:05.123450' >>> m = re.match('(\d+):(\d+):(\d+\.\d+)', value) >>> hour = int(m.group(1)) >>> min = int(m.group(2)) >>> sec = float(m.group(3)) >>> now = datetime.timedelta(hours=hour,minutes=min,seconds=sec) >>> str(now) '15:55:05.123450' >>> >>> delta = datetime.timedelta(seconds=5.1) >>> >>> earlier = (now - delta) >>> str(earlier) '15:55:00.023450' >>>
convert string of millisecond into datetime in python
I am a newbie in Python. I want to subtract interval time from my log file, but the problem is I cannot convert millisecond string of log file into datetime format. For example, I have 15:55:05.12345 and I want to remove 5.12345 seconds from this string, and show result of 15.55.00.00000 in Python. How can I do that? Currently, I am using python 2.5. Thank you in advance. Sorry, I meant I want to subtract value for example, remove 00:00:05.1000 so, i should get 15:55:00:02345
[ ">>> import datetime\n>>> s = '15:55:05.12345'\n>>> datetime.datetime.strptime(s.rpartition('.')[0], '%H:%M:%S').strftime('%H.%M.00.00000')\n'15.55.00.00000'\n\nedit after clarification:\nthere is no way to do this with Python standard library, only working directly with strings:\n>>> s[:6]+ '00' + s[-6:]\n'15:55:00.12345'\n\n", "I see that you need to subtract from the value, so I would use timedelta objects because you can do math with those.\n>>> value = '15:55:05.123450'\n>>> m = re.match('(\\d+):(\\d+):(\\d+\\.\\d+)', value)\n>>> hour = int(m.group(1))\n>>> min = int(m.group(2))\n>>> sec = float(m.group(3))\n>>> now = datetime.timedelta(hours=hour,minutes=min,seconds=sec)\n>>> str(now)\n'15:55:05.123450'\n>>>\n>>> delta = datetime.timedelta(seconds=5.1)\n>>>\n>>> earlier = (now - delta)\n>>> str(earlier)\n'15:55:00.023450'\n>>>\n\n" ]
[ 1, 0 ]
[]
[]
[ "datetime", "python", "python_2.5" ]
stackoverflow_0002470784_datetime_python_python_2.5.txt
Q: How can I use python itertools.groupby() to group a list of strings by their first character? I have a list of strings similar to this list: tags = ('apples', 'apricots', 'oranges', 'pears', 'peaches') How should I go about grouping this list by the first character in each string using itertools.groupby()? How should I supply the 'key' argument required by itertools.groupby()? A: You might want to create dict afterwards: from itertools import groupby d = {k: list(v) for k, v in groupby(sorted(tags), key=lambda x: x[0])} A: groupby(sorted(tags), key=operator.itemgetter(0)) A: >>> for i, j in itertools.groupby(tags, key=lambda x: x[0]): print(i, list(j)) a ['apples', 'apricots'] o ['oranges'] p ['pears', 'peaches'] A: just another way, >>> from collections import defaultdict >>> t=defaultdict(list) >>> for items in tags: ... t[items[0]].append(items) ... >>> t defaultdict(<type 'list'>, {'a': ['apples', 'apricots'], 'p': ['pears', 'peaches'], 'o': ['oranges']})
How can I use python itertools.groupby() to group a list of strings by their first character?
I have a list of strings similar to this list: tags = ('apples', 'apricots', 'oranges', 'pears', 'peaches') How should I go about grouping this list by the first character in each string using itertools.groupby()? How should I supply the 'key' argument required by itertools.groupby()?
[ "You might want to create dict afterwards:\nfrom itertools import groupby\n\nd = {k: list(v) for k, v in groupby(sorted(tags), key=lambda x: x[0])}\n\n", "groupby(sorted(tags), key=operator.itemgetter(0))\n\n", ">>> for i, j in itertools.groupby(tags, key=lambda x: x[0]):\n print(i, list(j))\n\n\na ['apples', 'apricots']\no ['oranges']\np ['pears', 'peaches']\n\n", "just another way, \n>>> from collections import defaultdict\n>>> t=defaultdict(list)\n>>> for items in tags:\n... t[items[0]].append(items)\n...\n>>> t\ndefaultdict(<type 'list'>, {'a': ['apples', 'apricots'], 'p': ['pears', 'peaches'], 'o': ['oranges']})\n\n" ]
[ 24, 16, 5, 1 ]
[]
[]
[ "python", "python_itertools", "string" ]
stackoverflow_0002472001_python_python_itertools_string.txt
Q: Producing a color map image using Python I have a working program in C++ that generates data for a Mandelbrot Set. I am able to get the color map image of the Mandelbrot set using gnuplot. In order to save the image, I just take a screenshot which doesn't give a very accurate image. how I can use a Python script in order to produce and save the image. A: The Python Imaging Library is the standard means to produce 2D images and image files in Python. A: Source code Draw a Mandelbrot Set (Python) PIL and NumPy ofcourse ;)
Producing a color map image using Python
I have a working program in C++ that generates data for a Mandelbrot Set. I am able to get the color map image of the Mandelbrot set using gnuplot. In order to save the image, I just take a screenshot which doesn't give a very accurate image. how I can use a Python script in order to produce and save the image.
[ "The Python Imaging Library is the standard means to produce 2D images and image files in Python.\n", "Source code Draw a Mandelbrot Set (Python)\nPIL and NumPy ofcourse ;)\n" ]
[ 0, 0 ]
[]
[]
[ "c", "image", "python" ]
stackoverflow_0002471899_c_image_python.txt
Q: Is there a functional way to do this? def flattenList(toFlatten): final=[] for el in toFlatten: if isinstance(el, list): final.extend(flattenList(el)) else: final.append(el) return final When I don't know how deeply the lists will nest, this is the only way I can think to do this. A: You should avoid typechecking in Python. In this case, this means avoiding arbitrarily-nested structures where you distinguish by type. You can build your own node type which you can traverse by methods other than typechecking, like looking at a specific attribute. For flattening one level or exactly n levels, look at itertools.chain.from_iterable. I don't know what you mean by "functional". This code is pretty functional: it uses recursion (not to its credit!) and it doesn't mutate its argument. (Strictly speaking, it does use mutable state for building a list, but that is just how you do it in Python. I suppose one more functional attribute would be lazy evaluation. You could implement this thusly def flatten(toFlatten): for item in toFlatten: if isinstance(item, list): # Ewww, typchecking for subitem in flatten(item): # they are considering adding yield subitem # "yield from" to the language # to give this pattern syntax else: yield item Recursion is very limited in Python (at least, in all its major implementations) and should generally be avoided for arbitrary depth. It is quite possible to rewrite this (and all recursive code) to use iteration, which will make this more scalable (and less functional, which is a good thing in Python, which is not especially suited for FP.) A: This answer explains why you do not want to use reduce for this in Python. Consider the snippet reduce(operator.add, [[1], [2], [3], [4], [5]]) What does this have to do? [1] + [2] => [1, 2] [1, 2] + [3] => This makes a new list, having to go over 1, then 2, then 3. [1, 2, 3] [1, 2, 3] + [4] => This has to copy the 1, 2, and 3 and then put 4 in the new list [1, 2, 3, 4] + [5] => The length of stuff I have to copy gets bigger each time! This quadratic behavior is completely avoidable: the original solution (and any number of other solutions) does not form these intermediate copying steps. A: Under the doc for itertools, there's a flatten() function A: Here's another option (though there may be something cleaner than type-checking, like testing if something is iterable and hence not an "atom"): def flatten(lst): if not isinstance(lst,list): return [lst] else: return reduce(lambda x,y:x+y,[flatten(x) for x in lst],[]) It's based on something scheme-like.
Is there a functional way to do this?
def flattenList(toFlatten): final=[] for el in toFlatten: if isinstance(el, list): final.extend(flattenList(el)) else: final.append(el) return final When I don't know how deeply the lists will nest, this is the only way I can think to do this.
[ "\nYou should avoid typechecking in Python. In this case, this means avoiding arbitrarily-nested structures where you distinguish by type. You can build your own node type which you can traverse by methods other than typechecking, like looking at a specific attribute.\nFor flattening one level or exactly n levels, look at itertools.chain.from_iterable.\nI don't know what you mean by \"functional\". This code is pretty functional: it uses recursion (not to its credit!) and it doesn't mutate its argument. (Strictly speaking, it does use mutable state for building a list, but that is just how you do it in Python.\nI suppose one more functional attribute would be lazy evaluation. You could implement this thusly\ndef flatten(toFlatten):\n for item in toFlatten:\n if isinstance(item, list): # Ewww, typchecking\n for subitem in flatten(item): # they are considering adding \n yield subitem # \"yield from\" to the language\n # to give this pattern syntax\n else:\n yield item\n\nRecursion is very limited in Python (at least, in all its major implementations) and should generally be avoided for arbitrary depth. It is quite possible to rewrite this (and all recursive code) to use iteration, which will make this more scalable (and less functional, which is a good thing in Python, which is not especially suited for FP.)\n\n", "This answer explains why you do not want to use reduce for this in Python. \nConsider the snippet \nreduce(operator.add, [[1], [2], [3], [4], [5]])\n\nWhat does this have to do?\n[1] + [2] => [1, 2]\n[1, 2] + [3] => This makes a new list, having to go over 1, then 2, then 3. [1, 2, 3]\n[1, 2, 3] + [4] => This has to copy the 1, 2, and 3 and then put 4 in the new list\n[1, 2, 3, 4] + [5] => The length of stuff I have to copy gets bigger each time!\n\nThis quadratic behavior is completely avoidable: the original solution (and any number of other solutions) does not form these intermediate copying steps.\n", "Under the doc for itertools, there's a flatten() function\n", "Here's another option (though there may be something cleaner than type-checking, like testing if something is iterable and hence not an \"atom\"):\ndef flatten(lst):\n if not isinstance(lst,list):\n return [lst]\n else:\n return reduce(lambda x,y:x+y,[flatten(x) for x in lst],[])\n\nIt's based on something scheme-like.\n" ]
[ 7, 3, 2, 1 ]
[]
[]
[ "python", "sequences" ]
stackoverflow_0002471413_python_sequences.txt
Q: how can i edit and run the python nltk program how can i edit and run the python nltk program A: nltk is not a program (in the sense of something that you are intended to execute) but a library. You need to import the particular modules that you need and then call their functions, or construct their objects, or whatever you want to do. This article has some examples. Notice the first two lines of the first example: >>> from nltk.tokenizer import * >>> t = Token(TEXT='This is my first test sentence') The first line indicates that he is importing all of the definitions in the module nltk.tokenizer - this includes the Token class. In the next line, he is able to instantiate a Token object (something he would not be able to do without the import statement). nltk is a very large library with many modules encompassing different types of natural language processing functionality. The first thing to do would be to figure out which specific functionality you would like to take advantage up, and then look it up in the documentation.
how can i edit and run the python nltk program
how can i edit and run the python nltk program
[ "nltk is not a program (in the sense of something that you are intended to execute) but a library. You need to import the particular modules that you need and then call their functions, or construct their objects, or whatever you want to do.\nThis article has some examples.\nNotice the first two lines of the first example:\n>>> from nltk.tokenizer import *\n>>> t = Token(TEXT='This is my first test sentence')\n\nThe first line indicates that he is importing all of the definitions in the module nltk.tokenizer - this includes the Token class. In the next line, he is able to instantiate a Token object (something he would not be able to do without the import statement).\nnltk is a very large library with many modules encompassing different types of natural language processing functionality. The first thing to do would be to figure out which specific functionality you would like to take advantage up, and then look it up in the documentation.\n" ]
[ 4 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0002472313_nltk_python.txt
Q: How to get "paster request" to use config host value instead of localhost? I'm trying to access my pylons application via cron job to send notifications to my users. The way I'm doing this is by running the application using something like: paster request myconfig.ini /maintenance/do In the actual controller I check for the "paste.command_request" to block public access. Everything works but the only problem is that within the notifications that I send to my users there is a link to their profile and the host is "localhost" which should instead be the domain name of the application. When the notifications are sent from within the served application (say, a user modifies their settings on the site) the notifications have the correct url. I am using mako to render my email tamplates and within the template I am using the "pylons.url" method with "qualified" set to "True". Am I missing something here? Thanks in advance. A: What I pretty much ended up doing was the following paster command: paster request myconfig.ini /maintenance/do --header=HOST:<USE_THIS_HOST> Where is the domain name I wanted my users to see in their email. You can even add in the IP address if you are testing the application locally. I'm not sure if this is the best way of doing this. If anyone else has any suggestions, they are greatly appreciated.
How to get "paster request" to use config host value instead of localhost?
I'm trying to access my pylons application via cron job to send notifications to my users. The way I'm doing this is by running the application using something like: paster request myconfig.ini /maintenance/do In the actual controller I check for the "paste.command_request" to block public access. Everything works but the only problem is that within the notifications that I send to my users there is a link to their profile and the host is "localhost" which should instead be the domain name of the application. When the notifications are sent from within the served application (say, a user modifies their settings on the site) the notifications have the correct url. I am using mako to render my email tamplates and within the template I am using the "pylons.url" method with "qualified" set to "True". Am I missing something here? Thanks in advance.
[ "What I pretty much ended up doing was the following paster command:\npaster request myconfig.ini /maintenance/do --header=HOST:<USE_THIS_HOST>\n\nWhere is the domain name I wanted my users to see in their email. You can even add in the IP address if you are testing the application locally.\nI'm not sure if this is the best way of doing this. If anyone else has any suggestions, they are greatly appreciated.\n" ]
[ 1 ]
[]
[]
[ "paster", "pylons", "python", "routes" ]
stackoverflow_0002467021_paster_pylons_python_routes.txt
Q: subprocess isn't outputting anything I'm trying to use Python to run pdftotext, but for some reason, my code isn't working. If I run the below, I expect that the content variable would contain the contents of the PDF, but the result I am getting is just an empty string. Does anybody know what I'm missing? def getPDFContent(path): path = "/path/to/a valid/pdffile.pdf" process = subprocess.Popen(["pdftotext", path], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) content, err = process.communicate()[0:2] return content, err A: By default pdftotext doesn't output anything on stdout, it instead creates a .txt file with the same base name as the pdf. To get the text on stdout, add - as a second parameter in the call to pdftotext: process = subprocess.Popen(["pdftotext", path, "-"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
subprocess isn't outputting anything
I'm trying to use Python to run pdftotext, but for some reason, my code isn't working. If I run the below, I expect that the content variable would contain the contents of the PDF, but the result I am getting is just an empty string. Does anybody know what I'm missing? def getPDFContent(path): path = "/path/to/a valid/pdffile.pdf" process = subprocess.Popen(["pdftotext", path], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) content, err = process.communicate()[0:2] return content, err
[ "By default pdftotext doesn't output anything on stdout, it instead creates a .txt file with the same base name as the pdf. To get the text on stdout, add - as a second parameter in the call to pdftotext:\nprocess = subprocess.Popen([\"pdftotext\", path, \"-\"], shell=False, \n stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n" ]
[ 2 ]
[]
[]
[ "pdftotext", "python", "subprocess" ]
stackoverflow_0002472488_pdftotext_python_subprocess.txt
Q: Simple debugger, want work? i'm reading the Gray Hat Python,, i reach for this :: class debugger(): def __init__(self): self.h_process = None self.pid = None self.debugger_active = False def load(self,path_to_exe): creation_flags = DEBUG_PROCESS startupinfo = STARTUPINFO() process_information = PROCESS_INFORMATION() startupinfo.dwFlags = 0x1 startupinfo.wShowWindows = 0x0 startupinfo.cb = sizeof(startupinfo) if kernel32.CreateProcessA(path_to_exe, None, None, None, None, creation_flags, None, None, byref(startupinfo), byref(process_information)): print "[*] We have successfully launched the process!" print "[*] PID: %d"%(process_information.dwProcessId) self.h_process = self.open_process(process_information.dwProcessId) else: print "[*] Error: 0x%08x."%(kernel32.GetLastError()) def open_process(self,pid): h_process = self.open_process(pid) if kernel32.DebugActiveProcess(pid): self.debugger_active = True self.pid = int(pid) self.run() else: print "[*] Unable to attach to the process." def run(self): while self.debugger_active == True: self.get_debug_event() def get_debug_event(self): debug_event = DEBUG_EVENT() continue_status = DBG_CONTINUE if kernel32.WaitForDebugEvent(byref(debug_event), INFINITE): raw_input("Press a Key to continue...") self.debugger_active = False kernel32.ContinueDebugEvent( \ debug_event.dwProcessId, \ debug_event.dwThreadId, \ continue_status ) def detach(self): if kernel32.DebugActiveProcessStop(self.pid): print "[*] Finished debugging. Exiting..." return True else: print "There was an error" return False when run my_test.py :: import my_dbg debugger = my_dbg.debugger() pid = raw_input('Enter the PID of the process to attach to: ') debugger.open_process(int(pid)) debugger.detach() i get this error :: Traceback (most recent call last): File "C:/Python26/dbgpy/my_test.py", line 5, in <module> debugger.attach(int(pid)) File "C:/Python26/dbgpy\my_dbg.py", line 37, in attach h_process = self.attach(pid) ........... ........... ........... File "C:/Python26/dbgpy\my_dbg.py", line 37, in attach h_process = self.attach(pid) File "C:/Python26/dbgpy\my_dbg.py", line 37, in attach h_process = self.attach(pid) RuntimeError: maximum recursion depth exceeded its because the loop and something else, but what it is ?? I'm running on Windows using Python2.6.4.. :) Update:: Found the problem thanks all,, this code work great :) from ctypes import * from my_dbg_def import * kernel32 = windll.kernel32 class debugger(): def __init__(self): self.h_process = None self.pid = None self.debugger_active = False def open_process(self,pid): h_process = kernel32.OpenProcess(PROCESS_ALL_ACCESS,pid,False) return h_process def attach(self,pid): self.h_process = self.open_process(pid) if kernel32.DebugActiveProcess(pid): self.debugger_active = True self.pid = int(pid) else: print "[*] Unable to attach to the process." def run(self): while self.debugger_active == True: self.get_debug_event() def get_debug_event(self): debug_event = DEBUG_EVENT() continue_status= DBG_CONTINUE if kernel32.WaitForDebugEvent(byref(debug_event),INFINITE): raw_input("Press a key to continue...") self.debugger_active = False kernel32.ContinueDebugEvent( \ debug_event.dwProcessId, \ debug_event.dwThreadId, \ continue_status ) def detach(self): if kernel32.DebugActiveProcessStop(self.pid): print "[*] Finished debugging. Exiting..." return True else: print "There was an error" return False A: I suppose at a certain point, you changed name from attach to open_process (as it seems from the output of the traceback). In this case, the error is here: def open_process(self,pid): h_process = self.open_process(pid) As you can see, it is recursively calling itself. It seems to me that you have it for some copy&paste, so maybe you can safely remove it.
Simple debugger, want work?
i'm reading the Gray Hat Python,, i reach for this :: class debugger(): def __init__(self): self.h_process = None self.pid = None self.debugger_active = False def load(self,path_to_exe): creation_flags = DEBUG_PROCESS startupinfo = STARTUPINFO() process_information = PROCESS_INFORMATION() startupinfo.dwFlags = 0x1 startupinfo.wShowWindows = 0x0 startupinfo.cb = sizeof(startupinfo) if kernel32.CreateProcessA(path_to_exe, None, None, None, None, creation_flags, None, None, byref(startupinfo), byref(process_information)): print "[*] We have successfully launched the process!" print "[*] PID: %d"%(process_information.dwProcessId) self.h_process = self.open_process(process_information.dwProcessId) else: print "[*] Error: 0x%08x."%(kernel32.GetLastError()) def open_process(self,pid): h_process = self.open_process(pid) if kernel32.DebugActiveProcess(pid): self.debugger_active = True self.pid = int(pid) self.run() else: print "[*] Unable to attach to the process." def run(self): while self.debugger_active == True: self.get_debug_event() def get_debug_event(self): debug_event = DEBUG_EVENT() continue_status = DBG_CONTINUE if kernel32.WaitForDebugEvent(byref(debug_event), INFINITE): raw_input("Press a Key to continue...") self.debugger_active = False kernel32.ContinueDebugEvent( \ debug_event.dwProcessId, \ debug_event.dwThreadId, \ continue_status ) def detach(self): if kernel32.DebugActiveProcessStop(self.pid): print "[*] Finished debugging. Exiting..." return True else: print "There was an error" return False when run my_test.py :: import my_dbg debugger = my_dbg.debugger() pid = raw_input('Enter the PID of the process to attach to: ') debugger.open_process(int(pid)) debugger.detach() i get this error :: Traceback (most recent call last): File "C:/Python26/dbgpy/my_test.py", line 5, in <module> debugger.attach(int(pid)) File "C:/Python26/dbgpy\my_dbg.py", line 37, in attach h_process = self.attach(pid) ........... ........... ........... File "C:/Python26/dbgpy\my_dbg.py", line 37, in attach h_process = self.attach(pid) File "C:/Python26/dbgpy\my_dbg.py", line 37, in attach h_process = self.attach(pid) RuntimeError: maximum recursion depth exceeded its because the loop and something else, but what it is ?? I'm running on Windows using Python2.6.4.. :) Update:: Found the problem thanks all,, this code work great :) from ctypes import * from my_dbg_def import * kernel32 = windll.kernel32 class debugger(): def __init__(self): self.h_process = None self.pid = None self.debugger_active = False def open_process(self,pid): h_process = kernel32.OpenProcess(PROCESS_ALL_ACCESS,pid,False) return h_process def attach(self,pid): self.h_process = self.open_process(pid) if kernel32.DebugActiveProcess(pid): self.debugger_active = True self.pid = int(pid) else: print "[*] Unable to attach to the process." def run(self): while self.debugger_active == True: self.get_debug_event() def get_debug_event(self): debug_event = DEBUG_EVENT() continue_status= DBG_CONTINUE if kernel32.WaitForDebugEvent(byref(debug_event),INFINITE): raw_input("Press a key to continue...") self.debugger_active = False kernel32.ContinueDebugEvent( \ debug_event.dwProcessId, \ debug_event.dwThreadId, \ continue_status ) def detach(self): if kernel32.DebugActiveProcessStop(self.pid): print "[*] Finished debugging. Exiting..." return True else: print "There was an error" return False
[ "I suppose at a certain point, you changed name from attach to open_process (as it seems from the output of the traceback).\nIn this case, the error is here:\ndef open_process(self,pid): \n h_process = self.open_process(pid) \n\nAs you can see, it is recursively calling itself.\nIt seems to me that you have it for some copy&paste, so maybe you can safely remove it.\n" ]
[ 1 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0002472409_debugging_python.txt
Q: Changing Element Value in Existing XML File Using DOM I am trying to find examples of how to change an existing xml files Element Value. Using the following xml example: <book> <title>My Book</title> <author>John Smith</author> </book> If I wanted to replace the author element value 'John Smith' with 'Jim Johnson' in a Python script using DOM, how would I go about doing so? I've tried to look for examples on this, but have failed in doing so. Any help would be greatly appreciated. Regards, Rylic A: Presuming s = ''' <book> <title>My Book</title> <author>John Smith</author> </book>''' DOM would look like: from xml.dom import minidom dom = minidom.parseString(s) # or parse(filename_or_file) for author in dom.getElementsByTagName('author'): author.childNodes = [dom.createTextNode("Jane Smith")] But I'd encourage you to look into ElementTree, it makes working with XML a breeze: from xml.etree import ElementTree et = ElementTree.fromstring(s) # or parse(filename_or_file) for author in et.findall('author'): author.text = "Jane Smith"
Changing Element Value in Existing XML File Using DOM
I am trying to find examples of how to change an existing xml files Element Value. Using the following xml example: <book> <title>My Book</title> <author>John Smith</author> </book> If I wanted to replace the author element value 'John Smith' with 'Jim Johnson' in a Python script using DOM, how would I go about doing so? I've tried to look for examples on this, but have failed in doing so. Any help would be greatly appreciated. Regards, Rylic
[ "Presuming\ns = '''\n<book>\n <title>My Book</title>\n <author>John Smith</author>\n</book>'''\n\nDOM would look like:\nfrom xml.dom import minidom\n\ndom = minidom.parseString(s) # or parse(filename_or_file)\nfor author in dom.getElementsByTagName('author'):\n author.childNodes = [dom.createTextNode(\"Jane Smith\")]\n\nBut I'd encourage you to look into ElementTree, it makes working with XML a breeze:\nfrom xml.etree import ElementTree\n\net = ElementTree.fromstring(s) # or parse(filename_or_file)\nfor author in et.findall('author'):\n author.text = \"Jane Smith\"\n\n" ]
[ 5 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002472279_python_xml.txt
Q: In Sphinx, can I register a bunch of keywords that should always be translated into links? My doc strings have references to other python classes that I've defined. Every time Sphinx encounters one of these classes, I want it to insert a link to the documentation for that other class. Is this possible in Sphinx? Specifically, I have a doc string like: '''This class contains a bunch of Foo objects''' I could write: '''This class contains a bunch of :class:`~foo.Foo` objects''' but I would prefer that Sphinx finds all text matching Foo and makes it seem as though I had typed :class:~foo.Foo A: You can use macros. In my project, I have a header file that contains all "important" classes and global functions and their abbreviation. Two example lines: .. |PostItem| replace:: :class:`PostItem <hklib.PostItem>` .. |PostNotFoundError| replace:: :class:`PostNotFoundError <hklib.PostNotFoundError>` In my rst files, I include this header file. Then I can use the macros in any rst file: .. include:: defs.hrst |PostItem| is a nice class. |PostNotFoundError|, on the other hand is not. (You can include docstrings from Python source files as well, using the autogen extension. Macros in those will be replaced as well.) About your example: I would add Foo to the header file and write the docstring this way: '''This class contains a bunch of |Foo| objects''' A: Sphinx has a huge number of interpreted text roles for this. https://www.sphinx-doc.org/en/2.0/usage/restructuredtext/domains.html#cross-referencing-python-objects I want to enter Foo and have Sphinx interpret it as though I had written :class:~foo.Foo That sounds impractical. It seems like it would paralyze RST trying parse your text. Looking for interpreted text and the few quoting rules that RST supports (*_|`) is about the limit that's practical. What you're asking for might lead to RST taking all day to check each instance Foo in every possible context and reason out whether you wanted a link or not. You'd want this only in otherwise-undecorated instances of Foo; trivial search and replace wouldn't work. You can mess with docstring pre-processing. https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#docstring-preprocessing This may allow you to try a global search-and-replace strategy on your docstring text.
In Sphinx, can I register a bunch of keywords that should always be translated into links?
My doc strings have references to other python classes that I've defined. Every time Sphinx encounters one of these classes, I want it to insert a link to the documentation for that other class. Is this possible in Sphinx? Specifically, I have a doc string like: '''This class contains a bunch of Foo objects''' I could write: '''This class contains a bunch of :class:`~foo.Foo` objects''' but I would prefer that Sphinx finds all text matching Foo and makes it seem as though I had typed :class:~foo.Foo
[ "You can use macros.\nIn my project, I have a header file that contains all \"important\" classes and global functions and their abbreviation. Two example lines:\n.. |PostItem| replace:: :class:`PostItem <hklib.PostItem>`\n.. |PostNotFoundError| replace:: :class:`PostNotFoundError <hklib.PostNotFoundError>`\n\nIn my rst files, I include this header file. Then I can use the macros in any rst file:\n.. include:: defs.hrst\n\n|PostItem| is a nice class. |PostNotFoundError|, on the other hand is not.\n\n(You can include docstrings from Python source files as well, using the autogen extension. Macros in those will be replaced as well.)\nAbout your example: I would add Foo to the header file and write the docstring this way:\n'''This class contains a bunch of |Foo| objects'''\n\n", "Sphinx has a huge number of interpreted text roles for this.\nhttps://www.sphinx-doc.org/en/2.0/usage/restructuredtext/domains.html#cross-referencing-python-objects\n\nI want to enter Foo and have Sphinx interpret it as though I had written :class:~foo.Foo\n\nThat sounds impractical. It seems like it would paralyze RST trying parse your text. Looking for interpreted text and the few quoting rules that RST supports (*_|`) is about the limit that's practical.\nWhat you're asking for might lead to RST taking all day to check each instance Foo in every possible context and reason out whether you wanted a link or not. You'd want this only in otherwise-undecorated instances of Foo; trivial search and replace wouldn't work. \nYou can mess with docstring pre-processing.\nhttps://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#docstring-preprocessing\nThis may allow you to try a global search-and-replace strategy on your docstring text.\n" ]
[ 8, 2 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0002472364_python_python_sphinx.txt
Q: "Bootstrap" python script in the Windows shell without .py / .pyw associations Sometimes (in customer's PCs) I need a python script to execute in the Windows shell like a .CMD or .BAT, but without having the .py or .pyw extensions associated with PYTHON / PYTHONW. I came out with a pair of 'quick'n dirty' solutions: 1) """ e:\devtool\python\python.exe %0 :: or %PYTHONPATH%\python.exe goto eof: """ # Python test print "[works, but shows shell errors]" 2) @echo off for /f "skip=4 delims=xxx" %%l in (%0) do @echo %%l | e:\devtools\python\python.exe goto :eof ::---------- # Python test print "[works better, but is somewhat messy]" Do you know a better solution? (ie: more concise or elegant) Update: based on @van answer, the more concise way I found (without setting ERRORLEVEL) @e:\devtools\python\python.exe -x "%~f0" %* & exit /b ### Python begins.... import sys for arg in sys.argv: print arg raw_input("It works!!!\n") ### A: You can try to create a script what is both python and windows shell script. In this case you can name you file my_flexible_script.bat and execute it either directly or via python .... See a content of pylint.bat file from pylint: @echo off rem = """-*-Python-*- script rem -------------------- DOS section -------------------- rem You could set PYTHONPATH or TK environment variables here python -x "%~f0" %* goto exit """ # -------------------- Python section -------------------- import sys from pylint import lint lint.Run(sys.argv[1:]) DosExitLabel = """ :exit exit(ERRORLEVEL) rem """ It is similar to what you do, but has more compliant dual-script support. A: I use the following distutils/py2exe script to produce a single runnable executable file: from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1}}, console = [{'script': "MyScript.py"}], zipfile = None, ) I see that MSVCR71.DLL gets copied into the dist directory as a result... but the chances are high that this dependancy is already on the target machine.
"Bootstrap" python script in the Windows shell without .py / .pyw associations
Sometimes (in customer's PCs) I need a python script to execute in the Windows shell like a .CMD or .BAT, but without having the .py or .pyw extensions associated with PYTHON / PYTHONW. I came out with a pair of 'quick'n dirty' solutions: 1) """ e:\devtool\python\python.exe %0 :: or %PYTHONPATH%\python.exe goto eof: """ # Python test print "[works, but shows shell errors]" 2) @echo off for /f "skip=4 delims=xxx" %%l in (%0) do @echo %%l | e:\devtools\python\python.exe goto :eof ::---------- # Python test print "[works better, but is somewhat messy]" Do you know a better solution? (ie: more concise or elegant) Update: based on @van answer, the more concise way I found (without setting ERRORLEVEL) @e:\devtools\python\python.exe -x "%~f0" %* & exit /b ### Python begins.... import sys for arg in sys.argv: print arg raw_input("It works!!!\n") ###
[ "You can try to create a script what is both python and windows shell script. In this case you can name you file my_flexible_script.bat and execute it either directly or via python ....\nSee a content of pylint.bat file from pylint:\n@echo off\nrem = \"\"\"-*-Python-*- script\nrem -------------------- DOS section --------------------\nrem You could set PYTHONPATH or TK environment variables here\npython -x \"%~f0\" %*\ngoto exit\n\n\"\"\"\n# -------------------- Python section --------------------\nimport sys\nfrom pylint import lint\nlint.Run(sys.argv[1:])\n\n\nDosExitLabel = \"\"\"\n:exit\nexit(ERRORLEVEL)\nrem \"\"\"\n\nIt is similar to what you do, but has more compliant dual-script support.\n", "I use the following distutils/py2exe script to produce a single runnable executable file:\nfrom distutils.core import setup\nimport py2exe, sys, os\n\nsys.argv.append('py2exe')\n\nsetup(\n options = {'py2exe': {'bundle_files': 1}},\n console = [{'script': \"MyScript.py\"}],\n zipfile = None,\n)\n\nI see that MSVCR71.DLL gets copied into the dist directory as a result... but the chances are high that this dependancy is already on the target machine.\n" ]
[ 10, 0 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0002472558_python_shell.txt
Q: paster errors after installing distribute 0.6.10 Been working on a Plone site for the last few weeks, it's the first time I've worked on one using buildout for recipes and paster for template generation, and it's been a learning curve. two days ago, everything was working fine. Yesterday, I started working from my known good source and used paster to generate boilerplate for a new archetype, worked fine. I edited the buildout (as I've done several times before) to account for the new item, ran buildout, and got a hung build (kept repeating that it was generating distribute) Googling indicated that this was due to a version mismatch, and that I should upgrade to the latest version of distribute, so I did so (to 0.6.10) Now, that error is gone, but so is any ability to do paster. Even running paster create --list-templates kicks out the error: F:\Plone\src>paster create --list-templates Traceback (most recent call last): File "F:\Plone\Python\Scripts\paster-script.py", line 5, in ? from pkg_resources import load_entry_point ImportError: No module named pkg_resources Hope someone can help, b/c I'm pretty stalled right now. A: Turns out, the problem had to do with the new version of distribute apparently doesn't squash the old version correctly. I had to manually rename the old egg, delete teh new one, then re-install the new one. A: You're spot on to delete the distribute egg and reinstall. If your easy_install produces a similar issue (mine did after deleting my setuptools egg) you can manually reinstall distribute with: $ curl -O http://python-distribute.org/distribute_setup.py $ python distribute_setup.py A: Maybe this helps? New distribute release: use new zc.buildout to prevent recursion I don't know that much about that particular part of the stack, but might be related?
paster errors after installing distribute 0.6.10
Been working on a Plone site for the last few weeks, it's the first time I've worked on one using buildout for recipes and paster for template generation, and it's been a learning curve. two days ago, everything was working fine. Yesterday, I started working from my known good source and used paster to generate boilerplate for a new archetype, worked fine. I edited the buildout (as I've done several times before) to account for the new item, ran buildout, and got a hung build (kept repeating that it was generating distribute) Googling indicated that this was due to a version mismatch, and that I should upgrade to the latest version of distribute, so I did so (to 0.6.10) Now, that error is gone, but so is any ability to do paster. Even running paster create --list-templates kicks out the error: F:\Plone\src>paster create --list-templates Traceback (most recent call last): File "F:\Plone\Python\Scripts\paster-script.py", line 5, in ? from pkg_resources import load_entry_point ImportError: No module named pkg_resources Hope someone can help, b/c I'm pretty stalled right now.
[ "Turns out, the problem had to do with the new version of distribute apparently doesn't squash the old version correctly. I had to manually rename the old egg, delete teh new one, then re-install the new one.\n", "You're spot on to delete the distribute egg and reinstall.\nIf your easy_install produces a similar issue (mine did after deleting my setuptools egg) you can manually reinstall distribute with:\n$ curl -O http://python-distribute.org/distribute_setup.py\n$ python distribute_setup.py\n\n", "Maybe this helps?\nNew distribute release: use new zc.buildout to prevent recursion\nI don't know that much about that particular part of the stack, but might be related?\n" ]
[ 3, 1, 0 ]
[]
[]
[ "distribute", "paster", "plone", "python" ]
stackoverflow_0001898055_distribute_paster_plone_python.txt
Q: python gui events out of order from Tkinter import * from tkMessageBox import * class Gui: def __init__(self, root): self.container = Frame(root) self.container.grid() self.inputText = Text(self.container, width=50, height=8) self.outputText = Text(self.container, width=50, height=8, bg='#E0E0E0', state=DISABLED) self.inputText.grid(row=0, column=0) self.outputText.grid(row=0, column=1) self.inputText.bind("<Key>", self.translate) def translate(self, event): input = self.inputText.get(0.0, END) output = self.outputText.get(0.0, END) self.outputText.config(state=NORMAL) self.outputText.delete(0.0, END) self.outputText.insert(INSERT, input) self.outputText.config(state=DISABLED) showinfo(message="Input: %s characters\nOutput: %s characters" % (len(input), len(input))) root = Tk() #toplevel object app = Gui(root) #call to the class where gui is defined root.mainloop() #enter event loop Working on a gui in tkinter I'm a little confused as to the sequence the event handlers are run. If you run the above code you'll hopefully see... 1) Editing the text widget triggers the event handler but it seems to fire it off without registering the actual change, 2) Even when the text widget is cleared (ie, keep pressing BackSpace) it still seems to have a one character length string, 3) The output widget only receives its update when the NEXT event trigger is fired despite the fact the data came on the previous event. Is this just how bindings work in tkinter or am i missing something here? The behaviour i would like when updating the input widget is: 1) Show the change, 2) Enter event handler, 3) Update output widget, 4) Show message box. A: This is how bindings work (and that's a good thing), but your problem is easily solved. Bindings are fired in the order specified by a widgets binding tags (also known as bind tags or bindtags). Unless you specify otherwise, the bindings happen in the following order: if there is a binding directly on the widget it will be fired before any other bindings. if there is a binding on the widget's class, it is fired next if there is a binding on the toplevel widget that contains the widget, it is fired next (note: the root window is considered a toplevel window in this context) if there is a binding on "all" it will fire next. The sequence can be stopped at any point by one of the event handlers, but that's beside the point for this specific discussion. In the default case, your binding on <Key> happens before the class binding, and it is the class binding where the text is actually inserted into the widget. That is why your binding always seems to be one character behind. Normally this order of things is exactly right, since more specific bindings get a chance to override the default behavior. If it wasn't this way you'd always get the default behavior even if you didn't want it. One place where this is not always what you want is when you want to augment the default bindings rather than replace them. You can swap the order of the bindtags so that the class binding happens first. Or, add an additional bindtag to your text widget and add that in the sequence after the class binding, and bind to that. Usually adding a bindtag is the better solution, but not always. To change the bindtags you can do something like this: self.inputText.bindtags(((str(self.inputText)), "Text", "post-insert", ".", "all")) To bind to "post-insert", do it with the bind_class method: self.inputText.bind_class("post-insert", "<Key>", self.translate) It may seem odd, but bindtags are one of the most powerful binding mechanisms out there. They give you complete and total control over the order of bindings, which is much more difficult with any other toolkit. By the way, don't forget that if you get all the characters to the end of the text widget there will always be an extra newline at the end. Either get to end-1c, or trim off one newline from the text.
python gui events out of order
from Tkinter import * from tkMessageBox import * class Gui: def __init__(self, root): self.container = Frame(root) self.container.grid() self.inputText = Text(self.container, width=50, height=8) self.outputText = Text(self.container, width=50, height=8, bg='#E0E0E0', state=DISABLED) self.inputText.grid(row=0, column=0) self.outputText.grid(row=0, column=1) self.inputText.bind("<Key>", self.translate) def translate(self, event): input = self.inputText.get(0.0, END) output = self.outputText.get(0.0, END) self.outputText.config(state=NORMAL) self.outputText.delete(0.0, END) self.outputText.insert(INSERT, input) self.outputText.config(state=DISABLED) showinfo(message="Input: %s characters\nOutput: %s characters" % (len(input), len(input))) root = Tk() #toplevel object app = Gui(root) #call to the class where gui is defined root.mainloop() #enter event loop Working on a gui in tkinter I'm a little confused as to the sequence the event handlers are run. If you run the above code you'll hopefully see... 1) Editing the text widget triggers the event handler but it seems to fire it off without registering the actual change, 2) Even when the text widget is cleared (ie, keep pressing BackSpace) it still seems to have a one character length string, 3) The output widget only receives its update when the NEXT event trigger is fired despite the fact the data came on the previous event. Is this just how bindings work in tkinter or am i missing something here? The behaviour i would like when updating the input widget is: 1) Show the change, 2) Enter event handler, 3) Update output widget, 4) Show message box.
[ "This is how bindings work (and that's a good thing), but your problem is easily solved. \nBindings are fired in the order specified by a widgets binding tags (also known as bind tags or bindtags). Unless you specify otherwise, the bindings happen in the following order:\n\nif there is a binding directly on the widget it will be fired before any other bindings.\nif there is a binding on the widget's class, it is fired next\nif there is a binding on the toplevel widget that contains the widget, it is fired next (note: the root window is considered a toplevel window in this context)\nif there is a binding on \"all\" it will fire next.\n\nThe sequence can be stopped at any point by one of the event handlers, but that's beside the point for this specific discussion.\nIn the default case, your binding on <Key> happens before the class binding, and it is the class binding where the text is actually inserted into the widget. That is why your binding always seems to be one character behind.\nNormally this order of things is exactly right, since more specific bindings get a chance to override the default behavior. If it wasn't this way you'd always get the default behavior even if you didn't want it. One place where this is not always what you want is when you want to augment the default bindings rather than replace them. \nYou can swap the order of the bindtags so that the class binding happens first. Or, add an additional bindtag to your text widget and add that in the sequence after the class binding, and bind to that. Usually adding a bindtag is the better solution, but not always. \nTo change the bindtags you can do something like this:\nself.inputText.bindtags(((str(self.inputText)), \"Text\", \"post-insert\", \".\", \"all\"))\n\nTo bind to \"post-insert\", do it with the bind_class method:\nself.inputText.bind_class(\"post-insert\", \"<Key>\", self.translate)\n\nIt may seem odd, but bindtags are one of the most powerful binding mechanisms out there. They give you complete and total control over the order of bindings, which is much more difficult with any other toolkit.\nBy the way, don't forget that if you get all the characters to the end of the text widget there will always be an extra newline at the end. Either get to end-1c, or trim off one newline from the text.\n" ]
[ 4 ]
[]
[]
[ "events", "python", "tkinter", "user_interface" ]
stackoverflow_0002458026_events_python_tkinter_user_interface.txt
Q: Can generateDS be used like xsd.exe Can I use generateDS.py in python in a similar way that I would use xsd.exe to create C# classes from xsd? Basically, given an xsd schema I want to create a data structure, in python, fill its data in, and then render it into an xml string. perhaps pyXSD is better? oh, and yes, I'm a python newbie A: generateDS did exactly what I wanted it to, a way to deal with a object graph of data, rather than a node graph ran python generateDS.py -o MedicationDS.py medication.xsd gave me a python Class I could instantiate and populate with data, then render to a stream. medObj = MedicationDS.Medication.factory() medObj.set_dateStarted('2010-01-01') medObj.set_dateStopped('2010-02-02') medObj.set_reasonStopped('hurt my brain') brandNameObj = MedicationDS.CodedValue.factory() brandNameObj.set_abbrev('aspirin') brandNameObj.set_value('aspirin') medObj.set_brandName(brandNameObj) xmlStr=StringIO() medObj.export(xmlStr, 0)
Can generateDS be used like xsd.exe
Can I use generateDS.py in python in a similar way that I would use xsd.exe to create C# classes from xsd? Basically, given an xsd schema I want to create a data structure, in python, fill its data in, and then render it into an xml string. perhaps pyXSD is better? oh, and yes, I'm a python newbie
[ "generateDS did exactly what I wanted it to, a way to deal with a object graph of data, rather than a node graph\nran\npython generateDS.py -o MedicationDS.py medication.xsd\n\ngave me a python Class I could instantiate and populate with data, then render to a stream.\nmedObj = MedicationDS.Medication.factory()\nmedObj.set_dateStarted('2010-01-01')\nmedObj.set_dateStopped('2010-02-02')\nmedObj.set_reasonStopped('hurt my brain')\nbrandNameObj = MedicationDS.CodedValue.factory()\nbrandNameObj.set_abbrev('aspirin')\nbrandNameObj.set_value('aspirin')\nmedObj.set_brandName(brandNameObj)\n\nxmlStr=StringIO()\nmedObj.export(xmlStr, 0)\n\n" ]
[ 2 ]
[]
[]
[ "python", "xsd" ]
stackoverflow_0002368857_python_xsd.txt
Q: Cannot turn off autocommit in a script using the Django ORM I have a command line script that uses the Django ORM and MySQL backend. I want to turn off autocommit and commit manually. For the life of me, I cannot get this to work. Here is a pared down version of the script. A row is inserted into testtable every time I run this and I get this warning from MySQL: "Some non-transactional changed tables couldn't be rolled back". #!/usr/bin/python import os import sys django_dir = os.path.abspath(os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))) sys.path.append(django_dir) os.environ['DJANGO_DIR'] = django_dir os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' from django.core.management import setup_environ from myproject import settings setup_environ(settings) from django.db import transaction, connection cursor = connection.cursor() cursor.execute('SET autocommit = 0') cursor.execute('insert into testtable values (\'X\')') cursor.execute('rollback') I also tried placing the insert in a function and adding Django's commit_manually wrapper, like so: @transaction.commit_manually def myfunction(): cursor = connection.cursor() cursor.execute('SET autocommit = 0') cursor.execute('insert into westest values (\'X\')') cursor.execute('rollback') myfunction() I also tried setting DISABLE_TRANSACTION_MANAGEMENT = True in settings.py, with no further luck. I feel like I am missing something obvious. Any help you can give me is greatly appreciated. Thanks! A: Are your tables MyISAM or InnoDB? Remember that MyISAM isn't transactional, so can't be rolled back. See for example this page in the MySQL documentation: In transactional terms, MyISAM tables effectively always operate in autocommit = 1 mode.
Cannot turn off autocommit in a script using the Django ORM
I have a command line script that uses the Django ORM and MySQL backend. I want to turn off autocommit and commit manually. For the life of me, I cannot get this to work. Here is a pared down version of the script. A row is inserted into testtable every time I run this and I get this warning from MySQL: "Some non-transactional changed tables couldn't be rolled back". #!/usr/bin/python import os import sys django_dir = os.path.abspath(os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))) sys.path.append(django_dir) os.environ['DJANGO_DIR'] = django_dir os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings' from django.core.management import setup_environ from myproject import settings setup_environ(settings) from django.db import transaction, connection cursor = connection.cursor() cursor.execute('SET autocommit = 0') cursor.execute('insert into testtable values (\'X\')') cursor.execute('rollback') I also tried placing the insert in a function and adding Django's commit_manually wrapper, like so: @transaction.commit_manually def myfunction(): cursor = connection.cursor() cursor.execute('SET autocommit = 0') cursor.execute('insert into westest values (\'X\')') cursor.execute('rollback') myfunction() I also tried setting DISABLE_TRANSACTION_MANAGEMENT = True in settings.py, with no further luck. I feel like I am missing something obvious. Any help you can give me is greatly appreciated. Thanks!
[ "Are your tables MyISAM or InnoDB? Remember that MyISAM isn't transactional, so can't be rolled back. See for example this page in the MySQL documentation:\n\nIn transactional terms, MyISAM tables effectively always operate in autocommit = 1 mode.\n\n" ]
[ 2 ]
[]
[]
[ "command_line", "django", "mysql", "python" ]
stackoverflow_0002473090_command_line_django_mysql_python.txt
Q: Python: write to file multiple times without open/close for each write How can i open file in python and write to it multiple times? I am using speech recognition, and i want one file to change its contents based on what i say. Other application needs to be able to read this file. Is there way to do this, or i need to open/close for each write? A: You can just keep the file object around and write to it whenever you want. You might need to flush it after each write to make things visible to the outside world. If you do the writes from a different process, just open the file in append mode ("a"). A: f = open('myfile.txt','w') f.write('Hi') f.write('Hi again!') f.write('Is this thing on?') # do this as long as you need to f.seek(0,0) # return to the beginning of the file if you need to f.close() # close the file handle
Python: write to file multiple times without open/close for each write
How can i open file in python and write to it multiple times? I am using speech recognition, and i want one file to change its contents based on what i say. Other application needs to be able to read this file. Is there way to do this, or i need to open/close for each write?
[ "You can just keep the file object around and write to it whenever you want. You might need to flush it after each write to make things visible to the outside world.\nIf you do the writes from a different process, just open the file in append mode (\"a\").\n", "f = open('myfile.txt','w')\nf.write('Hi')\nf.write('Hi again!')\nf.write('Is this thing on?')\n# do this as long as you need to\nf.seek(0,0) # return to the beginning of the file if you need to\nf.close() # close the file handle\n\n" ]
[ 11, 7 ]
[]
[]
[ "file", "python" ]
stackoverflow_0002473202_file_python.txt
Q: How do I create self-relationships in polymorphic inheritance in Elixir and Pylons? I am new to programming and am following the example in the Pylons documentation on creating a Wiki. The database I want to link to the wiki was created with Elixir so I rewrote the Wiki database schema and have continued from there. In the wiki there is a requirement for a Navigation table which is inherited by Pages and Sections. A section can have many pages, while a page can only have one section. In addition, each sibling node can be chain-referenced to each other. So: Nav has "section" (OneToMany) and "before" (OneToOne - to reference preceeding node) Page has "section" (ManyToOne - many pages in one section) and inherits "before" Section inherits all from Nav The code I've written looks like this: class Nav(Entity): using_options(inheritance='multi') name = Field(Unicode(30), default=u'Untitled Node') path = Field(Unicode(255), default=u'') section = OneToMany('Page', inverse='section') after = OneToOne('Nav', inverse='before') before = OneToMany('Nav', inverse='after') class Page(Nav): using_options(inheritance='multi') content = Field(UnicodeText, nullable=False) posted = Field(DateTime, default=now()) title = Field(Unicode(255), default=u'Untitled Page') heading = Field(Unicode(255)) tags = ManyToMany('Tag') comments = OneToMany('Comment') section = ManyToOne('Nav', inverse='section') class Section(Nav): using_options(inheritance='multi') Errors received on this: sqlalchemy.exc.OperationalError: (OperationalError) table nav has no column named aftr_id u'INSERT INTO nav (name, path, aftr_id, row_type) VALUES (?, ?, ?, ?)' I've also tried: before = ManyToMany('Nav', inverse='before') on Nav in the hopes this might break the problem, but also not. The original SQLAlchemy code from the tutorial for these declarations is as follows: nav_table = schema.Table('nav', meta.metadata, schema.Column('id', types.Integer(), schema.Sequence('nav_id_seq', optional=True), primary_key=True), schema.Column('name', types.Unicode(255), default=u'Untitled Node'), schema.Column('path', types.Unicode(255), default=u''), schema.Column('section', types.Integer(), schema.ForeignKey('nav.id')), schema.Column('before', types.Integer(), default=None), schema.Column('type', types.String(30), nullable=False) ) page_table = schema.Table('page', meta.metadata, schema.Column('id', types.Integer, schema.ForeignKey('nav.id'), primary_key=True), schema.Column('content', types.Text(), nullable=False), schema.Column('posted', types.DateTime(), default=now), schema.Column('title', types.Unicode(255), default=u'Untitled Page'), schema.Column('heading', types.Unicode(255)), ) section_table = sa.Table('section', meta.metadata, schema.Column('id', types.Integer, schema.ForeignKey('nav.id'), primary_key=True), ) orm.mapper(Nav, nav_table, polymorphic_on=nav_table.c.type, polymorphic_identity='nav') orm.mapper(Section, section_table, inherits=Nav, polymorphic_identity='section') orm.mapper(Page, page_table, inherits=Nav, polymorphic_identity='page', properties={ 'comments':orm.relation(Comment, backref='page', cascade='all'), 'tags':orm.relation(Tag, secondary=pagetag_table) }) Any help is much appreciated. A: I think that your model is mostly correct. The only thing I found is the link section from Nav->Page and back: class Nav(Entity): section = OneToMany('Page', inverse='section') class Page(Nav): section = ManyToOne('Nav', inverse='section') The tutorial just that the Section (not Page) is the parent (class Nav), so you should instead have: class Nav(Entity): section = ManyToOne('Section') # and optionally inverse class Section(Nav): children = ManyToOne('Nav') Basically, to make a model clear, see Section as a Directory, where Page is like a File. Both of them have a (parent) section and, assuming that they are sorted in some way, also have the before reference. The part with before and after looks correct to me. So the only thing remaining is that you database schema does not reflect the object model. Can you re-create the db model? Or at least post resulting db scripts as well?
How do I create self-relationships in polymorphic inheritance in Elixir and Pylons?
I am new to programming and am following the example in the Pylons documentation on creating a Wiki. The database I want to link to the wiki was created with Elixir so I rewrote the Wiki database schema and have continued from there. In the wiki there is a requirement for a Navigation table which is inherited by Pages and Sections. A section can have many pages, while a page can only have one section. In addition, each sibling node can be chain-referenced to each other. So: Nav has "section" (OneToMany) and "before" (OneToOne - to reference preceeding node) Page has "section" (ManyToOne - many pages in one section) and inherits "before" Section inherits all from Nav The code I've written looks like this: class Nav(Entity): using_options(inheritance='multi') name = Field(Unicode(30), default=u'Untitled Node') path = Field(Unicode(255), default=u'') section = OneToMany('Page', inverse='section') after = OneToOne('Nav', inverse='before') before = OneToMany('Nav', inverse='after') class Page(Nav): using_options(inheritance='multi') content = Field(UnicodeText, nullable=False) posted = Field(DateTime, default=now()) title = Field(Unicode(255), default=u'Untitled Page') heading = Field(Unicode(255)) tags = ManyToMany('Tag') comments = OneToMany('Comment') section = ManyToOne('Nav', inverse='section') class Section(Nav): using_options(inheritance='multi') Errors received on this: sqlalchemy.exc.OperationalError: (OperationalError) table nav has no column named aftr_id u'INSERT INTO nav (name, path, aftr_id, row_type) VALUES (?, ?, ?, ?)' I've also tried: before = ManyToMany('Nav', inverse='before') on Nav in the hopes this might break the problem, but also not. The original SQLAlchemy code from the tutorial for these declarations is as follows: nav_table = schema.Table('nav', meta.metadata, schema.Column('id', types.Integer(), schema.Sequence('nav_id_seq', optional=True), primary_key=True), schema.Column('name', types.Unicode(255), default=u'Untitled Node'), schema.Column('path', types.Unicode(255), default=u''), schema.Column('section', types.Integer(), schema.ForeignKey('nav.id')), schema.Column('before', types.Integer(), default=None), schema.Column('type', types.String(30), nullable=False) ) page_table = schema.Table('page', meta.metadata, schema.Column('id', types.Integer, schema.ForeignKey('nav.id'), primary_key=True), schema.Column('content', types.Text(), nullable=False), schema.Column('posted', types.DateTime(), default=now), schema.Column('title', types.Unicode(255), default=u'Untitled Page'), schema.Column('heading', types.Unicode(255)), ) section_table = sa.Table('section', meta.metadata, schema.Column('id', types.Integer, schema.ForeignKey('nav.id'), primary_key=True), ) orm.mapper(Nav, nav_table, polymorphic_on=nav_table.c.type, polymorphic_identity='nav') orm.mapper(Section, section_table, inherits=Nav, polymorphic_identity='section') orm.mapper(Page, page_table, inherits=Nav, polymorphic_identity='page', properties={ 'comments':orm.relation(Comment, backref='page', cascade='all'), 'tags':orm.relation(Tag, secondary=pagetag_table) }) Any help is much appreciated.
[ "I think that your model is mostly correct. The only thing I found is the link section from Nav->Page and back:\nclass Nav(Entity):\n section = OneToMany('Page', inverse='section')\nclass Page(Nav):\n section = ManyToOne('Nav', inverse='section')\n\nThe tutorial just that the Section (not Page) is the parent (class Nav), so you should instead have:\nclass Nav(Entity):\n section = ManyToOne('Section')\n# and optionally inverse\nclass Section(Nav):\n children = ManyToOne('Nav')\n\nBasically, to make a model clear, see Section as a Directory, where Page is like a File. Both of them have a (parent) section and, assuming that they are sorted in some way, also have the before reference.\nThe part with before and after looks correct to me. So the only thing remaining is that you database schema does not reflect the object model. Can you re-create the db model? Or at least post resulting db scripts as well?\n" ]
[ 0 ]
[]
[]
[ "pylons", "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0002462049_pylons_python_python_elixir_sqlalchemy.txt
Q: Get the Model context of a Key object in Datastore (App Engine) I'd like to bypass some frequent queries by storing str(key) in memcache. When I get the encoded_key back from memcached, I can reconstruct the key with Key(encoded=encoded_key). But how can I query the actual object from the key? A possibility would be to use GqlQuery('SELECT * FROM ' + Key(encoded_key).kind() + \ ' WHERE __key__ = ' + encoded_key) but I'd rather not use GQL if possible. Is there a way of getting the object without using GQL? A: Are you just storing the result of str(key) in memcached? If so, when you get it back, you should be able to just do db.get(key) to get the entity to which it points. db.get() will take either a db.Key object or the string representation of a db.Key object (or a list of keys or key strings).
Get the Model context of a Key object in Datastore (App Engine)
I'd like to bypass some frequent queries by storing str(key) in memcache. When I get the encoded_key back from memcached, I can reconstruct the key with Key(encoded=encoded_key). But how can I query the actual object from the key? A possibility would be to use GqlQuery('SELECT * FROM ' + Key(encoded_key).kind() + \ ' WHERE __key__ = ' + encoded_key) but I'd rather not use GQL if possible. Is there a way of getting the object without using GQL?
[ "Are you just storing the result of str(key) in memcached? If so, when you get it back, you should be able to just do db.get(key) to get the entity to which it points.\ndb.get() will take either a db.Key object or the string representation of a db.Key object (or a list of keys or key strings).\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002473632_google_app_engine_google_cloud_datastore_python.txt
Q: cpython: when PyDict_GetItem is called and when dict_subscript? I am reading cpython code for python 3k and I have noticed, that __missing__ is called only when dict_subscript is called, but not when PyDict_GetItem is used. What is the difference between those two methods and when each is called? If I pass an PyObject that is a subclass of dict and has __missing__ method, how can I force using it, since PyDict_GetItem doesn't do that. A: Observations, guesses, etc: Same happens in Python 2.x. dict_subscript implements the equivalent of the high_level dict.__getitem__ method and thus will be called whenever adict[somekey] appears other than on the LHS of an assignment in Python code. PyDict_GetItem is part of the C API. Perhaps it's an oversight that it hasn't been updated. Having read the dire comments at the start of PyDict_GetItem, I'd be using PyDict_GetItemWithError instead ;-) Perhaps you can do the C-level equivalent of my_getitem = getattr(my_dict, '__getitem__') once then call that. Perhaps you could raise a bug ticket or ask on comp.lang.python
cpython: when PyDict_GetItem is called and when dict_subscript?
I am reading cpython code for python 3k and I have noticed, that __missing__ is called only when dict_subscript is called, but not when PyDict_GetItem is used. What is the difference between those two methods and when each is called? If I pass an PyObject that is a subclass of dict and has __missing__ method, how can I force using it, since PyDict_GetItem doesn't do that.
[ "Observations, guesses, etc:\nSame happens in Python 2.x.\ndict_subscript implements the equivalent of the high_level dict.__getitem__ method and thus will be called whenever adict[somekey] appears other than on the LHS of an assignment in Python code.\nPyDict_GetItem is part of the C API. Perhaps it's an oversight that it hasn't been updated.\nHaving read the dire comments at the start of PyDict_GetItem, I'd be using PyDict_GetItemWithError instead ;-)\nPerhaps you can do the C-level equivalent of my_getitem = getattr(my_dict, '__getitem__') once then call that.\nPerhaps you could raise a bug ticket or ask on comp.lang.python\n" ]
[ 1 ]
[]
[]
[ "cpython", "dictionary", "python" ]
stackoverflow_0002470928_cpython_dictionary_python.txt
Q: Python script web service timeout We have had a Python script running for many months now that simply scans through a directory of files, and posts each file to our web site via a web service call. The web site is also written in Python. For no apparent reason, this morning this script started throwing the following error: urllib2.URLError: <urlopen error (10060, 'Operation timed out')> The site itself is up and running just fine. There are no indications of any errors. The developer that was working on this site is no longer with us, and we do not have a strong Python developer on staff as we are moving away from that. Before I do an all nighter and rewrite this thing in C#, I wanted to see if anyone had any experience dealing with this issue. I do know that the script is connecting to a secure site (HTTPS), so I am not sure if something has come up with that, and I honestly dont know where to look to determine that. As I said before, the site itself isn't showing any signs of error, including SSL. Any thoughts? A: I think if it was working up until this point the suspect is not the code but the site. However, you may want to dig around in the code and write some debugging. The urllib2 module method urlopen throws the object URLError as you can see and has an attribute 'reason'. Beyond that I am not sure what you might do to debug the issue. Check the credentials or the certs? Its very possible the cert has expired or something has happened with that. More likely than the code being the issue given its been working all this time.
Python script web service timeout
We have had a Python script running for many months now that simply scans through a directory of files, and posts each file to our web site via a web service call. The web site is also written in Python. For no apparent reason, this morning this script started throwing the following error: urllib2.URLError: <urlopen error (10060, 'Operation timed out')> The site itself is up and running just fine. There are no indications of any errors. The developer that was working on this site is no longer with us, and we do not have a strong Python developer on staff as we are moving away from that. Before I do an all nighter and rewrite this thing in C#, I wanted to see if anyone had any experience dealing with this issue. I do know that the script is connecting to a secure site (HTTPS), so I am not sure if something has come up with that, and I honestly dont know where to look to determine that. As I said before, the site itself isn't showing any signs of error, including SSL. Any thoughts?
[ "I think if it was working up until this point the suspect is not the code but the site. However, you may want to dig around in the code and write some debugging. The urllib2 module method urlopen throws the object URLError as you can see and has an attribute 'reason'. Beyond that I am not sure what you might do to debug the issue. Check the credentials or the certs? Its very possible the cert has expired or something has happened with that. More likely than the code being the issue given its been working all this time.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002473872_python.txt
Q: Ubuntu System Tray in Python How do I put a program in the system tray (I don't think it's called like that in Linux) in python TKINTER for UBUNTU 9.04. A: I don't believe you can do that using Tkinter. You will have to use the gtk libraries. An example, found on a Ubuntu forum: http://ubuntuforums.org/showpost.php?s=bc369fc9343ae728577f1bdcd292caca&p=1053546&postcount=3 Here's an example (in Perl) of combining gtk and Tk. Gtk handles the tray icon, and the rest of the app uses Tk: http://www.perlmonks.org/?node_id=626617 A: You have to use GTK. Do note that Ubuntu 10.04+ has a new, incompatible system tray. It's called AppIndicator; there's a python example here: https://wiki.ubuntu.com/DesktopExperienceTeam/ApplicationIndicators#Python%20version A: There is the sytem tray protocol, which I believe both gnome and kde use. You might be able to use it straight from python using ctype to call X11 methods. But I would go with the GTK solution.
Ubuntu System Tray in Python
How do I put a program in the system tray (I don't think it's called like that in Linux) in python TKINTER for UBUNTU 9.04.
[ "I don't believe you can do that using Tkinter. You will have to use the gtk libraries.\nAn example, found on a Ubuntu forum: http://ubuntuforums.org/showpost.php?s=bc369fc9343ae728577f1bdcd292caca&p=1053546&postcount=3\nHere's an example (in Perl) of combining gtk and Tk. Gtk handles the tray icon, and the rest of the app uses Tk: http://www.perlmonks.org/?node_id=626617\n", "You have to use GTK. Do note that Ubuntu 10.04+ has a new, incompatible system tray. It's called AppIndicator; there's a python example here: https://wiki.ubuntu.com/DesktopExperienceTeam/ApplicationIndicators#Python%20version\n", "There is the sytem tray protocol, which I believe both gnome and kde use. You might be able to use it straight from python using ctype to call X11 methods. But I would go with the GTK solution.\n" ]
[ 8, 7, 3 ]
[]
[]
[ "linux", "python", "tkinter", "ubuntu" ]
stackoverflow_0002400432_linux_python_tkinter_ubuntu.txt
Q: How do I retrieve an automated report and save it to a database? I've got a web server that will take scripts in Python, PHP or Perl. I don't know much about any of those languages, but of the three, Python seems the least scary. It has a MySql database set up, and I know enough SQL to manage it and write queries for it. I also have a program that I want to add automated error reporting to. Something goes wrong, it sends a bug report to my server. What I don't know how to do is write a Python script that will sit on the web server and, when my program sends in a bug report, do the following: Receive the bug report. Parse it out into sections. Insert it into the database. Have the server send me an email. From what little I understand, this seems like it shouldn't be too difficult if I only knew what I was doing. Could someone point me to a site that explains the basic principles I'd need to create a script like this? A: I don't know python so I am showing you php. So assuming your bug sending code posts to file.php?report=report+is+here The following will work. <? # code to initialize the database here $rc = mysql_connect(...); if (!$rc) { die ("Could not connect to the database."); } // probably should do some error checking in a try .. catch mysql_execute(" INSERT INTO BugTable(report) VALUES('".addslashes($_REQUEST['report'])."')"); mail("youremail@set.com","Bug Report Recieved", "Recieved the following bug report: {$_REQUEST['report']}"); ?> Everything about php is at php.net. A: With Python, it depends on your web hosting. Some shared web hosts do PHP and then only do Perl/Python (and Ruby etc.) through CGI. With Python, you can build web stuff either using the CGI model or - if you have hosting that supports it - WSGI. If you are going to do Python and CGI, just look in the documentation for the cgi module. Alternatively, use web.py. You basically need to read in the input as an HTTP POST message on a particular URI. The web.py documentation should describe how to write this. For the parsing - depends on what format it is being sent as. You can use x-www-form-encoded to transmit simple key-value pairs. I don't know the intricacies of web.py (I use Ruby mostly), but it should basically provide you with a way of getting a 'request' object, doing something with it and then you modify a 'return' object which contains what goes back to the browser. With web.py, this is web.input() - see here. For anything more complicated, you need to basically POST the data in your chosen format - XML, JSON, magical binary blob format. How you parse that depends on what it is. Simply Google for "python xml" or "python json" or whatever and you'll find the latest library for it. Inserting into the database - use the mysqldb library for Python (I use Postgres, mostly from Ruby and Java, so I'm not fully hip to the latest Python MySQL libraries). For sending e-mail, you can either just use sendmail (on Unix systems with a sendmail installation) or you can use Python's smtplib to send it to an SMTP server - if you are just doing admin e-mails, use something like a Gmail account as your SMTP server as you know that it is going to work. Oh, web.py makes it easy - it has a built-in mail module. Use that, I guess. You probably need to think about security - that means authentication and it means form validation. RTFM for whatever language and database library you use so you don't open yourself up to SQL injection - and do the same for e-mail. You don't want to be a proxy for spam.
How do I retrieve an automated report and save it to a database?
I've got a web server that will take scripts in Python, PHP or Perl. I don't know much about any of those languages, but of the three, Python seems the least scary. It has a MySql database set up, and I know enough SQL to manage it and write queries for it. I also have a program that I want to add automated error reporting to. Something goes wrong, it sends a bug report to my server. What I don't know how to do is write a Python script that will sit on the web server and, when my program sends in a bug report, do the following: Receive the bug report. Parse it out into sections. Insert it into the database. Have the server send me an email. From what little I understand, this seems like it shouldn't be too difficult if I only knew what I was doing. Could someone point me to a site that explains the basic principles I'd need to create a script like this?
[ "I don't know python so I am showing you php.\nSo assuming your bug sending code posts to file.php?report=report+is+here\nThe following will work. \n<?\n\n # code to initialize the database here\n $rc = mysql_connect(...);\n\n if (!$rc)\n {\n die (\"Could not connect to the database.\");\n }\n\n // probably should do some error checking in a try .. catch\n mysql_execute(\"\n INSERT INTO BugTable(report) \n VALUES('\".addslashes($_REQUEST['report']).\"')\");\n\n mail(\"youremail@set.com\",\"Bug Report Recieved\", \"Recieved the following bug report: {$_REQUEST['report']}\");\n\n ?>\n\nEverything about php is at php.net.\n", "With Python, it depends on your web hosting. Some shared web hosts do PHP and then only do Perl/Python (and Ruby etc.) through CGI. With Python, you can build web stuff either using the CGI model or - if you have hosting that supports it - WSGI. If you are going to do Python and CGI, just look in the documentation for the cgi module. Alternatively, use web.py. You basically need to read in the input as an HTTP POST message on a particular URI. The web.py documentation should describe how to write this.\nFor the parsing - depends on what format it is being sent as. You can use x-www-form-encoded to transmit simple key-value pairs. I don't know the intricacies of web.py (I use Ruby mostly), but it should basically provide you with a way of getting a 'request' object, doing something with it and then you modify a 'return' object which contains what goes back to the browser. With web.py, this is web.input() - see here.\nFor anything more complicated, you need to basically POST the data in your chosen format - XML, JSON, magical binary blob format. How you parse that depends on what it is. Simply Google for \"python xml\" or \"python json\" or whatever and you'll find the latest library for it.\nInserting into the database - use the mysqldb library for Python (I use Postgres, mostly from Ruby and Java, so I'm not fully hip to the latest Python MySQL libraries). \nFor sending e-mail, you can either just use sendmail (on Unix systems with a sendmail installation) or you can use Python's smtplib to send it to an SMTP server - if you are just doing admin e-mails, use something like a Gmail account as your SMTP server as you know that it is going to work. Oh, web.py makes it easy - it has a built-in mail module. Use that, I guess.\nYou probably need to think about security - that means authentication and it means form validation. RTFM for whatever language and database library you use so you don't open yourself up to SQL injection - and do the same for e-mail. You don't want to be a proxy for spam.\n" ]
[ 0, 0 ]
[]
[]
[ "error_reporting", "python" ]
stackoverflow_0002474062_error_reporting_python.txt
Q: Python to extract data from a file I am trying to extract the text between that has specific text file: ---- data1 data1 data1 extractme ---- data2 data2 data2 ---- data3 data3 extractme ---- and then dump it to text file so that ---- data1 data1 data1 extractme --- data3 data3 extractme --- Thanks for the help. A: This works well enough for me. Your sample data is in a file called "data.txt" and the output goes to "result.txt" inFile = open("data.txt") outFile = open("result.txt", "w") buffer = [] keepCurrentSet = True for line in inFile: buffer.append(line) if line.startswith("----"): #---- starts a new data set if keepCurrentSet: outFile.write("".join(buffer)) #now reset our state keepCurrentSet = False buffer = [] elif line.startswith("extractme"): keepCurrentSet = True inFile.close() outFile.close() A: I imagine the change in number of dashes (4 in the input, sometimes 4 and sometimes 3 in the output) is an error and not actually desired (since no algorithm is even hinted at, to explain how many dashes are to be output on different occasions). I would structure the task in terms of reading and yielding one block of lines at a time: def readbyblock(f): while True: block = [] for line in f: if line = '----\n': break block.append(line) if not block: break yield block so that the (selective) output can be neatly separated from the input: with open('infile.txt') as fin: with open('oufile.txt', 'w') as fou: for block in readbyblock(fin): if 'extractme\n' in block: fou.writelines(block) fou.write('----\n') This is not optimal, performance-wise, if the blocks are large, since it has a separate loop on all lines in the block implied in the if clause. So, a good refactoring might be: def selectivereadbyblock(f, marker='extractme\n'): while True: block = [] extract = False for line in f: if line = '----\n': break block.append(line) if line==marker: extract = True if not block: break if extract: yield block with open('infile.txt') as fin: with open('oufile.txt', 'w') as fou: for block in selectivereadbyblock(fin): fou.writelines(block) fou.write('----\n') Parameterizing the separators (now hard-coded as '----\n' for both input and output) is another reasonable coding tweak. A: For Python2 #!/usr/bin/env python with open("infile.txt") as infile: with open("outfile.txt","w") as outfile: collector = [] for line in infile: if line.startswith("----"): collector = [] collector.append(line) if line.startswith("extractme"): for outline in collector: outfile.write(outline) For Python3 #!/usr/bin/env python3 with open("infile.txt") as infile, open("outfile.txt","w") as outfile: collector = [] for line in infile: if line.startswith("----"): collector = [] collector.append(line) if line.startswith("extractme"): for outline in collector: outfile.write(outline) A: data=open("file").read().split("----") print '----'.join([ i for i in data if "extractme" in i ])
Python to extract data from a file
I am trying to extract the text between that has specific text file: ---- data1 data1 data1 extractme ---- data2 data2 data2 ---- data3 data3 extractme ---- and then dump it to text file so that ---- data1 data1 data1 extractme --- data3 data3 extractme --- Thanks for the help.
[ "This works well enough for me. Your sample data is in a file called \"data.txt\" and the output goes to \"result.txt\"\ninFile = open(\"data.txt\")\noutFile = open(\"result.txt\", \"w\")\nbuffer = []\nkeepCurrentSet = True\nfor line in inFile:\n buffer.append(line)\n if line.startswith(\"----\"):\n #---- starts a new data set\n if keepCurrentSet:\n outFile.write(\"\".join(buffer))\n #now reset our state\n keepCurrentSet = False\n buffer = []\n elif line.startswith(\"extractme\"):\n keepCurrentSet = True\ninFile.close()\noutFile.close()\n\n", "I imagine the change in number of dashes (4 in the input, sometimes 4 and sometimes 3 in the output) is an error and not actually desired (since no algorithm is even hinted at, to explain how many dashes are to be output on different occasions).\nI would structure the task in terms of reading and yielding one block of lines at a time:\ndef readbyblock(f):\n while True:\n block = []\n for line in f:\n if line = '----\\n': break\n block.append(line)\n if not block: break\n yield block\n\nso that the (selective) output can be neatly separated from the input:\nwith open('infile.txt') as fin:\n with open('oufile.txt', 'w') as fou:\n for block in readbyblock(fin):\n if 'extractme\\n' in block:\n fou.writelines(block)\n fou.write('----\\n')\n\nThis is not optimal, performance-wise, if the blocks are large, since it has a separate loop on all lines in the block implied in the if clause. So, a good refactoring might be:\ndef selectivereadbyblock(f, marker='extractme\\n'):\n while True:\n block = []\n extract = False\n for line in f:\n if line = '----\\n': break\n block.append(line)\n if line==marker: extract = True\n if not block: break\n if extract: yield block\n\nwith open('infile.txt') as fin:\n with open('oufile.txt', 'w') as fou:\n for block in selectivereadbyblock(fin):\n fou.writelines(block)\n fou.write('----\\n')\n\nParameterizing the separators (now hard-coded as '----\\n' for both input and output) is another reasonable coding tweak.\n", "For Python2\n#!/usr/bin/env python\n\nwith open(\"infile.txt\") as infile:\n with open(\"outfile.txt\",\"w\") as outfile:\n collector = []\n for line in infile:\n if line.startswith(\"----\"):\n collector = []\n collector.append(line)\n if line.startswith(\"extractme\"):\n for outline in collector:\n outfile.write(outline)\n\nFor Python3\n#!/usr/bin/env python3\n\nwith open(\"infile.txt\") as infile, open(\"outfile.txt\",\"w\") as outfile:\n collector = []\n for line in infile:\n if line.startswith(\"----\"):\n collector = []\n collector.append(line)\n if line.startswith(\"extractme\"):\n for outline in collector:\n outfile.write(outline)\n\n", "data=open(\"file\").read().split(\"----\")\nprint '----'.join([ i for i in data if \"extractme\" in i ])\n\n" ]
[ 6, 5, 2, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002474216_file_io_python.txt
Q: PyQt and unittest - how to handle signals and slots some small application I'm developing uses a module I have written to check certain web services via a REST API. I've been trying to add unit tests to it so I don't break stuff, and I stumbled upon a problem. I use a lot of signal-slot connections to perform operations asynchronously. For example a typical test would be (pseudo-Python), with postDataDownloaded as a signal: def testConnection(self): "Test connection and posts retrieved" def length_test(): self.assertEqual(len(self.client.post_data), 5) self.client.postDataReady.connect(length_test) self.client.get_post_list(limit=5) Now, unittest will report this test to be "ok" when running, regardless of the result (as another slot is being called), even if asserts fail (I will get an unhandled AssertionError). Example when deliberatiely making the test fail: Test connection and posts retrieved ... ok [... more tests...] OK Traceback (most recent call last): [...] AssertionError: 4 != 5 The slot inside the test is merely an experiment: I get the same results if it's outside (instance method). I also have to add that the various methods I'm calling all make HTTP requests, which means they take a bit of time (I need to mock the request - in the mean time I'm using SimpleHTTPServer to fake the connections and give them proper data). Is there a way around this problem? A: You need to avoid exiting the test method until the callback has been called. I believe the call is going to happen in a separate thread, so a threading.Event seems appropriate: import threading ... def testConnection(self): "Test connection and posts retrieved" self.evt = threading.Event() def length_test(): self.evt.set() self.client.postDataReady.connect(length_test) self.client.get_post_list(limit=5) self.evt.wait() self.assertEqual(len(self.client.post_data), 5)
PyQt and unittest - how to handle signals and slots
some small application I'm developing uses a module I have written to check certain web services via a REST API. I've been trying to add unit tests to it so I don't break stuff, and I stumbled upon a problem. I use a lot of signal-slot connections to perform operations asynchronously. For example a typical test would be (pseudo-Python), with postDataDownloaded as a signal: def testConnection(self): "Test connection and posts retrieved" def length_test(): self.assertEqual(len(self.client.post_data), 5) self.client.postDataReady.connect(length_test) self.client.get_post_list(limit=5) Now, unittest will report this test to be "ok" when running, regardless of the result (as another slot is being called), even if asserts fail (I will get an unhandled AssertionError). Example when deliberatiely making the test fail: Test connection and posts retrieved ... ok [... more tests...] OK Traceback (most recent call last): [...] AssertionError: 4 != 5 The slot inside the test is merely an experiment: I get the same results if it's outside (instance method). I also have to add that the various methods I'm calling all make HTTP requests, which means they take a bit of time (I need to mock the request - in the mean time I'm using SimpleHTTPServer to fake the connections and give them proper data). Is there a way around this problem?
[ "You need to avoid exiting the test method until the callback has been called. I believe the call is going to happen in a separate thread, so a threading.Event seems appropriate:\nimport threading\n\n...\n\ndef testConnection(self):\n \"Test connection and posts retrieved\"\n\n self.evt = threading.Event()\n\n def length_test():\n self.evt.set()\n\n self.client.postDataReady.connect(length_test)\n self.client.get_post_list(limit=5)\n self.evt.wait()\n self.assertEqual(len(self.client.post_data), 5)\n\n" ]
[ 3 ]
[]
[]
[ "pyqt", "python", "unit_testing" ]
stackoverflow_0002473577_pyqt_python_unit_testing.txt
Q: Python 'datetime.datetime' object is unsubscriptable First, I am NOT a python developer. I am trying to fix an issue within a python script that is being executed from the command line. This script was written by someone who is no longer around, and no longer willing to help with issues. This is python 2.5, and for the moment it cannot be upgraded. Here are the lines of code in question: start_time = datetime.strptime(str(paf.Start),"%Y-%m-%d %H:%M:%S") dict_start = datetime(*start_time[:6]) end_time = datetime.strptime(str(paf.End),"%Y-%m-%d %H:%M:%S") dict_end = datetime(*end_time[:6]) When this code is ran, it generates an error with the description: 'datetime.datetime' object is unsubscriptable. This is the import statement: from datetime import datetime I have a feeling that this is something simple, but not being my native language and Google not yielding any valuable results, I am stuck. I have tried a couple of different import methods, yielding different errors, but all with these statements. Any help on this would be greatly appreciated. A: It looks like you just want the time right? The datetime.strptime method returns a 'datetime' object and as such the following attributes contain the time: datetime.day, datetime.hour, datetime.year, etc. A: Its not the import fault. Its the *start_time[:6] *end_time[:6] that Python doesn't like. Replace it A: Robert, try replacing dict_start = datetime(*start_time[:6]) with dict_start = start_time and dict_end = datetime(*end_time[:6]) with dict_end = end_time It looks silly, but perhaps try it anyway. My reason is this: datetime.strptime returns a datetime.datetime object. Since the code originally says dict_start = datetime(*start_time[:6]) it appears that dict_start is intended to also be a datetime.datetime, with the same 6 fields (year,month,day,hour,minutes,seconds). So try dict_start = start_time If that doesn't work, you might have to show us more of the code so we can form a better guess as to what was intended. Edit: The easiest way to get at the individual fields (year,month,day,hour,minutes,seconds) is to use the dot notation to access the attributes. For example, (start_time.year,start_time.month,start_time.day) gives a 3-tuple with the year, month, and day as integers. PS. For more info about datetime objects, see http://docs.python.org/library/datetime.html. It may contain useful examples for you. A: Looks like the datetime.strptime call was actually meant to be a call to time.strptime (with a separate import time at the start of the module) -- the latter call would indeed return a subscriptable, tuple-like object, and the idiom xx = time.strptime(...) yy = datetime.datetime(x[:6]) (with import time and import datetime at the start of the module, of course) was indeed the canonical way to parse a string into a datetime.datetime instance before the datetime.datetime type added its own strptime function which basically does just this job. So, it looks like "imperfectly migrated" code. To extract just the date (as a datetime.date object, with just year, month and day -- no hours, minutes, seconds and fractions) from a datetime.datetime instance x, call x.date() which will return the desired date object (not modify x itself of course: datetime objects are immutable -- you always make new ones, not change existing ones). A: Observations: Whoever wrote the code didn't test it; it never could have run properly. Whoever wrote it was confusing datetime.datetime.strptime with time.strptime. Once upon a time (pun intended) datetime.datetime.strptime didn't exist. One had to do something like the following: >>> from datetime import datetime >>> import time >>> time_tuple = time.strptime("2010-03-19 13:22:45","%Y-%m-%d %H:%M:%S") >>> time_tuple (2010, 3, 19, 13, 22, 45, 4, 78, -1) >>> datetime(*time_tuple[:6]) datetime.datetime(2010, 3, 19, 13, 22, 45) (The [:6] was a dead give-away) Now one can do this: >>> from datetime import datetime >>> datetime.strptime("2010-03-19 13:22:45","%Y-%m-%d %H:%M:%S") datetime.datetime(2010, 3, 19, 13, 22, 45) A: The following code doesn't make sense to me: start_time = datetime.strptime(str(paf.Start),"%Y-%m-%d %H:%M:%S") dict_start = datetime(*start_time[:6]) If you need a tuple mapping in dict_start, then use something like this: start_time = datetime.strptime(str(paf.Start),"%Y-%m-%d %H:%M:%S") dict_start = start_time.timetuple()[:6] If you need dict, then: start_time = datetime.strptime(str(paf.Start),"%Y-%m-%d %H:%M:%S") dict_start = dict(zip(('year', 'month' ,'day', 'hour', 'minute', 'second'), start_time.timetuple()[:6])) -- or use paf.Start, if possible. Also, I'm not sure but it could be that ('year', 'month' ,'day', 'hour', 'minute', 'second') tuple is predefined somewhere in Python std lib or it can be easily replaced with some other construct, but it's midnight here and I don't see any other obvious solution.
Python 'datetime.datetime' object is unsubscriptable
First, I am NOT a python developer. I am trying to fix an issue within a python script that is being executed from the command line. This script was written by someone who is no longer around, and no longer willing to help with issues. This is python 2.5, and for the moment it cannot be upgraded. Here are the lines of code in question: start_time = datetime.strptime(str(paf.Start),"%Y-%m-%d %H:%M:%S") dict_start = datetime(*start_time[:6]) end_time = datetime.strptime(str(paf.End),"%Y-%m-%d %H:%M:%S") dict_end = datetime(*end_time[:6]) When this code is ran, it generates an error with the description: 'datetime.datetime' object is unsubscriptable. This is the import statement: from datetime import datetime I have a feeling that this is something simple, but not being my native language and Google not yielding any valuable results, I am stuck. I have tried a couple of different import methods, yielding different errors, but all with these statements. Any help on this would be greatly appreciated.
[ "It looks like you just want the time right? The datetime.strptime method returns a 'datetime' object and as such the following attributes contain the time: datetime.day, datetime.hour, datetime.year, etc.\n", "Its not the import fault. Its the *start_time[:6] *end_time[:6] that Python doesn't like. Replace it\n", "Robert, try replacing\ndict_start = datetime(*start_time[:6])\n\nwith\ndict_start = start_time\n\nand \ndict_end = datetime(*end_time[:6])\n\nwith \ndict_end = end_time\n\nIt looks silly, but perhaps try it anyway. My reason is this: datetime.strptime returns a datetime.datetime object. Since the code originally says\ndict_start = datetime(*start_time[:6])\n\nit appears that dict_start is intended to also be a datetime.datetime, with the same 6 fields (year,month,day,hour,minutes,seconds). So try\ndict_start = start_time\n\nIf that doesn't work, you might have to show us more of the code so we can form a better guess as to what was intended.\nEdit: The easiest way to get at the individual fields (year,month,day,hour,minutes,seconds) is to use the dot notation to access the attributes. For example,\n(start_time.year,start_time.month,start_time.day)\n\ngives a 3-tuple with the year, month, and day as integers.\nPS. For more info about datetime objects, see http://docs.python.org/library/datetime.html. It may contain useful examples for you.\n", "Looks like the datetime.strptime call was actually meant to be a call to time.strptime (with a separate import time at the start of the module) -- the latter call would indeed return a subscriptable, tuple-like object, and the idiom\nxx = time.strptime(...)\nyy = datetime.datetime(x[:6])\n\n(with import time and import datetime at the start of the module, of course) was indeed the canonical way to parse a string into a datetime.datetime instance before the datetime.datetime type added its own strptime function which basically does just this job. So, it looks like \"imperfectly migrated\" code.\nTo extract just the date (as a datetime.date object, with just year, month and day -- no hours, minutes, seconds and fractions) from a datetime.datetime instance x, call x.date() which will return the desired date object (not modify x itself of course: datetime objects are immutable -- you always make new ones, not change existing ones).\n", "Observations:\nWhoever wrote the code didn't test it; it never could have run properly.\nWhoever wrote it was confusing datetime.datetime.strptime with time.strptime.\nOnce upon a time (pun intended) datetime.datetime.strptime didn't exist. One had to do something like the following: \n>>> from datetime import datetime\n>>> import time\n>>> time_tuple = time.strptime(\"2010-03-19 13:22:45\",\"%Y-%m-%d %H:%M:%S\")\n>>> time_tuple\n(2010, 3, 19, 13, 22, 45, 4, 78, -1)\n>>> datetime(*time_tuple[:6])\ndatetime.datetime(2010, 3, 19, 13, 22, 45)\n\n(The [:6] was a dead give-away)\nNow one can do this:\n>>> from datetime import datetime\n>>> datetime.strptime(\"2010-03-19 13:22:45\",\"%Y-%m-%d %H:%M:%S\")\ndatetime.datetime(2010, 3, 19, 13, 22, 45)\n\n", "The following code doesn't make sense to me:\nstart_time = datetime.strptime(str(paf.Start),\"%Y-%m-%d %H:%M:%S\")\ndict_start = datetime(*start_time[:6])\n\nIf you need a tuple mapping in dict_start, then use something like this:\nstart_time = datetime.strptime(str(paf.Start),\"%Y-%m-%d %H:%M:%S\")\ndict_start = start_time.timetuple()[:6]\n\nIf you need dict, then:\nstart_time = datetime.strptime(str(paf.Start),\"%Y-%m-%d %H:%M:%S\")\ndict_start = dict(zip(('year', 'month' ,'day', 'hour', 'minute', 'second'), start_time.timetuple()[:6]))\n\n-- or use paf.Start, if possible. Also, I'm not sure but it could be that ('year', 'month' ,'day', 'hour', 'minute', 'second') tuple is predefined somewhere in Python std lib or it can be easily replaced with some other construct, but it's midnight here and I don't see any other obvious solution.\n" ]
[ 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002473760_python.txt
Q: Explicit disable MySQL query cache in some parts of program In a Django project, some cronjob programs are mainly used for administrative or analysis purposes, e.g. generating site usage stats, rotating user activities log, etc. We probably do not hope MySQL to cache queries in those programs to save memory usage and improve query cache efficiency. Is it possible to turn off MySQL query cache explicitly in those programs while keep it enabled for other parts including all views.py? A: Per http://dev.mysql.com/doc/refman/5.1/en/query-cache-configuration.html Individual clients can control cache behavior for their own connection by setting the SESSION query_cache_type value. For example, a client can disable use of the query cache for its own queries like this: mysql> SET SESSION query_cache_type = OFF; There's not usually a compelling reason to bother, though. The query cache isn't nearly as important as you might think, particularly during off-peak periods (which I assume is when you would run the cron jobs).
Explicit disable MySQL query cache in some parts of program
In a Django project, some cronjob programs are mainly used for administrative or analysis purposes, e.g. generating site usage stats, rotating user activities log, etc. We probably do not hope MySQL to cache queries in those programs to save memory usage and improve query cache efficiency. Is it possible to turn off MySQL query cache explicitly in those programs while keep it enabled for other parts including all views.py?
[ "Per http://dev.mysql.com/doc/refman/5.1/en/query-cache-configuration.html\n\nIndividual clients can control cache behavior for their own connection by setting the SESSION query_cache_type value. For example, a client can disable use of the query cache for its own queries like this:\nmysql> SET SESSION query_cache_type = OFF;\n\nThere's not usually a compelling reason to bother, though. The query cache isn't nearly as important as you might think, particularly during off-peak periods (which I assume is when you would run the cron jobs).\n" ]
[ 2 ]
[]
[]
[ "caching", "django", "mysql", "python" ]
stackoverflow_0002474609_caching_django_mysql_python.txt
Q: Python: speed up removal of every n-th element from list I'm trying to solve this programming riddle and although the solution (see code below) works correctly, it is too slow for succesful submission. Any pointers as how to make this run faster (removal of every n-th element from a list)? Or suggestions for a better algorithm to calculate the same; seems I can't think of anything else than brute-force for now... Basically, the task at hand is: GIVEN: L = [2,3,4,5,6,7,8,9,10,11,........] 1. Take the first remaining item in list L (in the general case 'n'). Move it to the 'lucky number list'. Then drop every 'n-th' item from the list. 2. Repeat 1 TASK: Calculate the n-th number from the 'lucky number list' ( 1 <= n <= 3000) My original code (it calculated the 3000 first lucky numbers in about a second on my machine - unfortunately too slow): """ SPOJ Problem Set (classical) 1798. Assistance Required URL: http://www.spoj.pl/problems/ASSIST/ """ sieve = range(3, 33900, 2) luckynumbers = [2] while True: wanted_n = input() if wanted_n == 0: break while len(luckynumbers) < wanted_n: item = sieve[0] luckynumbers.append(item) items_to_delete = set(sieve[::item]) sieve = filter(lambda x: x not in items_to_delete, sieve) print luckynumbers[wanted_n-1] EDIT: thanks to the terrific contributions of Mark Dickinson, Steve Jessop and gnibbler, I got at the following, which is quite a whole lot faster than my original code (and succesfully got submitted at http://www.spoj.pl with 0.58 seconds!)... sieve = range(3, 33810, 2) luckynumbers = [2] while len(luckynumbers) < 3000: if len(sieve) < sieve[0]: luckynumbers.extend(sieve) break luckynumbers.append(sieve[0]) del sieve[::sieve[0]] while True: wanted_n = input() if wanted_n == 0: break else: print luckynumbers[wanted_n-1] A: This series is called ludic numbers __delslice__ should be faster than __setslice__+filter >>> L=[2,3,4,5,6,7,8,9,10,11,12] >>> lucky=[] >>> lucky.append(L[0]) >>> del L[::L[0]] >>> L [3, 5, 7, 9, 11] >>> lucky.append(L[0]) >>> del L[::L[0]] >>> L [5, 7, 11] So the loop becomes. while len(luckynumbers) < 3000: item = sieve[0] luckynumbers.append(item) del sieve[::item] Which runs in less than 0.1 second A: Try using these two lines for the deletion and filtering, instead of what you have; filter(None, ...) runs considerably faster than the filter(lambda ...). sieve[::item] = [0]*-(-len(sieve)//item) sieve = filter(None, sieve) Edit: much better to simply use del sieve[::item]; see gnibbler's solution. You might also be able to find a better termination condition for the while loop: for example, if the first remaining item in the sieve is i then the first i elements of the sieve will become the next i lucky numbers; so if len(luckynumbers) + sieve[0] >= wanted_n you should already have computed the number you need---you just need to figure out where in sieve it is so that you can extract it. On my machine, the following version of your inner loop runs around 15 times faster than your original for finding the 3000th lucky number: while len(luckynumbers) + sieve[0] < wanted_n: item = sieve[0] luckynumbers.append(item) sieve[::item] = [0]*-(-len(sieve)//item) sieve = filter(None, sieve) print (luckynumbers + sieve)[wanted_n-1] A: An explanation on how to solve this problem can be found here. (The problem I linked to asks for more, but the main step in that problem is the same as the one you're trying to solve.) The site I linked to also contains a sample solution in C++. The set of numbers can be represented in a binary tree, which supports the following operations: Return the nth element Erase the nth element These operations can be implemented to run in O(log n) time, where n is the number of nodes in the tree. To build the tree, you can either make a custom routine that builds the tree from a given array of elements, or implement an insert operation (make sure to keep the tree balanced). Each node in the tree need the following information: Pointers to the left and right children How many items there are in the left and right subtrees With such a structure in place, solving the rest of the problem should be fairly straightforward. I also recommend calculating the answers for all possible input values before reading any input, instead of calculating the answer for each input line. A Java implementation of the above algorithm gets accepted in 0.68 seconds at the website you linked. (Sorry for not providing any Python-specific help, but hopefully the algorithm outlined above will be fast enough.) A: You're better off using an array and zeroing out every Nth item using that strategy; after you do this a few times in a row, the updates start getting tricky so you'd want to re-form the array. This should improve the speed by at least a factor of 10. Do you need vastly better than that? A: Why not just create a new list? L = [x for (i, x) in enumerate(L) if i % n]
Python: speed up removal of every n-th element from list
I'm trying to solve this programming riddle and although the solution (see code below) works correctly, it is too slow for succesful submission. Any pointers as how to make this run faster (removal of every n-th element from a list)? Or suggestions for a better algorithm to calculate the same; seems I can't think of anything else than brute-force for now... Basically, the task at hand is: GIVEN: L = [2,3,4,5,6,7,8,9,10,11,........] 1. Take the first remaining item in list L (in the general case 'n'). Move it to the 'lucky number list'. Then drop every 'n-th' item from the list. 2. Repeat 1 TASK: Calculate the n-th number from the 'lucky number list' ( 1 <= n <= 3000) My original code (it calculated the 3000 first lucky numbers in about a second on my machine - unfortunately too slow): """ SPOJ Problem Set (classical) 1798. Assistance Required URL: http://www.spoj.pl/problems/ASSIST/ """ sieve = range(3, 33900, 2) luckynumbers = [2] while True: wanted_n = input() if wanted_n == 0: break while len(luckynumbers) < wanted_n: item = sieve[0] luckynumbers.append(item) items_to_delete = set(sieve[::item]) sieve = filter(lambda x: x not in items_to_delete, sieve) print luckynumbers[wanted_n-1] EDIT: thanks to the terrific contributions of Mark Dickinson, Steve Jessop and gnibbler, I got at the following, which is quite a whole lot faster than my original code (and succesfully got submitted at http://www.spoj.pl with 0.58 seconds!)... sieve = range(3, 33810, 2) luckynumbers = [2] while len(luckynumbers) < 3000: if len(sieve) < sieve[0]: luckynumbers.extend(sieve) break luckynumbers.append(sieve[0]) del sieve[::sieve[0]] while True: wanted_n = input() if wanted_n == 0: break else: print luckynumbers[wanted_n-1]
[ "This series is called ludic numbers\n__delslice__ should be faster than __setslice__+filter\n>>> L=[2,3,4,5,6,7,8,9,10,11,12]\n>>> lucky=[]\n>>> lucky.append(L[0])\n>>> del L[::L[0]]\n>>> L\n[3, 5, 7, 9, 11]\n>>> lucky.append(L[0])\n>>> del L[::L[0]]\n>>> L\n[5, 7, 11]\n\nSo the loop becomes.\nwhile len(luckynumbers) < 3000:\n item = sieve[0]\n luckynumbers.append(item)\n del sieve[::item] \n\nWhich runs in less than 0.1 second\n", "Try using these two lines for the deletion and filtering, instead of what you have; filter(None, ...) runs considerably faster than the filter(lambda ...).\nsieve[::item] = [0]*-(-len(sieve)//item)\nsieve = filter(None, sieve)\n\nEdit: much better to simply use del sieve[::item]; see gnibbler's solution.\nYou might also be able to find a better termination condition for the while loop: for example, if the first remaining item in the sieve is i then the first i elements of the sieve will become the next i lucky numbers; so if len(luckynumbers) + sieve[0] >= wanted_n you should already have computed the number you need---you just need to figure out where in sieve it is so that you can extract it.\nOn my machine, the following version of your inner loop runs around 15 times faster than your original for finding the 3000th lucky number:\nwhile len(luckynumbers) + sieve[0] < wanted_n:\n item = sieve[0]\n luckynumbers.append(item)\n sieve[::item] = [0]*-(-len(sieve)//item)\n sieve = filter(None, sieve)\nprint (luckynumbers + sieve)[wanted_n-1]\n\n", "An explanation on how to solve this problem can be found here. (The problem I linked to asks for more, but the main step in that problem is the same as the one you're trying to solve.) The site I linked to also contains a sample solution in C++.\nThe set of numbers can be represented in a binary tree, which supports the following operations:\n\nReturn the nth element\nErase the nth element\n\nThese operations can be implemented to run in O(log n) time, where n is the number of nodes in the tree.\nTo build the tree, you can either make a custom routine that builds the tree from a given array of elements, or implement an insert operation (make sure to keep the tree balanced).\nEach node in the tree need the following information:\n\nPointers to the left and right children\nHow many items there are in the left and right subtrees\n\nWith such a structure in place, solving the rest of the problem should be fairly straightforward.\nI also recommend calculating the answers for all possible input values before reading any input, instead of calculating the answer for each input line.\nA Java implementation of the above algorithm gets accepted in 0.68 seconds at the website you linked.\n(Sorry for not providing any Python-specific help, but hopefully the algorithm outlined above will be fast enough.)\n", "You're better off using an array and zeroing out every Nth item using that strategy; after you do this a few times in a row, the updates start getting tricky so you'd want to re-form the array. This should improve the speed by at least a factor of 10. Do you need vastly better than that?\n", "Why not just create a new list?\nL = [x for (i, x) in enumerate(L) if i % n]\n\n" ]
[ 7, 4, 2, 1, 0 ]
[]
[]
[ "algorithm", "performance", "python" ]
stackoverflow_0002473710_algorithm_performance_python.txt