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: Help with Django app and payment systems (general queries) So I'm working on an app in Django, however this is my first time venturing into advance integration for a webapp with payment systems (I used to work with paypal/2checkout so it was pretty no-skill-required). My partners have chosen PaymentExpress, and th...
Help with Django app and payment systems (general queries)
So I'm working on an app in Django, however this is my first time venturing into advance integration for a webapp with payment systems (I used to work with paypal/2checkout so it was pretty no-skill-required). My partners have chosen PaymentExpress, and there are several sets of API (all of which are pretty new to me) ...
[ "PXPost is the most straight-forward solution. You just communicate via HTTP POSTs and XML. You don't need any external dependencies, just urllib2 and ElementTree. \nSoftware toolkit can be used only on Windows platform, so it's not an option for you(or is it?). COM is also a nasty beast.\nWeb service is a more ele...
[ 0 ]
[]
[]
[ "django", "payment", "python" ]
stackoverflow_0000954478_django_payment_python.txt
Q: How to debug Google App Engine scripts with PyScripter The situation is as follows: I have downloaded the Google App Engine SDK. I have written my "helloworld" app that runs locally in my computer. I have to use PyScripter as IDE. I can't use Eclipse, that would not be a valid solution to my problem. In PyScr...
How to debug Google App Engine scripts with PyScripter
The situation is as follows: I have downloaded the Google App Engine SDK. I have written my "helloworld" app that runs locally in my computer. I have to use PyScripter as IDE. I can't use Eclipse, that would not be a valid solution to my problem. In PyScripter, I have set a "Run Configuration", so that an instance...
[ "I think this is a PyScripter's bug. I tested in version 1.9.9.7 and the same problem is still there. \n" ]
[ 2 ]
[]
[]
[ "debugging", "google_app_engine", "pyscripter", "python" ]
stackoverflow_0000789558_debugging_google_app_engine_pyscripter_python.txt
Q: By System command By using system command i want to open '.py' in the notepad. Ex assume i have "Fact.py" file. Now i want to write a program which will open this file in notepad and we can edit this file. A: It's best to use subprocess for this, since this will avoid having to deal with quoting files containin...
By System command
By using system command i want to open '.py' in the notepad. Ex assume i have "Fact.py" file. Now i want to write a program which will open this file in notepad and we can edit this file.
[ "It's best to use subprocess for this, since this will avoid having to deal with quoting files containing spaces etc for the shell.\nimport subprocess\nsubprocess.call(['notepad','Fact.py'])\n\n", "import os\n\nos.system(\"notepad.exe fact.py\")\n\nshould do it, assuming the Notepad program is in your system's pa...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000954823_python.txt
Q: how to program functions with alternative return value signatures in python? (next() for alternative iterators) e.g. so that these would both work - is it possible? (val,VAL2) = func(args) val = func(args) Where val is not a tuple For example I'd like these to work for my custom object something for item in some...
how to program functions with alternative return value signatures in python? (next() for alternative iterators)
e.g. so that these would both work - is it possible? (val,VAL2) = func(args) val = func(args) Where val is not a tuple For example I'd like these to work for my custom object something for item in something: do_item(item) #where again item - is not a tuple for (item,key) in something: do_more(key,item) I th...
[ "If you mean, can the function act differently based on the return types the caller is expecting, the answer is no (bar seriously nasty bytecode inspection). In this case, you should provide two different iterators on your object, and write something like:\nfor item in something: # Default iterator: returns non-t...
[ 7, 5, 3, 3, 3, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000953914_python.txt
Q: How can I tell if a certain key was pressed in Python? import sys print (sys.platform) print (2 ** 100) input('press Enter to exit') Suppose I wanted to use the number 1 as the button that must be pressed to exit. How would I go about doing this? A: Something like this? http://mail.python.org/pipermail/python-...
How can I tell if a certain key was pressed in Python?
import sys print (sys.platform) print (2 ** 100) input('press Enter to exit') Suppose I wanted to use the number 1 as the button that must be pressed to exit. How would I go about doing this?
[ "Something like this?\nhttp://mail.python.org/pipermail/python-list/1999-October/014262.html\nNot so clean, but doable.\n", "If you're building a command line app, why not use one of the libraries that help you build one.\nFor example:\n\ncurses \nurwid.\n\n", "Something like this will do what you want:\nwhile(...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000954933_python.txt
Q: How do I use a Python library in my Java application? What are the basic nuts and bolts of calling (running? interpreting? what can you do?) Python code from a Java program? Are there many ways to do it? A: You can embed Jython within your Java application, rather than spawning off a separate process. Provided ...
How do I use a Python library in my Java application?
What are the basic nuts and bolts of calling (running? interpreting? what can you do?) Python code from a Java program? Are there many ways to do it?
[ "You can embed Jython within your Java application, rather than spawning off a separate process. Provided your library is compatible with Jython, that would seem the most logical place to start.\n", "Apart from embedding Jython as mentioned by Brian, you have these options as well.\nJava 1.6 has inbuilt support f...
[ 4, 2, 0 ]
[]
[]
[ "java", "jython", "python" ]
stackoverflow_0000954950_java_jython_python.txt
Q: Finding out which functions are available from a class instance in python? How do you dynamically find out which functions have been defined from an instance of a class? For example: class A(object): def methodA(self, intA=1): pass def methodB(self, strB): pass a = A() Ideally I want to ...
Finding out which functions are available from a class instance in python?
How do you dynamically find out which functions have been defined from an instance of a class? For example: class A(object): def methodA(self, intA=1): pass def methodB(self, strB): pass a = A() Ideally I want to find out that the instance 'a' has methodA and methodB, and which arguments they...
[ "Have a look at the inspect module.\n>>> import inspect\n>>> inspect.getmembers(a)\n[('__class__', <class '__main__.A'>),\n ('__delattr__', <method-wrapper '__delattr__' of A object at 0xb77d48ac>),\n ('__dict__', {}),\n ('__doc__', None),\n ('__getattribute__',\n <method-wrapper '__getattribute__' of A object at ...
[ 15 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0000955533_introspection_python.txt
Q: PyS60 application not going full screen I am very new to PyS60. I was testing how to set an application to full screen mode but unfortunately, it doesn't work as expected. I tested the script on Nokia 6120 Classic. Here is what I did: appuifw.app.screen = 'full' What I get is a half screen of my application with...
PyS60 application not going full screen
I am very new to PyS60. I was testing how to set an application to full screen mode but unfortunately, it doesn't work as expected. I tested the script on Nokia 6120 Classic. Here is what I did: appuifw.app.screen = 'full' What I get is a half screen of my application with a plain white colour below. What am I doing ...
[ "Make sure you define own functions for screen redraw and screen rotate callbacks. When you rotate the device, you have to manually rescale everything to fit the new screen size. Otherwise you might get that \"half of screen\" effect.\n\n canvas = img = None\n\n def cb_redraw(aRect=(0,0,0,0)):\n ''' Ov...
[ 4, 0 ]
[]
[]
[ "pys60", "python", "symbian" ]
stackoverflow_0000954272_pys60_python_symbian.txt
Q: Create plugins for python standalone executables how to create a good plugin engine for standalone executables created with pyInstaller, py2exe or similar tools? I do not have experience with py2exe, but pyInstaller uses an import hook to import packages from it's compressed repository. Of course I am able to imp...
Create plugins for python standalone executables
how to create a good plugin engine for standalone executables created with pyInstaller, py2exe or similar tools? I do not have experience with py2exe, but pyInstaller uses an import hook to import packages from it's compressed repository. Of course I am able to import dynamically another compressed repository created ...
[ "When compiling to exe, your going to have this issue.\nThe only option I can think of to allow users access with thier plugins to use any python library is to include all libraries in the exe package. \nIt's probably a good idea to limit supported libraries to a subset, and list it in your documentation. Up to yo...
[ 3, 1 ]
[]
[]
[ "plugins", "py2exe", "pyinstaller", "python" ]
stackoverflow_0000307338_plugins_py2exe_pyinstaller_python.txt
Q: Data Synchronization framework / algorithm for server<->device? I'm looking to implement data synchronization between servers and distributed clients. The data source on the server is mysql with django on top. The client can vary. Updates can take place on either client or server, and the connection between server...
Data Synchronization framework / algorithm for server<->device?
I'm looking to implement data synchronization between servers and distributed clients. The data source on the server is mysql with django on top. The client can vary. Updates can take place on either client or server, and the connection between server and client is not reliable (eg. changes can be made on a disconnecte...
[ "Perhaps using plain old rsync is enough.\n", "AFAIK there isnt any generic solution to this mainly due to the diverse requirements for synchronization.\nIn one of our earlier projects we implemented a Spring batching based sync mechanism which relies on last updated timestamp field on each of the tables (that ta...
[ 1, 1 ]
[]
[]
[ "django", "python", "synchronization" ]
stackoverflow_0000682951_django_python_synchronization.txt
Q: Iterating through large lists with potential conditions in Python I have large chunks of data, normally at around 2000+ entries, but in this report we have the ability to look as far as we want so it could be up to 10,000 records The report is split up into: Two categories and then within each Category, we split b...
Iterating through large lists with potential conditions in Python
I have large chunks of data, normally at around 2000+ entries, but in this report we have the ability to look as far as we want so it could be up to 10,000 records The report is split up into: Two categories and then within each Category, we split by Currency so we have several sub categories within the list. My issue ...
[ "You could define a little inline function:\ndef EntryMatches(e):\n if use_currency and not (e.currency == currency):\n return False\n if use_category and not (e.category == category):\n return False\n return True\n\nthen\ntotals['quantity'] = sum([e.quantity for e in entries if EntryMatches(e)])\n\nEntryM...
[ 6 ]
[]
[]
[ "django", "list", "python" ]
stackoverflow_0000956820_django_list_python.txt
Q: Am I missing step in building/installing VTK-5.4 with Python2.6 bindings on Ubuntu 9.04? I successfully built and installed VTK-5.4 with Python bindings from source. Yet, when I try to import VTK in python it gives the following Traceback error File "", line 1, in File "/usr/local/lib/python2.6/dist-packag...
Am I missing step in building/installing VTK-5.4 with Python2.6 bindings on Ubuntu 9.04?
I successfully built and installed VTK-5.4 with Python bindings from source. Yet, when I try to import VTK in python it gives the following Traceback error File "", line 1, in File "/usr/local/lib/python2.6/dist-packages/VTK-5.4.2-py2.6.egg/vtk/init.py", line 41, in from common import * File "/usr/local...
[ "Test if adding /usr/local/lib to your $LD_LIBRARY_PATH helps:\nIn a shell:\nexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib\n\nIf it works, make it permanent by (adding /usr/local/lib to /etc/ld.so.conf) _ (running 'ldconfig -n /usr/local/lib')\n" ]
[ 5 ]
[]
[]
[ "3d", "python", "vtk" ]
stackoverflow_0000956716_3d_python_vtk.txt
Q: Bundling PyQwt with py2exe I have a standard setup script for py2exe with which I bundle PyQt-based applications into Windows .exe files. Today I tried a simple script that uses the PyQwt module, and it doesn't seem to work. py2exe runs alright, but when I execute the .exe it creates, it dumps the following into a...
Bundling PyQwt with py2exe
I have a standard setup script for py2exe with which I bundle PyQt-based applications into Windows .exe files. Today I tried a simple script that uses the PyQwt module, and it doesn't seem to work. py2exe runs alright, but when I execute the .exe it creates, it dumps the following into a log file and doesn't run: Trace...
[ "py2exe is not the only way, and maybe not the best way, to put together exe files for Python apps -- in particular, it hardly if at all supports pyqt. Please, I beseech you, check out PyInstaller, which DOES know about PyQt (and Linux, and Mac, should you care...) -- just make sure you use the SVN head checkout, n...
[ 4, 1 ]
[]
[]
[ "py2exe", "pyqt", "python" ]
stackoverflow_0000899658_py2exe_pyqt_python.txt
Q: python web framework focusing on json-oriented web applications I'm looking for a python equivalent of ruby's halcyon - a framework focused on "web service"-type applications rather than html-page-oriented ones. Google brings up a lot of example code and experiments, but I couldn't find anything that people were u...
python web framework focusing on json-oriented web applications
I'm looking for a python equivalent of ruby's halcyon - a framework focused on "web service"-type applications rather than html-page-oriented ones. Google brings up a lot of example code and experiments, but I couldn't find anything that people were using in production and hammering on. Failing that, what is the best w...
[ "Based on you comment, it sounds like one of the microframeworks may be what you're looking for.\n", "Why not use django? You can return a json with it, so it's not a problem. At the same time, you get good, well-tested framework... \n" ]
[ 4, 3 ]
[]
[]
[ "json", "python", "web_applications", "web_services" ]
stackoverflow_0000955751_json_python_web_applications_web_services.txt
Q: Getting column info in cx_oracle when table is empty? I am working on an a handler for the python logging module. That essentially logs to an oracle database. I am using cx_oracle, and something i don't know how to get is the column values when the table is empty. cursor.execute('select * from FOO') for row in cu...
Getting column info in cx_oracle when table is empty?
I am working on an a handler for the python logging module. That essentially logs to an oracle database. I am using cx_oracle, and something i don't know how to get is the column values when the table is empty. cursor.execute('select * from FOO') for row in cursor: # this is never executed because cursor has no ro...
[ "I think the description attribute may be what you are looking for. This returns a list of tuples that describe the columns of the data returned. It works quite happily if there are no rows returned, for example:\n\n>>> import cx_Oracle\n>>> c = cx_Oracle.connect(\"username\", \"password\")\n>>> cr = c.cursor()\n...
[ 14 ]
[]
[]
[ "cx_oracle", "python" ]
stackoverflow_0000956085_cx_oracle_python.txt
Q: retrieving current drive letters in windows (from python) Possible Duplicate: Is there a way to list all the available drive letters in python? What's the way to retrieve currently mounted drive list in Windows incl. Thumb drives, and mapped networks. i currently do drives=[] for c in string.lowercase: ...
retrieving current drive letters in windows (from python)
Possible Duplicate: Is there a way to list all the available drive letters in python? What's the way to retrieve currently mounted drive list in Windows incl. Thumb drives, and mapped networks. i currently do drives=[] for c in string.lowercase: if os.path.isdir(c+':'): drives.append(c+'...
[ "win32api.GetLogicalDriveStrings().split(\"\\x00\")\n\n" ]
[ 3 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0000956971_python_windows.txt
Q: Clean Python Regular Expressions Is there a cleaner way to write long regex patterns in python? I saw this approach somewhere but regex in python doesn't allow lists. patterns = [ re.compile(r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'), re.compile(r'\n+|\s{2}') ] A: You can use verbose mode to write more reada...
Clean Python Regular Expressions
Is there a cleaner way to write long regex patterns in python? I saw this approach somewhere but regex in python doesn't allow lists. patterns = [ re.compile(r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'), re.compile(r'\n+|\s{2}') ]
[ "You can use verbose mode to write more readable regular expressions. In this mode:\n\nWhitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash.\nWhen a line contains a '#' neither in a character class or preceded by an unescaped backslash, all characters from...
[ 31, 13, 2 ]
[]
[]
[ "list", "python", "regex" ]
stackoverflow_0000958853_list_python_regex.txt
Q: pyExcelerator or xlrd - How to FIND/SEARCH a row for the given few column data? Python communicating with EXCEL... i need to find a way so that I can find/search a row for given column datas. Now, i m scanning entire rows one by one... It would be useful, If there is some functions like FIND/SEARCH/REPLACE .... I ...
pyExcelerator or xlrd - How to FIND/SEARCH a row for the given few column data?
Python communicating with EXCEL... i need to find a way so that I can find/search a row for given column datas. Now, i m scanning entire rows one by one... It would be useful, If there is some functions like FIND/SEARCH/REPLACE .... I dont see these features in pyExcelerator or xlrd modules.. I dont want to use win32co...
[ "@John Fouhy: [I'm the maintainer of xlwt, and author of xlrd]\nThe spreadsheet-reading part of pyExcelerator was so severely deprecated that it vanished completely out of xlwt. To read any XLS files created by Excel 2.0 up to 11.0 (Excel 2003) or compatible software, using Python 2.1+, use xlrd\nThat \"simple opti...
[ 6, 2, 2, 0 ]
[]
[]
[ "excel", "pyexcelerator", "python", "search", "xlrd" ]
stackoverflow_0000778093_excel_pyexcelerator_python_search_xlrd.txt
Q: PyQt and context menu I need to create a context menu on right clicking at my window. But I really don't know how to achieve that. Are there any widgets for that, or I have to create it from the beginning? Programming language: Python Graphical lib: Qt (PyQt) A: I can't speak for python, but it's fairly easy ...
PyQt and context menu
I need to create a context menu on right clicking at my window. But I really don't know how to achieve that. Are there any widgets for that, or I have to create it from the beginning? Programming language: Python Graphical lib: Qt (PyQt)
[ "I can't speak for python, but it's fairly easy in C++.\nfirst after creating the widget you set the policy:\nw->setContextMenuPolicy(Qt::CustomContextMenu);\n\nthen you connect the context menu event to a slot:\nconnect(w, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ctxMenu(const QPoint &)));\n\...
[ 42, 15 ]
[]
[]
[ "menu", "pyqt", "python", "qt" ]
stackoverflow_0000782255_menu_pyqt_python_qt.txt
Q: What are best practices for developing consistent libraries? I am working on developing a pair of libraries to work with a REST API. Because I need to be able to use the API in very different settings I'm currently planning to have a version in PHP (for web applications) and a second version in Python (for deskto...
What are best practices for developing consistent libraries?
I am working on developing a pair of libraries to work with a REST API. Because I need to be able to use the API in very different settings I'm currently planning to have a version in PHP (for web applications) and a second version in Python (for desktop applications, and long running processes). Are there any best p...
[ "So, the problem with developing parallel libraries in different languages is that often times different languages will have different idioms for the same task. I know this from personal experience, having ported a library from Python to PHP. Idioms aren't just naming: for example, Python has a good deal of magic y...
[ 6, 2, 2, 0, 0, 0 ]
[]
[]
[ "api", "php", "python", "rest" ]
stackoverflow_0000193701_api_php_python_rest.txt
Q: How can I determine if one PGArray is included in another using SQLAlchemy sessions? I have an SqlAlchemy table like so: table = sql.Table('treeItems', META, sql.Column('id', sql.Integer(), primary_key=True), sql.Column('type', sql.String, nullable=False), sql.Column('parentId', sql.Integer, sql.Foreig...
How can I determine if one PGArray is included in another using SQLAlchemy sessions?
I have an SqlAlchemy table like so: table = sql.Table('treeItems', META, sql.Column('id', sql.Integer(), primary_key=True), sql.Column('type', sql.String, nullable=False), sql.Column('parentId', sql.Integer, sql.ForeignKey('treeItems.id')), sql.Column('lineage', PGArray(sql.Integer)), sql.Column('de...
[ "SQLAlchemy's clause elements have an .op() method for custom operators. What isn't available is a special clause for array literals. You can specify the array literal with literal_column:\nprint sql.literal_column('ARRAY[2]').op('<@')(table.c.lineage)\n# ARRAY[2] <@ \"treeItems\".lineage\n\nIf you want a better AP...
[ 4, 0 ]
[]
[]
[ "arrays", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0000957762_arrays_postgresql_python_sqlalchemy.txt
Q: Find all possible factors in KenKen puzzle 'multiply' domain A KenKen puzzle is a Latin square divided into edge-connected domains: a single cell, two adjacent cells within the same row or column, three cells arranged in a row or in an ell, etc. Each domain has a label which gives a target number and a single ari...
Find all possible factors in KenKen puzzle 'multiply' domain
A KenKen puzzle is a Latin square divided into edge-connected domains: a single cell, two adjacent cells within the same row or column, three cells arranged in a row or in an ell, etc. Each domain has a label which gives a target number and a single arithmetic operation (+-*/) which is to be applied to the numbers in ...
[ "Simplified goal: you need to enumerate all integer combinations that multiply together to form a certain product, where the number of integers is fixed.\nTo solve this, all you need is a prime factorization of your target number, and then use a combinatorial approach to form all possible sub-products from these fa...
[ 5 ]
[]
[]
[ "algorithm", "partitioning", "prime_factoring", "python" ]
stackoverflow_0000958678_algorithm_partitioning_prime_factoring_python.txt
Q: Parsing numbers in Python i want to take inputs like this 10 12 13 14 15 16 .. how to take this input , as two diffrent integers so that i can multiply them in python after every 10 and 12 there is newline A: I'm not sure I understood your problem very well, it seems you want to parse two int separated from a...
Parsing numbers in Python
i want to take inputs like this 10 12 13 14 15 16 .. how to take this input , as two diffrent integers so that i can multiply them in python after every 10 and 12 there is newline
[ "I'm not sure I understood your problem very well, it seems you want to parse two int separated from a space.\nIn python you do:\ns = raw_input('Insert 2 integers separated by a space: ')\na,b = [int(i) for i in s.split(' ')]\nprint a*b\n\nExplanation:\ns = raw_input('Insert 2 integers separated by a space: ')\n\nr...
[ 7, 2, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0000959412_parsing_python.txt
Q: How to access the parent class during initialisation in python? How do I find out which class I am initialising a decorator in? It makes sense that I wouldn't be able to find this out as the decorator is not yet bound to the class, but is there a way of getting round this? class A(object): def dec(f): ...
How to access the parent class during initialisation in python?
How do I find out which class I am initialising a decorator in? It makes sense that I wouldn't be able to find this out as the decorator is not yet bound to the class, but is there a way of getting round this? class A(object): def dec(f): # I am in class 'A' def func(cls): f(cls)...
[ "I don't think this is possible. At the very moment when you define test, the class doesn't exist yet.\nWhen Python encounters\nclass A(object):\n\nit creates a new namespace in which it runs all code that it finds in the class definition (including the definition of test() and the call to the decorator), and when ...
[ 3, 0, 0 ]
[]
[]
[ "decorator", "introspection", "python" ]
stackoverflow_0000956994_decorator_introspection_python.txt
Q: My regex in python isn't recursing properly I'm suppose to capture everything inside a tag and the next lines after it, but it's suppose to stop the next time it meets a bracket. What am i doing wrong? import re #regex regex = re.compile(r""" ^ # Must start in a newline first ...
My regex in python isn't recursing properly
I'm suppose to capture everything inside a tag and the next lines after it, but it's suppose to stop the next time it meets a bracket. What am i doing wrong? import re #regex regex = re.compile(r""" ^ # Must start in a newline first \[\b(.*)\b\] # Get what's enclosed in bra...
[ "Python regex doesn't support recursion afaik.\nEDIT: but in your case this would work:\nregex = re.compile(r\"\"\"\n ^ # Must start in a newline first\n \\[(.*?)\\] # Get what's enclosed in brackets \n \\n # only capture bracket if a newline is next\n ([^\\[]*) ...
[ 3, 3, 2 ]
[]
[]
[ "python", "recursion", "regex" ]
stackoverflow_0000954989_python_recursion_regex.txt
Q: How to ensure xml.dom.minidom can parse its own output? I'm trying to serialize some data to xml in a way that can be read back. I'm doing this by manually building a DOM via xml.dom.minidom, and writing it to a file using the included writexml method. Of particular interest is how I build the text nodes. I do thi...
How to ensure xml.dom.minidom can parse its own output?
I'm trying to serialize some data to xml in a way that can be read back. I'm doing this by manually building a DOM via xml.dom.minidom, and writing it to a file using the included writexml method. Of particular interest is how I build the text nodes. I do this by initializing a Text object and then setting its data att...
[ "The issue you're encountering, as explained in Python's online docs, is that of Unicode encoding:\nNode.toxml([encoding])\nReturn the XML that the DOM represents as a string.\n\nWith no argument, the XML header does not specify an encoding, and the result is\nUnicode string if the default encoding cannot represent...
[ 3 ]
[]
[]
[ "dom", "escaping", "python", "xml" ]
stackoverflow_0000959782_dom_escaping_python_xml.txt
Q: chunk_split in python I'm trying to find a pythonic way to do this PHP code: chunk_split(base64_encode($picture)); http://us2.php.net/chunk_split chunk_split split the string into smaller chunks of 76 character long by adding a "\r\n" (RFC 2045). thank you A: chunk_split = lambda s: '\r\n'.join(s[i:min(i+76, l...
chunk_split in python
I'm trying to find a pythonic way to do this PHP code: chunk_split(base64_encode($picture)); http://us2.php.net/chunk_split chunk_split split the string into smaller chunks of 76 character long by adding a "\r\n" (RFC 2045). thank you
[ "chunk_split = lambda s: '\\r\\n'.join(s[i:min(i+76, len(s))] for i in xrange(0, len(s), 76))\n\n", "This should do it:\nstr.encode(\"base64\").replace(\"\\n\", \"\\r\\n\")\n\n" ]
[ 2, 2 ]
[]
[]
[ "php", "python" ]
stackoverflow_0000959780_php_python.txt
Q: Inferring appropriate database type declarations from strings in Python I am building some Postgres tables from Python dictionaries where the {'key': 'value'} pairs correspond to column 'key' and field 'value'. These are generated from .dbf files -- I now pipe the contents of the .dbf files into a script that retu...
Inferring appropriate database type declarations from strings in Python
I am building some Postgres tables from Python dictionaries where the {'key': 'value'} pairs correspond to column 'key' and field 'value'. These are generated from .dbf files -- I now pipe the contents of the .dbf files into a script that returns a list of dicts like: {'Warngentyp': '', 'Lon': '-81.67170', 'Zwatch_war'...
[ "Don't use eval. If someone inserts bad code, it can hose your database or server.\nInstead use these\ndef isFloat(s):\ntry:\n float(s)\n return True\nexcept (ValueError, TypeError), e:\n return False\n\n\nstr.isdigit()\n\nAnd everything else can be a varchar\n", "YOU DON'T NEED TO INFER THE TYPE DECLARA...
[ 5, 2, 1, 1 ]
[]
[]
[ "postgresql", "python", "sqlite", "types" ]
stackoverflow_0000952541_postgresql_python_sqlite_types.txt
Q: not able to start coding in python i want to code in python and i know the syntax well.. but i have got no idea how to compile and run it ..!! i mean i am from ruby , java , c , c++ background and there after saving it in a file we go to command prompt and type the command and the file name to compile and run it ....
not able to start coding in python
i want to code in python and i know the syntax well.. but i have got no idea how to compile and run it ..!! i mean i am from ruby , java , c , c++ background and there after saving it in a file we go to command prompt and type the command and the file name to compile and run it . then what about python ? why does pytho...
[ "If you're using Windows, you'll need to add the path to your Python executable to the Path environment variable; on Linux, and I presume Mac, this should already be done.\nOh, and you don't compile python programs, they are interpreted at run time.\n", "If you are from Ruby background, you should be able to hand...
[ 4, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000959168_python.txt
Q: Any graphics library for unix that can draw histograms? A python program needs to draw histograms. It's ok to use 3rd party library (free). What is the best way to do that? A: You can use matplotlib. A: Gnuplot.py lets you use Gnuplot from python. A: How much power do you need? How much external weight are ...
Any graphics library for unix that can draw histograms?
A python program needs to draw histograms. It's ok to use 3rd party library (free). What is the best way to do that?
[ "You can use matplotlib.\n", "Gnuplot.py lets you use Gnuplot from python. \n", "How much power do you need? How much external weight are you willing to take on? ROOT is accessible in python using PyROOT. Heavy and a lot to learn to get the most out of it, but very powerful.\n" ]
[ 9, 3, 1 ]
[]
[]
[ "graphics", "python", "unix" ]
stackoverflow_0000959702_graphics_python_unix.txt
Q: How do I use 'F' keys in gtk Accelerators? I'm trying (in python) to use gtk.Widget.add_accelerator... what should I pass as accel_key to use the F keys? Have attempted to check the docs to no avail. Thanks A: Consider using gtk.accelerator_parse(). Here is an informative post on dealing with keyboard codes in ...
How do I use 'F' keys in gtk Accelerators?
I'm trying (in python) to use gtk.Widget.add_accelerator... what should I pass as accel_key to use the F keys? Have attempted to check the docs to no avail. Thanks
[ "Consider using gtk.accelerator_parse(). Here is an informative post on dealing with keyboard codes in pygtk.\n", "Found it:\nkey,mods=gtk.accelerator_parse(\"F10\")\n\n" ]
[ 2, 1 ]
[]
[]
[ "accelerator", "gtk", "python" ]
stackoverflow_0000960269_accelerator_gtk_python.txt
Q: Python's file.read() on Ubuntu Python's file.read() function won't read anything. It always returns '' no matter what's inside the file. What can it be? I know it must be something straightforward, but I can't figure it out. UPD: I tried with 'r' and 'w+' modes. UPD: The code was: >>> file = open('helloworld',...
Python's file.read() on Ubuntu
Python's file.read() function won't read anything. It always returns '' no matter what's inside the file. What can it be? I know it must be something straightforward, but I can't figure it out. UPD: I tried with 'r' and 'w+' modes. UPD: The code was: >>> file = open('helloworld', 'w+') >>> file.read() '' S...
[ "Caveat: I'm just guessing as to behavior that is not 'working':\nIf you're working in the Python interpreter, \nand you do something like this:\n>>> f = open('myfile.txt', 'r')\n>>> f.read()\n\n...you'll get the whole file printed to the screen.\nBut if you do this again:\n>>> f.read()\n''\n\n...you get an empty ...
[ 2 ]
[]
[]
[ "file", "python", "ubuntu" ]
stackoverflow_0000960487_file_python_ubuntu.txt
Q: python3.0: imputils Why was the imputil module removed from python3.0 and what should be used in its place? A: In Python 3.1, there is a module called importlib, which should be a superior replacement for imputil. A: According to PEP 3108, it was rarely used, undocumented and never updated to support absolute ...
python3.0: imputils
Why was the imputil module removed from python3.0 and what should be used in its place?
[ "In Python 3.1, there is a module called importlib, which should be a superior replacement for imputil.\n", "According to PEP 3108, it was rarely used, undocumented and never updated to support absolute imports.\n" ]
[ 10, 9 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0000960646_python_python_3.x.txt
Q: PEP 302 Example: New Import Hooks Where can I find an example implementation of the "New Import Hooks" described in PEP 302? I would like to implement a custom finder and loader in the most forward compatible way possible. In other words, the implementation should work in python 2.x and 3.x. A: You can find tho...
PEP 302 Example: New Import Hooks
Where can I find an example implementation of the "New Import Hooks" described in PEP 302? I would like to implement a custom finder and loader in the most forward compatible way possible. In other words, the implementation should work in python 2.x and 3.x.
[ "You can find thousands of open-source examples e.g. with a google code search, here it is:\nhttp://www.google.com/codesearch?hl=en&lr=&q=\"imp.find_module\"+\"imp.load_module\"&sbtn=Search\n\nEdit: as the questioner clarified he's looking for example of implementation, not use, a better URL for the search is:\nhtt...
[ 3 ]
[]
[]
[ "http_status_code_302", "import_hooks", "python", "python_3.x" ]
stackoverflow_0000960832_http_status_code_302_import_hooks_python_python_3.x.txt
Q: how to multiply two different array of integers in python? i have taken input in two different lists by splitting a line having integers 1 2 for eg 1 2 3 4 so now i have split it and kept it in lists , and want to multiply them like 1*3 +2*4, but when i try to do it , its giving me that it can only multiply intege...
how to multiply two different array of integers in python?
i have taken input in two different lists by splitting a line having integers 1 2 for eg 1 2 3 4 so now i have split it and kept it in lists , and want to multiply them like 1*3 +2*4, but when i try to do it , its giving me that it can only multiply integers and not lists !! help here can't multiply sequence by non-in...
[ "You need:\n>>> a = [1,2]\n>>> b = [3,4]\n>>> sum(i*j for i, j in zip(a,b))\n11\n\n", "You can do it in a pythonic way using sum, map and a lambda expression. \n>>> a = [1,2]\n>>> b = [3,4]\n>>> prod = lambda a, b: a*b\n>>> sum(map(prod, a, b))\n11\n\nthe lambda a, b: a*b bit also has a special name in python, op...
[ 8, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000961326_python.txt
Q: Identical Error Codes I use python 2.4.1 on Linux, and a python package written inside the company I work in, for establishing a connection between 2 hosts for test purposes. Upon establishing the connection the side defined as the client side failed when calling socket.connect with the correct parameters (I check...
Identical Error Codes
I use python 2.4.1 on Linux, and a python package written inside the company I work in, for establishing a connection between 2 hosts for test purposes. Upon establishing the connection the side defined as the client side failed when calling socket.connect with the correct parameters (I checked) with the error code 111...
[ "It appears Python is exposing the error code from the OS - the interpretation of the code is OS-dependent.\n111 is ECONNREFUSED on many Linux systems, and on Cygwin.\n146 is ECONNREFUSED on Solaris.\n10061 is WSAECONNREFUSED in winerror.h - it's the Windows Socket API's version of ECONNREFUSED.\nNo doubt on other ...
[ 6 ]
[]
[]
[ "error_handling", "python", "sockets" ]
stackoverflow_0000961465_error_handling_python_sockets.txt
Q: Python3 Http Web Server: virtual hosts I am writing an rather simple http web server in python3. The web server needs to be simple - only basic reading from config files, etc. I am using only standard libraries and for now it works rather ok. There is only one requirement for this project, which I can't implement...
Python3 Http Web Server: virtual hosts
I am writing an rather simple http web server in python3. The web server needs to be simple - only basic reading from config files, etc. I am using only standard libraries and for now it works rather ok. There is only one requirement for this project, which I can't implement on my own - virtual hosts. I need to have a...
[ "Virtual hosts work by obeying the Host: header in the HTTP request.\nJust read the headers of the request, and take action based on the value of the Host: header\n", "For a simple HTTP web server, you can start with the WSGI reference implementation:\n\nwsgiref is a reference implementation of the WSGI specifica...
[ 10, 5 ]
[]
[]
[ "http", "python", "python_3.x", "virtualhost" ]
stackoverflow_0000781466_http_python_python_3.x_virtualhost.txt
Q: Python function calls are bleeding scope, stateful, failing to initialize parameters? Before I have the audacity to file a bug report, I thought I'd check my assumptions among wiser Pythonistas here. I encountered a baffling case today, so I whittled it down to a toy example, shown below: #!/usr/bin/env python # -...
Python function calls are bleeding scope, stateful, failing to initialize parameters?
Before I have the audacity to file a bug report, I thought I'd check my assumptions among wiser Pythonistas here. I encountered a baffling case today, so I whittled it down to a toy example, shown below: #!/usr/bin/env python # -*- coding: UTF-8 -*- """ A little script to demonstrate that a function won't re-initializ...
[ "In Python default parameter values only get initialized when the def call is parsed. In the case of an object (such as your lists), it gets reused between calls. Take a look at this article about it, which also provides the necessary workaround:\nhttp://effbot.org/zone/default-values.htm\n", "This is your proble...
[ 15, 8, 5, 1 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0000959113_python_scope.txt
Q: How to enumerate a list of non-string objects in Python? There is a nice class Enum from enum, but it only works for strings. I'm currently using: for index in range(len(objects)): # do something with index and objects[index] I guess it's not the optimal solution due to the premature use of len. How i...
How to enumerate a list of non-string objects in Python?
There is a nice class Enum from enum, but it only works for strings. I'm currently using: for index in range(len(objects)): # do something with index and objects[index] I guess it's not the optimal solution due to the premature use of len. How is it possible to do it more efficiently?
[ "Here is the pythonic way to write this loop:\nfor index, obj in enumerate(objects):\n # Use index, obj.\n\nenumerate works on any sequence regardless of the types of its elements. It is a builtin function.\nEdit:\nAfter running some timeit tests using Python 2.5, I found enumerate to be slightly slower:\n>>> time...
[ 13 ]
[]
[]
[ "enumeration", "loops", "python", "sequence" ]
stackoverflow_0000962082_enumeration_loops_python_sequence.txt
Q: Making a plain ASCII/UTF-8 request/stream HTTP POST request in Python? I'm reading some documentation on a service I'm trying to use, and it reads something like this: All requests must be sent using HTTP Post. The XML engine only accepts plain ASCII (text) UTF-8 requests/streams. Encoded streams are not accept...
Making a plain ASCII/UTF-8 request/stream HTTP POST request in Python?
I'm reading some documentation on a service I'm trying to use, and it reads something like this: All requests must be sent using HTTP Post. The XML engine only accepts plain ASCII (text) UTF-8 requests/streams. Encoded streams are not acceptable. All requests/responses are XML. But I really just don't understand wh...
[ "using urllib2.Request\nimport urllib2\nreq = urllib2.Request(\"http://foo.com/post_here\", \"<xml data to post>\")\nresponse = urllib2.urlopen(req)\nthe_page = response.read()\n\n", "\"plain ASCII UTF-8\" is a contradiction in terms, IMHO -- ASCII is a subset of UTF-8, though. Try sending UTF-8 including some \"...
[ 2, 1 ]
[]
[]
[ "http", "python" ]
stackoverflow_0000962179_http_python.txt
Q: Different behavior of python logging module when using mod_python We have a nasty problem where we see that the python logging module is behaving differently when running with mod_python on our servers. When executing the same code in the shell, or in django with the runserver command or with mod_wsgi, the behavio...
Different behavior of python logging module when using mod_python
We have a nasty problem where we see that the python logging module is behaving differently when running with mod_python on our servers. When executing the same code in the shell, or in django with the runserver command or with mod_wsgi, the behavior is correct: import logging logger = logging.getLogger('site-errors') ...
[ "It may be better if you do not configure logging in settings.py.\nWe configure your logging in our root urls.py. This seems to work out better. I haven't read enough Django source to know why, precisely, it's better, but it's working out well for us. I would add custom handlers here, also. \nAlso, look closely...
[ 5, 0, 0 ]
[]
[]
[ "django", "logging", "mod_python", "python" ]
stackoverflow_0000919990_django_logging_mod_python_python.txt
Q: How can I speed up a web-application? (Avoid rebuilding a structure.) After having successfully build a static data structure (see here), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pickle) into a ...
How can I speed up a web-application? (Avoid rebuilding a structure.)
After having successfully build a static data structure (see here), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pickle) into a file and load this file for each query. Needless to say (as I figured out),...
[ "You can dump it in a memory cache (such as memcached).\nThis method has the advantage of cache key invalidation. When underlying data changes you can invalidate your cached data.\nEDIT\nHere's the python implementation of memcached: python-memcached. Thanks NicDumZ.\n", "If you can rebuild your Python runtime wi...
[ 4, 3, 2, 2 ]
[]
[]
[ "apache", "pickle", "python", "web_applications" ]
stackoverflow_0000961981_apache_pickle_python_web_applications.txt
Q: Bazaar: Modify file content before commit via hook? I'm switching from SVN to Bzr for my private projects. There is one feature missing for me, which SVN provides: The replacement of a $Id:$ placeholder with the latest version identification. So far, Bzr provides hooks to do some tricks within the commit process. ...
Bazaar: Modify file content before commit via hook?
I'm switching from SVN to Bzr for my private projects. There is one feature missing for me, which SVN provides: The replacement of a $Id:$ placeholder with the latest version identification. So far, Bzr provides hooks to do some tricks within the commit process. I've managed to get a list of modified files an manipulat...
[ "Use this extension: http://launchpad.net/bzr-keywords\n" ]
[ 3 ]
[]
[]
[ "bazaar", "bazaar_plugins", "python" ]
stackoverflow_0000962228_bazaar_bazaar_plugins_python.txt
Q: How to call up attributes in python 3.1 -- easy Python 2.5 all you needed to do was type "dir(filename)" and that pulls up the attributes. What is the command in 3.1? A: Just dir(whateverobject). Example: Python 3.1rc1 (r31rc1:73141, Jun 2 2009, 12:50:02) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "he...
How to call up attributes in python 3.1 -- easy
Python 2.5 all you needed to do was type "dir(filename)" and that pulls up the attributes. What is the command in 3.1?
[ "Just dir(whateverobject). Example:\nPython 3.1rc1 (r31rc1:73141, Jun 2 2009, 12:50:02) \n[GCC 4.0.1 (Apple Inc. build 5493)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> x=23\n>>> dir(x)\n['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__d...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0000962877_python.txt
Q: Python Generator - what not to use it for Just looking at Python generators, real impressed with them, but are there any things not to use them for? I was thinking of past C coding where reading from a file, or user actions would be areas. For example, could the generator be used to prompt the user for input (ba...
Python Generator - what not to use it for
Just looking at Python generators, real impressed with them, but are there any things not to use them for? I was thinking of past C coding where reading from a file, or user actions would be areas. For example, could the generator be used to prompt the user for input (base data entry?) and the calling function proces...
[ "Generators don't persist well.\nGenerally, you get an error trying to persist a generator object.\n>>> def generatorForEvenKeys( aDictionary ):\n for k in aDictionary:\n if k % 2 == 0: yield aDictionary[k]\n\n>>> x = generatorForEvenKeys( someDictionary )\n>>> pickle.dump(x,file('temp.dat','wb'))\n\nGets...
[ 13, 12, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000961848_python.txt
Q: Django EmailMultiAlternatives and HTML e-mail display in Outlook 2003 on Win2003 I'm using django.core.mail.EmailMultiAlternatives when sending e-mails from my django app in an attempt to make sure that the message downgrades to text if the e-mail client doesn't support HTML. Here is my send_email method: def send...
Django EmailMultiAlternatives and HTML e-mail display in Outlook 2003 on Win2003
I'm using django.core.mail.EmailMultiAlternatives when sending e-mails from my django app in an attempt to make sure that the message downgrades to text if the e-mail client doesn't support HTML. Here is my send_email method: def send_email(self, from_address, to_list, subject, msg_text, msg_html): subject=subj...
[ "I don't have an Outlook installation available to test this, so I'm wondering about the reason for the fifth line in your function.\nself.msg.content_subtype = \"html\"\nI don't know much about multipart email internals, but on my system that line causes both parts of the message have a content-type of text/html. ...
[ 5 ]
[]
[]
[ "django", "email", "html", "python" ]
stackoverflow_0000959985_django_email_html_python.txt
Q: HTML tags within JSON (in Python) I understand its not a desirable circumstance, however if I NEEDED to have some kind of HTML within JSON tags, e.g.: { "node": { "list":"<ul><li class="lists">Hello World</li><ul>" } } is this possible to do in Python without requiring to to be escaped beforeh...
HTML tags within JSON (in Python)
I understand its not a desirable circumstance, however if I NEEDED to have some kind of HTML within JSON tags, e.g.: { "node": { "list":"<ul><li class="lists">Hello World</li><ul>" } } is this possible to do in Python without requiring to to be escaped beforehand? It will be a string initially so ...
[ "Well, depending on how varied your HTML is, you can use single quotes in HTML fine, so you could do:\n{\n \"node\":\n {\n \"list\": \"<ul><li class='lists'>Hello World</li><ul>\"\n }\n}\n\nHowever, with simplejson, which is built into Python 2.6 as the json module, it does any escaping you need aut...
[ 7, 1 ]
[]
[]
[ "escaping", "json", "markup", "python" ]
stackoverflow_0000963448_escaping_json_markup_python.txt
Q: Tab view in CSS with tables I need a tab view in CSS with each tab showing a dynamic table. The complete table is dynamically constructed in loop and only after that should the tabs should hide and show each of the table corresponding to each tab. Any suggestions? The content of the tab is within list item and in ...
Tab view in CSS with tables
I need a tab view in CSS with each tab showing a dynamic table. The complete table is dynamically constructed in loop and only after that should the tabs should hide and show each of the table corresponding to each tab. Any suggestions? The content of the tab is within list item and in loop only. The development is in ...
[ "Check out jQuery UI Tabs; this will do what you're looking for. It's not possible to do this using pure CSS.\n", "Just of the top of my head, check out what some of the Javascript toolkits have to offer. Things like jQuery with a few plugins or Dojo might have something like that in its Dijit library.\n" ]
[ 1, 0 ]
[]
[]
[ "css", "css_tables", "html", "python", "tabs" ]
stackoverflow_0000963506_css_css_tables_html_python_tabs.txt
Q: How can I instantiate a comment element programatically using lxml? I'm using lxml to programatically build HTML and I need to include a custom comment in the output. Whilst there is code in lxml to cope with comments (they can be instantiated when parsing existing HTML code) I cannot find a way to instantiate on...
How can I instantiate a comment element programatically using lxml?
I'm using lxml to programatically build HTML and I need to include a custom comment in the output. Whilst there is code in lxml to cope with comments (they can be instantiated when parsing existing HTML code) I cannot find a way to instantiate one programatically. Can anyone help?
[ "You can use the lxml.etree.Comment() factory function. It will return a comment element that you can use like any other element.\n" ]
[ 6 ]
[]
[]
[ "html", "lxml", "python", "xml" ]
stackoverflow_0000963621_html_lxml_python_xml.txt
Q: AJAX console window with ANSI/VT100 support? I'm planning to write gateway web application, which would need "terminal window" with VT100/ANSI escape code support. Are there any AJAX based alternatives for such a task? I'm thinking something like this: http://tryruby.hobix.com/ My preferred backend for the system ...
AJAX console window with ANSI/VT100 support?
I'm planning to write gateway web application, which would need "terminal window" with VT100/ANSI escape code support. Are there any AJAX based alternatives for such a task? I'm thinking something like this: http://tryruby.hobix.com/ My preferred backend for the system is Python/Twisted/Pylons, but since I'm just plann...
[ "Try\nAnyTerm\nAjaxTerm\nWebShell\n", "There's also Shell In A Box.\n", "AjaxTerm has a terminal, with mostly felicitous terminal emulation, done on the Python backend (it just pushes display updates to the client Javascript).\nThe AjaxTerm website has been down for some time, but you can still find it packaged...
[ 9, 7, 3 ]
[]
[]
[ "ajax", "python", "vt100" ]
stackoverflow_0000244750_ajax_python_vt100.txt
Q: Django models: how to return a default value in case of a non-existing foreign-key relationship? I am developing a vocabulary training program with Django (German-Swedish). The app's vocabulary data consists of a large number of "vocabulary cards", each of which contains one or more German words or terms that cor...
Django models: how to return a default value in case of a non-existing foreign-key relationship?
I am developing a vocabulary training program with Django (German-Swedish). The app's vocabulary data consists of a large number of "vocabulary cards", each of which contains one or more German words or terms that correspond to one or more Swedish terms. Training is only available for registered users, because the app...
[ "This is what methods (and perhaps properties) are for.\nclass OptionalFKWithDefault( models.Model ):\n another = models.ForeignKey( AnotherModel, blank=True, null=True )\n @property\n def another_score( self ):\n if self.another is None:\n return 0\n else:\n return self...
[ 2, 1 ]
[]
[]
[ "aggregation", "django_models", "python" ]
stackoverflow_0000955815_aggregation_django_models_python.txt
Q: Zipping dynamic files in App Engine (Python) Is there anyway I can zip dynamically generated content, such as a freshly rendered html template, into a zip file using zipfile? There seem to be some examples around for zipping static content, but none for zipping dynamic ones. Or, is it not possible at all? One more...
Zipping dynamic files in App Engine (Python)
Is there anyway I can zip dynamically generated content, such as a freshly rendered html template, into a zip file using zipfile? There seem to be some examples around for zipping static content, but none for zipping dynamic ones. Or, is it not possible at all? One more question: Is it possible to create a zip file wit...
[ "The working code: (for app engine:)\noutput = StringIO.StringIO()\nz = zipfile.ZipFile(output,'w')\nmy_data = \"<html><body><p>Hello, world!</p></body></html>\"\nz.writestr(\"hello.html\", my_data)\nz.close()\n\nself.response.headers[\"Content-Type\"] = \"multipart/x-zip\"\nself.response.headers['Content-Dispositi...
[ 14, 7, 3 ]
[]
[]
[ "google_app_engine", "python", "zip" ]
stackoverflow_0000963800_google_app_engine_python_zip.txt
Q: Patching classes in Python Suppose I have a Python class that I want to add an extra property to. Is there any difference between import path.MyClass MyClass.foo = bar and using something like : import path.MyClass setattr(MyClass, 'foo', bar) ? If not, why do people seem to do the second rather than the first?...
Patching classes in Python
Suppose I have a Python class that I want to add an extra property to. Is there any difference between import path.MyClass MyClass.foo = bar and using something like : import path.MyClass setattr(MyClass, 'foo', bar) ? If not, why do people seem to do the second rather than the first? (Eg. here http://concisionandco...
[ "The statements are equivalent, but setattr might be used because it's the most dynamic choice of the two (with setattr you can use a variable for the attribute name.)\nSee: http://docs.python.org/library/functions.html#setattr\n" ]
[ 11 ]
[]
[]
[ "class", "monkeypatching", "python" ]
stackoverflow_0000964532_class_monkeypatching_python.txt
Q: Find a HAL object based on /dev node path I'm using python-dbus to interface with HAL, and I need to find a device's UDI based on it's path in the /dev hierarchy. So given a path such as /dev/sdb, I want to get a value back like /org/freedesktop/Hal/devices/usb_device_10. A: Pure python solution: import dbus bus...
Find a HAL object based on /dev node path
I'm using python-dbus to interface with HAL, and I need to find a device's UDI based on it's path in the /dev hierarchy. So given a path such as /dev/sdb, I want to get a value back like /org/freedesktop/Hal/devices/usb_device_10.
[ "Pure python solution:\nimport dbus\nbus = dbus.SystemBus()\nobj = bus.get_object(\"org.freedesktop.Hal\", \"/org/freedesktop/Hal/Manager\")\niface = dbus.Interface(obj, \"org.freedesktop.Hal.Manager\")\nprint iface.FindDeviceStringMatch(\"block.device\", \"/dev/sda\")\n\n", "I would spawn a hal-find-by-property ...
[ 3, 1 ]
[]
[]
[ "dbus", "hal", "python" ]
stackoverflow_0000964801_dbus_hal_python.txt
Q: Python: Reading part of a text file HI all I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: <word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/> I need the form, lemma and postag information. e.g. for above I...
Python: Reading part of a text file
HI all I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: <word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/> I need the form, lemma and postag information. e.g. for above I need hibernis, hibernus1 and n-p---nb-. ...
[ "If it's XML, use ElementTree to parse it:\nfrom xml.etree import ElementTree\n\nline = '<word id=\"8\" form=\"hibernis\" lemma=\"hibernus1\" postag=\"n-p---nb-\" head=\"7\" relation=\"ADV\"/>'\n\nelement = ElementTree.fromstring(line)\n\nFor each XML element you can easily extract the name and all the attributes:\...
[ 5, 2, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000964993_python.txt
Q: Python - simple reading lines from a pipe I'm trying to read lines from a pipe and process them, but I'm doing something silly and I can't figure out what. The producer is going to keep producing lines indefinitely, like this: producer.py import time while True: print 'Data' time.sleep(1) The consumer ju...
Python - simple reading lines from a pipe
I'm trying to read lines from a pipe and process them, but I'm doing something silly and I can't figure out what. The producer is going to keep producing lines indefinitely, like this: producer.py import time while True: print 'Data' time.sleep(1) The consumer just needs to check for lines periodically: consu...
[ "Some old versions of Windows simulated pipes through files (so they were prone to such problems), but that hasn't been a problem in 10+ years. Try adding a\n sys.stdout.flush()\n\nto the producer after the print, and also try to make the producer's stdout unbuffered (by using python -u).\nOf course this doesn't ...
[ 15, 7 ]
[]
[]
[ "pipe", "producer_consumer", "python" ]
stackoverflow_0000965210_pipe_producer_consumer_python.txt
Q: Python App Engine projects with sophisticated user-role-permission structures In followup to an earlier question, I'd be interested to know whether anyone can recommend some open-source Python-based Google App Engine projects with complex user-role-permission models to consult as a reference. A link to the code w...
Python App Engine projects with sophisticated user-role-permission structures
In followup to an earlier question, I'd be interested to know whether anyone can recommend some open-source Python-based Google App Engine projects with complex user-role-permission models to consult as a reference. A link to the code would be nice. In my own project, I'd like to add a layer of organizations in additi...
[ "App-Engine-Patch ports the django permission model over to AppEngine. Scroll down to the Permissions section of this page: http://code.google.com/p/app-engine-patch/wiki/GettingStarted. The source code is available from that site as well.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python", "roles" ]
stackoverflow_0000960125_google_app_engine_python_roles.txt
Q: Nokia N95 and PyS60 with the sensor and xprofile modules I've made a python script which should modify the profile of the phone based on the phone position. Runned under ScriptShell it works great. The problem is that it hangs, both with the "sis" script runned upon "boot up", as well as without it. So my question...
Nokia N95 and PyS60 with the sensor and xprofile modules
I've made a python script which should modify the profile of the phone based on the phone position. Runned under ScriptShell it works great. The problem is that it hangs, both with the "sis" script runned upon "boot up", as well as without it. So my question is what is wrong with the code, and also whether I need to pa...
[ "I often use something like that at the top of my scripts:\nimport os.path, sys\nPY_PATH = None\nfor p in ['c:\\\\Data\\\\Python', 'e:\\\\Data\\\\Python','c:\\\\Python','e:\\\\Python']:\n if os.path.exists(p): \n PY_PATH = p\n break\nif PY_PATH and PY_PATH not in sys.path: sys.path.append(PY_PATH)\...
[ 3, 2 ]
[]
[]
[ "nokia", "pys60", "python", "s60", "symbian" ]
stackoverflow_0000927150_nokia_pys60_python_s60_symbian.txt
Q: how to remove text between using python? how to remove text between <script> and </script> using python? A: You can use BeautifulSoup with this (and other) methods: soup = BeautifulSoup(source.lower()) to_extract = soup.findAll('script') for item in to_extract: item.extract() This actually removes the node...
how to remove text between using python?
how to remove text between <script> and </script> using python?
[ "You can use BeautifulSoup with this (and other) methods:\nsoup = BeautifulSoup(source.lower())\nto_extract = soup.findAll('script')\nfor item in to_extract:\n item.extract()\n\nThis actually removes the nodes from the HTML. If you wanted to leave the empty <script></script> tags you'll have to work with the it...
[ 27, 6, 1, 0, 0, 0, 0 ]
[ "I don't know Python good enough to tell you a solution. But if you want to use that to sanitize the user input you have to be very, very careful. Removing stuff between and just doesn't catch everything. Maybe you can have a look at existing solutions (I assume Django includes something like this).\n", "exampl...
[ -1, -1 ]
[ "javascript", "python" ]
stackoverflow_0000964459_javascript_python.txt
Q: Can't seem to get list() working I am trying to convert a set object to list...for example "p=list('abc')" is not working. any ideas or is it inherent in appengine A: A set object to list is converted like so: my_list = list(my_set) I don't understand your example though. Converting a string to a list results i...
Can't seem to get list() working
I am trying to convert a set object to list...for example "p=list('abc')" is not working. any ideas or is it inherent in appengine
[ "A set object to list is converted like so:\nmy_list = list(my_set)\n\nI don't understand your example though. Converting a string to a list results in a list of characters:\n>>> list('abc')\n['a', 'b', 'c']\n\n", "if the list() command is not working for you, you could work around it like this:\nmy_list = []\nfo...
[ 1, 0, 0 ]
[]
[]
[ "django", "google_app_engine", "list", "python" ]
stackoverflow_0000963932_django_google_app_engine_list_python.txt
Q: Serializing a Python object to/from a S60 phone I'm looking for a way to serialize generic Python objects between a CherryPy-based server and a Python client running on a Symbian phone.. Since pyS60 doesn't implement the pickle module, how would you do it? I know about Cerealizer but it requires you to register cl...
Serializing a Python object to/from a S60 phone
I'm looking for a way to serialize generic Python objects between a CherryPy-based server and a Python client running on a Symbian phone.. Since pyS60 doesn't implement the pickle module, how would you do it? I know about Cerealizer but it requires you to register classes before use (which I'd like to avoid) and doesn'...
[ "What's wrong with using the pickle module?\n", "There is a json module someone wrote for PyS60. I'd simply grab that, serialize things into json and use that as the transfer method between the web/client app. \nFor the json lib and a decent book on PyS60:\nhttp://www.mobilepythonbook.org/\n", "The last version...
[ 2, 1, 1 ]
[]
[]
[ "pickle", "pys60", "python", "serialization" ]
stackoverflow_0000362484_pickle_pys60_python_serialization.txt
Q: How do I infer the class to which a @staticmethod belongs? I am trying to implement infer_class function that, given a method, figures out the class to which the method belongs. So far I have something like this: import inspect def infer_class(f): if inspect.ismethod(f): return f.im_self if f.im_class...
How do I infer the class to which a @staticmethod belongs?
I am trying to implement infer_class function that, given a method, figures out the class to which the method belongs. So far I have something like this: import inspect def infer_class(f): if inspect.ismethod(f): return f.im_self if f.im_class == type else f.im_class # elif ... what about staticmethod-...
[ "That's because staticmethods really aren't methods. The staticmethod descriptor returns the original function as is. There is no way to get the class via which the function was accessed. But there is no real reason to use staticmethods for methods anyway, always use classmethods.\nThe only use that I have found fo...
[ 3, 3 ]
[]
[]
[ "decorator", "inspect", "python", "static_methods" ]
stackoverflow_0000949259_decorator_inspect_python_static_methods.txt
Q: Django : Adding a property to the User class. Changing it at runtime and UserManager.create_user For various complicated reasons[1] I need to add extra properties to the Django User class. I can't use either Profile nor the "inheritance" way of doing this. (As in Extending the User model with custom fields in Djan...
Django : Adding a property to the User class. Changing it at runtime and UserManager.create_user
For various complicated reasons[1] I need to add extra properties to the Django User class. I can't use either Profile nor the "inheritance" way of doing this. (As in Extending the User model with custom fields in Django ) So what I've been doing is including the User class in my local_settings file. And adding the pro...
[ "The usual way of the having site-specific user fields is to specify a user profile table in your settings.py. You can then retrieve the specific settings via a the u.user_profile() method. It's very well documented in the docs.\n", "You probably just need to make sure that you do the replacement/addition/monkey ...
[ 2, 2, 2 ]
[]
[]
[ "django", "django_authentication", "patch", "python" ]
stackoverflow_0000964569_django_django_authentication_patch_python.txt
Q: Python error: IndexError: list assignment index out of range a=[] a.append(3) a.append(7) for j in range(2,23480): a[j]=a[j-2]+(j+2)*(j+3)/2 When I write this code, it gives an error like this: Traceback (most recent call last): File "C:/Python26/tcount2.py", line 6, in <module> a[j]=a[j-2]+(j+2)*(j+3)...
Python error: IndexError: list assignment index out of range
a=[] a.append(3) a.append(7) for j in range(2,23480): a[j]=a[j-2]+(j+2)*(j+3)/2 When I write this code, it gives an error like this: Traceback (most recent call last): File "C:/Python26/tcount2.py", line 6, in <module> a[j]=a[j-2]+(j+2)*(j+3)/2 IndexError: list assignment index out of range May I know why ...
[ "Change this line of code:\na[j]=a[j-2]+(j+2)*(j+3)/2\n\nto this:\na.append(a[j-2] + (j+2)*(j+3)/2)\n\n", "You're adding new elements, elements that do not exist yet. Hence you need to use append: since the items do not exist yet, you cannot reference them by index. Overview of operations on mutable sequence type...
[ 7, 6, 3, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000966983_python.txt
Q: Unicode Problem with SQLAlchemy I know I'm having a problem with a conversion from Unicode but I'm not sure where it's happening. I'm extracting data about a recent Eruopean trip from a directory of HTML files. Some of the location names have non-ASCII characters (such as é, ô, ü). I'm getting the data from a st...
Unicode Problem with SQLAlchemy
I know I'm having a problem with a conversion from Unicode but I'm not sure where it's happening. I'm extracting data about a recent Eruopean trip from a directory of HTML files. Some of the location names have non-ASCII characters (such as é, ô, ü). I'm getting the data from a string representation of the the file u...
[ "I found this article that helped explain my troubles somewhat:\nhttp://www.amk.ca/python/howto/unicode#reading-and-writing-unicode-data\nI was able to get the desired results by using the 'codecs' module and then changing my program as follows:\nWhen opening the file:\ninfile = codecs.open(filename, 'r', encoding=...
[ 11, 7, 7 ]
[]
[]
[ "character_encoding", "encoding", "python", "sqlalchemy", "unicode" ]
stackoverflow_0000966352_character_encoding_encoding_python_sqlalchemy_unicode.txt
Q: Debug variable in Python I want to separate the debug outputs from production ones by defining a variable that can be used throughput the module. It cannot be defined in environment. Any suggestions for globals reused across classes in modules? Additionally is there a way to configure this variable flag for telli...
Debug variable in Python
I want to separate the debug outputs from production ones by defining a variable that can be used throughput the module. It cannot be defined in environment. Any suggestions for globals reused across classes in modules? Additionally is there a way to configure this variable flag for telling App Engine that dont use th...
[ "Have a look at the logging module, which is fully supported by Google App Engine. You can specify logging levels such as debug, warning, error, etc. They will show up in the dev server console, and will also be stored in the request log.\nIf you're after executing specific code only when running the dev server, yo...
[ 12, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000966571_google_app_engine_python.txt
Q: How do cursors work in Python's DB-API? I have been using python with RDBMS' (MySQL and PostgreSQL), and I have noticed that I really do not understand how to use a cursor. Usually, one have his script connect to the DB via a client DB-API (like psycopg2 or MySQLdb): connection = psycopg2.connect(host='otherhost',...
How do cursors work in Python's DB-API?
I have been using python with RDBMS' (MySQL and PostgreSQL), and I have noticed that I really do not understand how to use a cursor. Usually, one have his script connect to the DB via a client DB-API (like psycopg2 or MySQLdb): connection = psycopg2.connect(host='otherhost', etc) And then one creates a cursor: cursor ...
[ "ya, i know it's months old :P\nDB-API's cursor appears to be closely modeled after SQL cursors. AFA resource(rows) management is concerned, DB-API does not specify whether the client must retrieve all the rows or DECLARE an actual SQL cursor. As long as the fetchXXX interfaces do what they're supposed to, DB-API i...
[ 8, 2, 1 ]
[]
[]
[ "cursors", "performance", "psycopg2", "python", "rdbms" ]
stackoverflow_0000454337_cursors_performance_psycopg2_python_rdbms.txt
Q: Level control of Select inputs using Django Forms API I'm wanting to add a label= attribute to an option element of a Select form input using the Django Forms API without overwriting the Select widget's render_options method. Is this possible, if so, how? Note: I'm wanting to add a label directly to the option (...
Level control of Select inputs using Django Forms API
I'm wanting to add a label= attribute to an option element of a Select form input using the Django Forms API without overwriting the Select widget's render_options method. Is this possible, if so, how? Note: I'm wanting to add a label directly to the option (this is valid in the XHTML Strict standard) not an optgroup....
[ "I just wrote a class to do that:\nfrom django.forms.widgets import Select\nfrom django.utils.encoding import force_unicode\nfrom itertools import chain\nfrom django.utils.html import escape, conditional_escape\n\n\nclass ExtendedSelect(Select):\n \"\"\"\n A subclass of Select that adds the possibility to def...
[ 2, 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000965082_django_django_forms_python.txt
Q: Image distortion after sending through a WSGI app in Python A lot of the time when I send image data over WSGI (using wsgiref), the image comes out distorted. As an example, examine the following: (source: evanfosmark.com) A: As you haven't posted the code, here is a simple code which correctly works with pyth...
Image distortion after sending through a WSGI app in Python
A lot of the time when I send image data over WSGI (using wsgiref), the image comes out distorted. As an example, examine the following: (source: evanfosmark.com)
[ "As you haven't posted the code, here is a simple code which correctly works\nwith python 2.5 on windows\nfrom wsgiref.simple_server import make_server\n\ndef serveImage(environ, start_response):\n status = '200 OK'\n headers = [('Content-type', 'image/png')]\n start_response(status, headers)\n\n return...
[ 3, 1, 0 ]
[]
[]
[ "python", "wsgi" ]
stackoverflow_0000967826_python_wsgi.txt
Q: installing python libraries Ok, so i've downloaded the following library: http://www.lag.net/paramiko/ and i can't seem to figure out how to install on my local machine: Mac OS X 10.4.11 A: To use the package that you got from the web-site: "python setup.py install " My advice is to use easy_install instead of d...
installing python libraries
Ok, so i've downloaded the following library: http://www.lag.net/paramiko/ and i can't seem to figure out how to install on my local machine: Mac OS X 10.4.11
[ "To use the package that you got from the web-site: \"python setup.py install\n\"\nMy advice is to use easy_install instead of downloading packages straight from the project web-site.\nTo do this, you must first install setuptools.\nThen just use the command \"easy_install paramiko\".\nAs you use lots of different ...
[ 6 ]
[]
[]
[ "package_management", "python" ]
stackoverflow_0000968116_package_management_python.txt
Q: Python Advice for a beginner. Regex, Dictionaries etc? I'm writing my second python script to try and parse the contents of a config file and would like some noob advice. I'm not sure if its best to use regex to parse my script since its multiple lines? I've also been reading about dictionaries and wondered if thi...
Python Advice for a beginner. Regex, Dictionaries etc?
I'm writing my second python script to try and parse the contents of a config file and would like some noob advice. I'm not sure if its best to use regex to parse my script since its multiple lines? I've also been reading about dictionaries and wondered if this would be good practice. I'm not necessarily looking for th...
[ "If you can change the configuration file format, you can directly write your file as a Python file.\nconfig.py\njob = {\n 'Name' : \"host.domain.com-foo\",\n 'Client' : \"host.domain.com-fd\",\n 'JobDefs' : \"DefaultJob\",\n 'FileSet' : \"local\",\n 'Write Bootstrap' : \"/etc/foo/host.domain.com-foo.bsr\",\n ...
[ 8, 5, 5, 4, 2 ]
[]
[]
[ "configuration_files", "dictionary", "python", "regex" ]
stackoverflow_0000968018_configuration_files_dictionary_python_regex.txt
Q: How do we precompile base templates in Cheetah so that #include, #extends and #import works properly in Weby How do you serve Cheetah in production? Guys can you share the setup on how to precompile and serve cheetah in production Since we dont compile templates in webpy it is getting upstream time out errors. If ...
How do we precompile base templates in Cheetah so that #include, #extends and #import works properly in Weby
How do you serve Cheetah in production? Guys can you share the setup on how to precompile and serve cheetah in production Since we dont compile templates in webpy it is getting upstream time out errors. If you could share a good best practise it would help * Jeremy wrote: For a production site, I use Cheetah with ...
[ "Maybe compile automagically on as needed basis:\nimport sys\nimport os\nfrom os import path\nimport logging\nfrom Cheetah.Template import Template\nfrom Cheetah.Compiler import Compiler\n\nlog = logging.getLogger(__name__)\n\n_import_save = __import__\ndef cheetah_import(name, *args, **kw):\n \"\"\"Import functio...
[ 1, 0 ]
[]
[]
[ "inheritance", "python", "web.py" ]
stackoverflow_0000919539_inheritance_python_web.py.txt
Q: Python regex for alphanumerics not working from django import forms class ActonForm(forms.Form): creator = forms.RegexField('^[a-zA-Z0-9\-' ]$',max_length=30, min_length=3) data = {'creator': 'hello' } f = ActonForm(data) print f.is_valid() Why doesn't this work? have i made a wrong regular expressio...
Python regex for alphanumerics not working
from django import forms class ActonForm(forms.Form): creator = forms.RegexField('^[a-zA-Z0-9\-' ]$',max_length=30, min_length=3) data = {'creator': 'hello' } f = ActonForm(data) print f.is_valid() Why doesn't this work? have i made a wrong regular expression? I wanted a name field with provision for sing...
[ "It kind of shows in the syntax highlighting. The apostrophe in the regex isn't escaped, it should be like this:\nforms.RegexField('^[a-zA-Z0-9\\\\-\\' ]$',max_length=30, min_length=3)\n\nEdit: When escaping things in the regular expression, you need double backslashes. I doubled the backslash before the hyphen (no...
[ 1 ]
[]
[]
[ "google_app_engine", "python", "regex" ]
stackoverflow_0000968553_google_app_engine_python_regex.txt
Q: fetching row numbers in a database-independent way - django Let's say that I have a 'Scores' table with fields 'User','ScoreA', 'ScoreB', 'ScoreC'. In a leaderboard view I fetch and order a queryset by any one of these score fields that the visitor selects. The template paginates the queryset. The table is updated...
fetching row numbers in a database-independent way - django
Let's say that I have a 'Scores' table with fields 'User','ScoreA', 'ScoreB', 'ScoreC'. In a leaderboard view I fetch and order a queryset by any one of these score fields that the visitor selects. The template paginates the queryset. The table is updated by a job on regular periods (a django command triggered by cron)...
[ "Why can't you compute the rank in the template?\n{% for row in results_to_display %}\n <tr><td>{{forloop.counter}}</td><td>{{row.scorea}}</td>...\n{% endfor %}\n\nOr, you can compute the rank in the view function.\ndef fetch_ranked_scores( request ):\n query = Score.objects.filter( ... ).orderby( scorea )\n ...
[ 4 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0000969074_django_django_orm_python.txt
Q: Installed apps in Django - what about versions? After looking at the reusable apps chapter of Practical Django Projects and listening to the DjangoCon (Pycon?) lecture, there seems to be an emphasis on making your apps pluggable by installing them into the Python path, namely site-packages. What I don't understan...
Installed apps in Django - what about versions?
After looking at the reusable apps chapter of Practical Django Projects and listening to the DjangoCon (Pycon?) lecture, there seems to be an emphasis on making your apps pluggable by installing them into the Python path, namely site-packages. What I don't understand is what happens when the version of one of those in...
[ "Having multiple versions of the same package gets messy (setuptools can do it, though).\nI've found it cleaner to put each project in its own virtualenv. We use virtualevwrapper to manage the virtualenvs easily, and the --no-site-packages option to make every project really self-contained and portable across machi...
[ 5, 0, 0 ]
[]
[]
[ "django", "python", "version_control" ]
stackoverflow_0000967855_django_python_version_control.txt
Q: Calculate the center of a contour/Area I'm working on a Image-processing chain that seperates a single object by color and contour and then calculates the y-position of this object. How do I calculate the center of a contour or area with OpenCV? Opencv links: http://opencv.willowgarage.com/wiki/ http://en.wikipe...
Calculate the center of a contour/Area
I'm working on a Image-processing chain that seperates a single object by color and contour and then calculates the y-position of this object. How do I calculate the center of a contour or area with OpenCV? Opencv links: http://opencv.willowgarage.com/wiki/ http://en.wikipedia.org/wiki/OpenCV
[ "You can get the center of mass in the y direction by first calculating the Moments. Then the center of mass is given by yc = M01 / M00, where M01 and M00 are fields in the structure returned by the Moments call.\nIf you just want the center of the bounding rectangle, that is also easy to do with BoundingRect. This...
[ 10 ]
[ "I don't exactly know what OpenCV is, but I would suggest this:\nThe Selected cluster of pixels has a maximum width at one point - w - so lets say the area has w vertical columns of pixels. Now I would weight the columns according to how many pixels the column contains, and use these column-wights to determine the ...
[ -2 ]
[ "contour", "image_processing", "opencv", "python" ]
stackoverflow_0000968332_contour_image_processing_opencv_python.txt
Q: breakpoint in eclipse for appengine I have pydev on eclipse and would like to debug handlers. I put breakpoint on a handler and start project in debug mode. When I click on the hyperlink corresponding to handler the control does not come back to breakpoint. Am I missing something here? Also the launch is for googl...
breakpoint in eclipse for appengine
I have pydev on eclipse and would like to debug handlers. I put breakpoint on a handler and start project in debug mode. When I click on the hyperlink corresponding to handler the control does not come back to breakpoint. Am I missing something here? Also the launch is for google app engine application in python.
[ "I'm using eclipse with PyDev with appengine and I debug all the time, it's completely possible !\nWhat you have to do is start the program in debug, but you have to start the dev_appserver in debug, not the handler directly. The main module you have to debug is:\n<path_to_gae>/dev_appserver.py\n\nWith program argu...
[ 4, 0 ]
[]
[]
[ "debugging", "eclipse", "google_app_engine", "pydev", "python" ]
stackoverflow_0000968701_debugging_eclipse_google_app_engine_pydev_python.txt
Q: Can I automatically change my PYTHONPATH when activating/deactivating a virtualenv? I would like to have a different PYTHONPATH from my usual in a particular virtualenv. How do I set this up automatically? I realize that it's possible to hack the bin/activate file, is there a better/more standard way? A: This dj...
Can I automatically change my PYTHONPATH when activating/deactivating a virtualenv?
I would like to have a different PYTHONPATH from my usual in a particular virtualenv. How do I set this up automatically? I realize that it's possible to hack the bin/activate file, is there a better/more standard way?
[ "This django-users post is probably going to help you a lot. It suggests using virtualenvwrapper to wrap virtualenv, to use the add2virtualenv command. Using this, when the environment is active, you can just call:\nadd2virtualenv directory1 directory2 ...\n\nto add the directories to your pythonpath for the curren...
[ 19, 2 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0000969553_python_virtualenv.txt
Q: Binary file IO in python, where to start? As a self-taught python hobbyist, how would I go about learning to import and export binary files using standard formats? I'd like to implement a script that takes ePub ebooks (XHTML + CSS in a zip) and converts it to a mobipocket (Palmdoc) format in order to allow the Ama...
Binary file IO in python, where to start?
As a self-taught python hobbyist, how would I go about learning to import and export binary files using standard formats? I'd like to implement a script that takes ePub ebooks (XHTML + CSS in a zip) and converts it to a mobipocket (Palmdoc) format in order to allow the Amazon Kindle to read it (as part of a larger proj...
[ "You should probably start with the struct module, as you pointed to in your question, and of course, open the file as a binary.\nBasically you just start at the beginning of the file and pick it apart piece by piece. It's a hassle, but not a huge problem. If the files are compressed or encrypted, things can get ...
[ 10, 2, 0 ]
[]
[]
[ "binary", "epub", "io", "mobipocket", "python" ]
stackoverflow_0000967652_binary_epub_io_mobipocket_python.txt
Q: Subclassing list I want create a DataSet class which is basically a list of samples. But I need to override each insertion operation to the DataSet. Is there any simple way to do this without writing my own append, extend, iadd etc. ? UPDATE: I want to add a backpointer to each sample, holding index of the sample ...
Subclassing list
I want create a DataSet class which is basically a list of samples. But I need to override each insertion operation to the DataSet. Is there any simple way to do this without writing my own append, extend, iadd etc. ? UPDATE: I want to add a backpointer to each sample, holding index of the sample in the DataSet. This i...
[ "I don't know of a way of doing what you're asking -- overriding mutators without overriding them. With a class decorator, however, you can \"automate\" the overriding versions (assuming each can be achieved by wrapping the corresponding method in the base class), so it's not too bad...\nSuppose for example that wh...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0000970425_python.txt
Q: What is the most state-of-the-art, pure python, XML parser available? Considering that I want to write python code that would run on Google App Engine and also inside jython, C-extensions are not an option. Amara was a nice library, but due to its C-extensions, I can't use it for either of these platforms. A: El...
What is the most state-of-the-art, pure python, XML parser available?
Considering that I want to write python code that would run on Google App Engine and also inside jython, C-extensions are not an option. Amara was a nice library, but due to its C-extensions, I can't use it for either of these platforms.
[ "ElementTree is very nice. It's also part of 2.5.\n", "There's also Beautiful Soup (which may be geared more toward HTML, but it also does XML).\n", "xml.sax is a builtin SAX parser\n", "I would normally recommend lxml, but since that uses a C-library (libxml) the alternative would have to be, as Aaron has al...
[ 8, 4, 1, 1 ]
[]
[]
[ "google_app_engine", "jython", "python", "xml" ]
stackoverflow_0000970531_google_app_engine_jython_python_xml.txt
Q: Is a file on the same filesystem as another file in python? Is there a simple way of finding out if a file is on the same filesystem as another file? The following command: import shutil shutil.move('filepatha', 'filepathb') will try and rename the file (if it's on the same filesystem), otherwise it will copy it,...
Is a file on the same filesystem as another file in python?
Is there a simple way of finding out if a file is on the same filesystem as another file? The following command: import shutil shutil.move('filepatha', 'filepathb') will try and rename the file (if it's on the same filesystem), otherwise it will copy it, then unlink. I want to find out before calling this command whet...
[ "Use os.stat (on a filename) or os.fstat (on a file descriptor). The st_dev of the result will be the device number. If they are on the same file system, it will be the same in both.\nimport os\n\ndef same_fs(file1, file2):\n dev1 = os.stat(file1).st_dev\n dev2 = os.stat(file2).st_dev\n return dev1 == dev2...
[ 11 ]
[]
[]
[ "filesystems", "python" ]
stackoverflow_0000970742_filesystems_python.txt
Q: Testing for mysterious load errors in python/django This is related to this Configure Apache to recover from mod_python errors, although I've since stopped assuming that this has anything to do with mod_python. Essentially, I have a problem that I wasn't able to reproduce consistently and I wanted some feedback o...
Testing for mysterious load errors in python/django
This is related to this Configure Apache to recover from mod_python errors, although I've since stopped assuming that this has anything to do with mod_python. Essentially, I have a problem that I wasn't able to reproduce consistently and I wanted some feedback on whether the proposed solution seems likely and some pot...
[ "\"Do these configuration disasters seem like a likely explanation for sporadic ImportErrors\"\nYes. An old .pyc file is a disaster of the first magnitude.\nWe develop on Windows, but run production on Red Hat Linux. An accidentally moved .pyc file is an absolute mystery to debug because (1) it usually runs and (...
[ 2 ]
[]
[]
[ "apache", "configuration", "django", "python" ]
stackoverflow_0000970953_apache_configuration_django_python.txt
Q: Opencv sort sequences in python I'm using the Python OpenCV bindings to find the contours in an Image. I'm know looking for the possibility to sort this sequence. It seems the usual python ways for list sorting don't apply here because of the linked list structure generated from OpenCV. Do you know a good way t...
Opencv sort sequences in python
I'm using the Python OpenCV bindings to find the contours in an Image. I'm know looking for the possibility to sort this sequence. It seems the usual python ways for list sorting don't apply here because of the linked list structure generated from OpenCV. Do you know a good way to sort the Contours by Size (Area/Bou...
[ "You have to be able to look at an entire sequence in order to sort it (easily). Thus you should copy it to sort it.\nI would do something like\n contourList = list(<your linked list>)\n def sizeKey(countour):\n <get size from contour>\n contourList.sort(key = sizeKey)\n\nIf everything is not being store...
[ 2 ]
[]
[]
[ "contour", "image_processing", "opencv", "python", "sorting" ]
stackoverflow_0000971629_contour_image_processing_opencv_python_sorting.txt
Q: Interfacing web crawler with Django front end I'm trying to do three things. One: crawl and archive, at least daily, a predefined set of sites. Two: run overnight batch python scripts on this data (text classification). Three: expose a Django based front end to users to let them search the crawled data. I've been ...
Interfacing web crawler with Django front end
I'm trying to do three things. One: crawl and archive, at least daily, a predefined set of sites. Two: run overnight batch python scripts on this data (text classification). Three: expose a Django based front end to users to let them search the crawled data. I've been playing with Apache Nutch/Lucene but getting it to ...
[ "If you insert your django project's app directories into sys.path, you can write standard Python scripts that utilize the Django ORM functionality. We have an /admin/ directory that contains scripts to perform various tasks-- at the top of each script is a block that looks like:\nsys.path.insert(0,os.path.abspath...
[ 3, 2, 1 ]
[]
[]
[ "django", "python", "web_crawler" ]
stackoverflow_0000971660_django_python_web_crawler.txt
Q: automatic keystroke to stay logged in I have a web based email application that logs me out after 10 minutes of inactivity ("For security reasons"). I would like to write something that either a) imitates a keystroke b) pings an ip or c) some other option every 9 minutes so that I stay logged in. I am on my person...
automatic keystroke to stay logged in
I have a web based email application that logs me out after 10 minutes of inactivity ("For security reasons"). I would like to write something that either a) imitates a keystroke b) pings an ip or c) some other option every 9 minutes so that I stay logged in. I am on my personal laptop in an office with a door, so I'm ...
[ "Assuming you use Windows, you can add a bat file containing the python run command in the Startup folder.\nExample keeploggedin.bat\nC:\\Steve\\Projects\\Python> python pytest.py\n\n", "You can also use the Scheduled Tasks feature (on the Control Panel) to run it at startup, or you can change your script to ping...
[ 3, 3, 2, 1 ]
[]
[]
[ "authentication", "python" ]
stackoverflow_0000969849_authentication_python.txt
Q: Django conditional aggregation Does anyone know of how I would, through the django ORM, produce a query that conditionally aggregated related models? Let's say, for example, that you run a site that sells stuff, and you want to know how much each employee has sold in the last seven days. It's simple enough to do ...
Django conditional aggregation
Does anyone know of how I would, through the django ORM, produce a query that conditionally aggregated related models? Let's say, for example, that you run a site that sells stuff, and you want to know how much each employee has sold in the last seven days. It's simple enough to do this over all sales: q = Employee.ob...
[ "Alright, I guess I didn't think this through very far. I didn't realize that filter handled things with a left join (though thinking on it, how else would it map to the db?), so the obvious answer is:\nEmployee.objects.filter(type='salesman').filter(sale__timestamp__gte = start_date)\\\n .exclude(sale__tim...
[ 2 ]
[]
[]
[ "aggregation", "conditional", "database", "django", "python" ]
stackoverflow_0000971695_aggregation_conditional_database_django_python.txt
Q: How can I create a variable that is scoped to a single request in app engine? I'm creating a python app for google app engine and I've got a performance problem with some expensive operations that are repetitive within a single request. To help deal with this I'd like to create a sort of mini-cache that's scoped ...
How can I create a variable that is scoped to a single request in app engine?
I'm creating a python app for google app engine and I've got a performance problem with some expensive operations that are repetitive within a single request. To help deal with this I'd like to create a sort of mini-cache that's scoped to a single request. This is as opposed to a session-wide or application-wide cach...
[ "What I usually do is just create a new attribute on the request object. However, I use django with AppEngine, so I'm not sure if there is anything different about the appengine webapp framework.\ndef view_handler(request):\n if hasattr(request, 'mycache'):\n request.mycache['counter'] += 1\n else:\n ...
[ 2, 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000963080_google_app_engine_python.txt
Q: GQL does not work for GET paramters for keys I am trying to compare the key to filter results in GQL in Python but the direct comparison nor typecasting to int works. Therefore, I am forced to make a work around as mentioned in the uncommented lines below. Any clues? row = self.request.get("selectedrow") #mydbobje...
GQL does not work for GET paramters for keys
I am trying to compare the key to filter results in GQL in Python but the direct comparison nor typecasting to int works. Therefore, I am forced to make a work around as mentioned in the uncommented lines below. Any clues? row = self.request.get("selectedrow") #mydbobject = DbModel.gql("WHERE key=:1", row).fetch(1) #my...
[ "Am I correct in my assumption that you're basically just want to retrieve an object with a particular key? If so, the get and get_by_id methods may be of help:\nmydbobject = DbModel.get_by_id(int(self.request.get(\"selectedrow\")))\n\n", "The error \"invalid literal for int()\" indicate that the paramater pass t...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "gqlquery", "python" ]
stackoverflow_0000971153_google_app_engine_gqlquery_python.txt
Q: About GUI editor that would be compatible with Python 3.0 I would like to start learning Python (zero past experience). I am a bit inclined to start with Python 3.0. However, I am not sure if at this time there exists a GUI editor that would be compatible with Python 3.0. I've tried installing Glade, but the one I...
About GUI editor that would be compatible with Python 3.0
I would like to start learning Python (zero past experience). I am a bit inclined to start with Python 3.0. However, I am not sure if at this time there exists a GUI editor that would be compatible with Python 3.0. I've tried installing Glade, but the one I've got works only with Python 2.5. What could I possibly use w...
[ "There are many useful libraries (not to mention educational material, cookbook snippets, etc.) that have yet to be ported to Python 3.0, so I recommend using Python 2.x for now (where, currently, 5 <= x <= 6). Doubly so if you're a beginner to Python. Triply so if you're actually planning on releasing some softwar...
[ 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x", "user_interface" ]
stackoverflow_0000800769_python_python_3.x_user_interface.txt
Q: spawning process from python im spawning a script that runs for a long time from a web app like this: os.spawnle(os.P_NOWAIT, "../bin/producenotify.py", "producenotify.py", "xx",os.environ) the script is spawned successfully and it runs, but till it gets over i am not able to free the port that is used by the web...
spawning process from python
im spawning a script that runs for a long time from a web app like this: os.spawnle(os.P_NOWAIT, "../bin/producenotify.py", "producenotify.py", "xx",os.environ) the script is spawned successfully and it runs, but till it gets over i am not able to free the port that is used by the web app, or in other words i am not a...
[ "As @mark clarified it's a Linux system, the script could easily make itself fully independent, i.e., a daemon, by following this recipe. (You could also do it in the parent after an os.fork and only then os.exec... the child process).\nEdit: to clarify some details wrt @mark's comment on my answer: super-user pri...
[ 26, 12 ]
[]
[]
[ "process", "python", "spawn" ]
stackoverflow_0000972362_process_python_spawn.txt
Q: Running a set of Python scripts in a list I am working on a Python project that includes a lot of simple example scripts to help new users get used to the system. As well as the source code for each example, I include the output I get on my test machine so users know what to expect when all goes well. It occured ...
Running a set of Python scripts in a list
I am working on a Python project that includes a lot of simple example scripts to help new users get used to the system. As well as the source code for each example, I include the output I get on my test machine so users know what to expect when all goes well. It occured to me that I could use this as a crude form of ...
[ "You could leverage doctest to help you get this done. Write a method that executes each script, and in the docstring for each method you paste the expected output:\ndef run_example1():\n \"\"\"\n This is example number 1. Running it should give you the following output:\n\n >>> run_example1()\n \"This ...
[ 8, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0000973231_python.txt
Q: Python regular expression for multiple tags I would like to know how to retrieve all results from each <p> tag. import re htmlText = '<p data="5" size="4">item1</p><p size="4">item2</p><p size="4">item3</p>' print re.match('<p[^>]*size="[0-9]">(.*?)</p>', htmlText).groups() result: ('item1', ) what I need: ('ite...
Python regular expression for multiple tags
I would like to know how to retrieve all results from each <p> tag. import re htmlText = '<p data="5" size="4">item1</p><p size="4">item2</p><p size="4">item3</p>' print re.match('<p[^>]*size="[0-9]">(.*?)</p>', htmlText).groups() result: ('item1', ) what I need: ('item1', 'item2', 'item3')
[ "For this type of problem, it is recommended to use a DOM parser, not regex.\nI've seen Beautiful Soup frequently recommended for Python\n", "Beautiful soup is definitely the way to go with a problem like this. The code is cleaner and easier to read. Once you have it installed, getting all the tags looks someth...
[ 11, 5, 5, 2, 2 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0000972749_html_python_regex.txt
Q: writing to a file via FTP in python So i've followed the docs on this page: http://docs.python.org/library/ftplib.html#ftplib.FTP.retrbinary And maybe i'm confused just as to what 'retrbinary' does...i'm thinking it retrives a binary file and from there i can open it and write out to that file. here's the line tha...
writing to a file via FTP in python
So i've followed the docs on this page: http://docs.python.org/library/ftplib.html#ftplib.FTP.retrbinary And maybe i'm confused just as to what 'retrbinary' does...i'm thinking it retrives a binary file and from there i can open it and write out to that file. here's the line that is giving me problems... ftp.retrbinary...
[ "It looks like the original code should have worked, if you were trying to download a file from the server. The retrbinary command accepts a function object you specify (that is, the name of the function with no () after it); it is called whenever a piece of data (a binary file) arrives. In this case, it will call ...
[ 3, 0 ]
[]
[]
[ "ftp", "ftplib", "python" ]
stackoverflow_0000973551_ftp_ftplib_python.txt
Q: concurrently iterating through even and odd items of list I have a list of items (which are HTML table rows, extracted with Beautiful Soup) and I need to iterate over the list and get even and odd elements (I mean index) for each loop run. My code looks like this: for top, bottom in izip(table[::2], table[1::2]):...
concurrently iterating through even and odd items of list
I have a list of items (which are HTML table rows, extracted with Beautiful Soup) and I need to iterate over the list and get even and odd elements (I mean index) for each loop run. My code looks like this: for top, bottom in izip(table[::2], table[1::2]): #do something with top #do something else with bottom ...
[ "izip is a pretty good option, but here's a few alternatives since you're unhappy with it:\n>>> def chunker(seq, size):\n... return (tuple(seq[pos:pos+size]) for pos in xrange(0, len(seq), size))\n...\n>>> x = range(11)\n>>> x\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n>>> chunker(x, 2)\n<generator object <genexpr> a...
[ 5, 4, 0 ]
[]
[]
[ "for_loop", "python", "python_itertools" ]
stackoverflow_0000974219_for_loop_python_python_itertools.txt
Q: Syntax Highlighting in Cocoa TextView? Experiences? Suggestions? Ideas? Possible Duplicate: Syntax coloring for Cocoa app I'm interested in syntax highlighting in a Cocoa TextView. I found several resources: approach with flex, via a flex pattern matched against textStorageDidProcessEditing in a TextView delega...
Syntax Highlighting in Cocoa TextView? Experiences? Suggestions? Ideas?
Possible Duplicate: Syntax coloring for Cocoa app I'm interested in syntax highlighting in a Cocoa TextView. I found several resources: approach with flex, via a flex pattern matched against textStorageDidProcessEditing in a TextView delegate. In this approach the whole string get parsed on each input event, hence ...
[ "I would suggest taking a look at the source code to Smultron. It has very nice syntax highlighting. It uses a subclass of NSTextView to do most of the heavy lifting. The code uses the layout manager to add attributes to the text and uses some other clever tricks to only highlight as much of the document as nece...
[ 7 ]
[]
[]
[ "cocoa", "objective_c", "python", "syntax_highlighting", "textview" ]
stackoverflow_0000972812_cocoa_objective_c_python_syntax_highlighting_textview.txt
Q: Cleaning up an internal pysqlite connection on object destruction I have an object with an internal database connection that's active throughout its lifetime. At the end of the program's run, the connection has to be committed and closed. So far I've used an explicit close method, but this is somewhat cumbersome, ...
Cleaning up an internal pysqlite connection on object destruction
I have an object with an internal database connection that's active throughout its lifetime. At the end of the program's run, the connection has to be committed and closed. So far I've used an explicit close method, but this is somewhat cumbersome, especially when exceptions can happen in the calling code. I'm consider...
[ "Read up on the with statement. You're describing its use case.\nYou'll need to wrap your connection in a \"Context Manager\" class that handles the __enter__ and __exit__ methods used by the with statement.\nSee PEP 343 for more information.\n\nEdit\n\"my object isn't used as simply as open-play-close, but is kep...
[ 8, 6 ]
[]
[]
[ "destructor", "pysqlite", "python" ]
stackoverflow_0000974813_destructor_pysqlite_python.txt
Q: Multiply operator applied to list(data structure) I'm reading How to think like a computer scientist which is an introductory text for "Python Programming". I want to clarify the behaviour of multiply operator (*) when applied to lists. Consider the function make_matrix def make_matrix(rows, columns): """ >>> ma...
Multiply operator applied to list(data structure)
I'm reading How to think like a computer scientist which is an introductory text for "Python Programming". I want to clarify the behaviour of multiply operator (*) when applied to lists. Consider the function make_matrix def make_matrix(rows, columns): """ >>> make_matrix(4, 2) [[0, 0], [0, 0], [0, 0], [0, 0]] >>...
[ "EVERYTHING in python are objects, and python never makes copies unless explicity asked to do so.\nWhen you do \ninnerList = [0] * 10\n\nyou create a list with 10 elements, all of them refering to the same int object 0.\nSince integer objects are immutable, when you do\ninnerList[1] = 15\n\nYou are changing the sec...
[ 20 ]
[ "lists are not primitives, they are passed by reference. A copy of a list is a pointer to a list (in C jargon). Anything you do to the list happens to all copies of the list and the copies of its contents unless you do a shallow copy.\n[[0] * columns] * rows\n\nOops, we've just made a big list of pointers to [0]. C...
[ -4 ]
[ "list", "multiplication", "python", "python_datamodel", "shallow_copy" ]
stackoverflow_0000974931_list_multiplication_python_python_datamodel_shallow_copy.txt
Q: python not starting properly I have installed python and django in my system that uses win vista. Now when I go to command prompt and type python or django-admin.py both are not working. Every time I need to set the path to the python folder manually. But i have seen these commands running even without setting pa...
python not starting properly
I have installed python and django in my system that uses win vista. Now when I go to command prompt and type python or django-admin.py both are not working. Every time I need to set the path to the python folder manually. But i have seen these commands running even without setting path. So how do i make it to run pro...
[ "You probably need to add Python to you dos path. Here's a video that may help you out:\nhttp://showmedo.com/videotutorials/video?name=960000&fromSeriesID=96\n", "you can't run a command that isn't in your path. it should be set globally when you installed python.\ntype 'set' at a dos prompt and look at the PATH...
[ 2, 1, 0, 0 ]
[]
[]
[ "django_admin", "python", "windows" ]
stackoverflow_0000974821_django_admin_python_windows.txt
Q: python - match on array return value I want to do a functional like pattern match to get the first two elements, and then the rest of an array return value. For example, assume that perms(x) returns a list of values, and I want to do this: seq=perms(x) a = seq[0] b = seq[1] rest = seq[2:] Of course I can shorten ...
python - match on array return value
I want to do a functional like pattern match to get the first two elements, and then the rest of an array return value. For example, assume that perms(x) returns a list of values, and I want to do this: seq=perms(x) a = seq[0] b = seq[1] rest = seq[2:] Of course I can shorten to: [a,b] = seq[0:2] rest = seq[2:] Can ...
[ "You can do it in Python 3 like this:\n(a, b, *rest) = seq\n\nSee the extended iterable unpacking PEP for more details.\n", "In python 2, your question is very close to an answer already:\na, b, more = (seq[0], seq[1], seq[2:])\n\nor:\n(a, b), more = (seq[0:2], seq[2:])\n\n", "For Python 2, I know you can do it...
[ 6, 3, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0000923553_list_python.txt