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: Python (1..n) syntax? I see in the code on this Sage wiki page the following code: @interact def _(order=(1..12)): Is this (1..n) syntax unique to Sage or is it something in Python? Also, what does it do? A: It's Sage-specific. You can use preparse to see how it is desugared to: sage: preparse("(1..12)") '(elli...
Python (1..n) syntax?
I see in the code on this Sage wiki page the following code: @interact def _(order=(1..12)): Is this (1..n) syntax unique to Sage or is it something in Python? Also, what does it do?
[ "It's Sage-specific. You can use preparse to see how it is desugared to:\nsage: preparse(\"(1..12)\")\n'(ellipsis_iter(Integer(1),Ellipsis,Integer(12)))'\n\nSee here for documentation of ellipsis_iter, here for information on the preparser. \n", "There was a Python PEP to add this notation to Python, but it was r...
[ 13, 10, 1, 0 ]
[]
[]
[ "python", "sage" ]
stackoverflow_0003511699_python_sage.txt
Q: How to bind self events in Tkinter Text widget after it will binded by Text widget? I want to bind self events after Text widget class bindings, in order to change the text of the widget when my binding function is called. My binding, for example self.text.bind("<Key>", self.callback), is called before the content...
How to bind self events in Tkinter Text widget after it will binded by Text widget?
I want to bind self events after Text widget class bindings, in order to change the text of the widget when my binding function is called. My binding, for example self.text.bind("<Key>", self.callback), is called before the content in Text widget changes.
[ "What is happening in your case is that your binding to print the value happens before the class binding, and it's the class binding that actually takes user input and puts it in the widget. There are several ways to solve this problem. You could bind to <KeyRelease> instead of <KeyPress>, or you could use the buil...
[ 35 ]
[]
[]
[ "binding", "events", "python", "text", "tkinter" ]
stackoverflow_0003501849_binding_events_python_text_tkinter.txt
Q: Enable gzip compression in a Grok - Zope - PasteScript environment I am trying to make my server send gzipped data. I have a grok application that runs over Paste (Paste-1.7.2-py2.4.egg) I have been trying to google how to make all that environment to serve data in gzip... But without success... I think the answer...
Enable gzip compression in a Grok - Zope - PasteScript environment
I am trying to make my server send gzipped data. I have a grok application that runs over Paste (Paste-1.7.2-py2.4.egg) I have been trying to google how to make all that environment to serve data in gzip... But without success... I think the answer comes in http://pythonpaste.org/modules/gzipper.html but if I do this: ...
[ "Well... I am going to reply to myself... \nIt turns out that modifying the .ini files in the way I detailed in my question was, indeed, activating the gzip compression.\nI thought that it wasn't doing anything because I believed what the Google Chrome's Developer Tools audits were saying... Said audits were still ...
[ 1 ]
[]
[]
[ "grok", "gzip", "http", "paster", "python" ]
stackoverflow_0003391950_grok_gzip_http_paster_python.txt
Q: How to work with a new Python installation while having an old one installed? After a fresh installation of my Windows dev machine, I installed Python 2.7. Quickly I learnt that this was a mistake as many of the packages I use only work on Python 2.6. So I installed 2.6 also and now I have both installations. How ...
How to work with a new Python installation while having an old one installed?
After a fresh installation of my Windows dev machine, I installed Python 2.7. Quickly I learnt that this was a mistake as many of the packages I use only work on Python 2.6. So I installed 2.6 also and now I have both installations. How can I make everything work with Python 2.6 instead of Python 2.7? Every time I inst...
[ "Most python installations come with an uninstaller that shows up in Add/Remove programs on Windows.\nIt is certainly possible to have several versions installed. On my windows machine, I have Python 2.5, 2.6, 2.7 and 3.1. The \"default\" python is the one which occurs first in your system path. Also (depending on ...
[ 2 ]
[]
[]
[ "python", "uninstallation", "version", "windows" ]
stackoverflow_0003514444_python_uninstallation_version_windows.txt
Q: webpy: How to serve JSON Is it possible to use webpy to serve JSON? I built my website and I need to serve some information in JSON to interact with the Javascript on some pages. I try to look for answers in the documentation, but I'm not able to find anything. Thanks, Giovanni A: I wouldn't think you'd have to ...
webpy: How to serve JSON
Is it possible to use webpy to serve JSON? I built my website and I need to serve some information in JSON to interact with the Javascript on some pages. I try to look for answers in the documentation, but I'm not able to find anything. Thanks, Giovanni
[ "I wouldn't think you'd have to do any thing overly \"special\" for web.py to serve JSON.\nimport web\nimport json\n\nclass index:\n def GET(self):\n pyDict = {'one':1,'two':2}\n web.header('Content-Type', 'application/json')\n return json.dumps(pyDict)\n\n" ]
[ 62 ]
[ "It is certainly possible to serve JSON from webpy, But if you and choosing a framework, I would look at starlight and my fork twilight (for documentation).\nIt has a JSON wrapper for fixing the http headers for your json response. \nit uses either the json or simplejson libraries for json handling the conversions ...
[ -6 ]
[ "python", "web.py" ]
stackoverflow_0003513446_python_web.py.txt
Q: how to force matplotlib to update a plot I am trying to construct a little GUI that has a plot which updates every time a new data sample is read. I would prefer not to run it with a timer, since the data will be arriving at differing intervals. Instead, I'm trying to make an implementation using signals, where ...
how to force matplotlib to update a plot
I am trying to construct a little GUI that has a plot which updates every time a new data sample is read. I would prefer not to run it with a timer, since the data will be arriving at differing intervals. Instead, I'm trying to make an implementation using signals, where the data collection function will emit a signa...
[ "I'd guess that calling QCoreApplication::processEvents after paint() will help. More elegant would be to have a separate QThread for the reading. Take a look at this thread.\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "pyqt4", "python", "qt4", "signals_slots" ]
stackoverflow_0003514074_matplotlib_pyqt4_python_qt4_signals_slots.txt
Q: How do I parse only foreign characters from the text in an HTML file with regular expressions I'm trying to parse HTML and automatically change the font of any foreign characters, and I'm having some issues. There are a few different hackish ways I'm trying to accomplish this, but none work really well, and I'm wo...
How do I parse only foreign characters from the text in an HTML file with regular expressions
I'm trying to parse HTML and automatically change the font of any foreign characters, and I'm having some issues. There are a few different hackish ways I'm trying to accomplish this, but none work really well, and I'm wondering if anyone has any ideas. Is there any easy way with python to match all the foreign charact...
[ "I wouldn't use just regular expressions for this. Down that path lies an angry Tony the Pony.\nI'd use an HTML parser in conjuction with regular expressions, though. That way you can distinguish the markup from the non-markup.\n", "Use BeautifulSoup to get the content that you need, then use a variation on thi...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003514415_python_regex.txt
Q: How to use C extensions in python to get around GIL I want to run a cpu intensive program in Python across multiple cores and am trying to figure out how to write C extensions to do this. Are there any code samples or tutorials on this? A: You can already break a Python program into multiple processes. The OS ...
How to use C extensions in python to get around GIL
I want to run a cpu intensive program in Python across multiple cores and am trying to figure out how to write C extensions to do this. Are there any code samples or tutorials on this?
[ "You can already break a Python program into multiple processes. The OS will already allocate your processes across all the cores.\nDo this.\npython part1.py | python part2.py | python part3.py | ... etc.\n\nThe OS will assure that part uses as many resources as possible. You can trivially pass information along ...
[ 9, 7, 1 ]
[ "Have you considered using one of the python mpi libraries like mpi4py? Although MPI is normally used to distribute work across a cluster, it works quite well on a single multicore machine. The downside is that you'll have to refactor your code to use MPI's communication calls (which may be easy).\n", "multiproce...
[ -1, -2 ]
[ "python", "python_c_extension" ]
stackoverflow_0003514495_python_python_c_extension.txt
Q: What is wrong with this Python game code? import random secret = random.randint (1,99) guess = 0 tries = 0 print ("AHOY! I'm the Dread Pirate Roberts, and I have a secret!") print ("It is a number from 1 to 99. I'll give you 6 tries. ") while guess != secret and tries < 6: guess = input ("What's yer guess? ...
What is wrong with this Python game code?
import random secret = random.randint (1,99) guess = 0 tries = 0 print ("AHOY! I'm the Dread Pirate Roberts, and I have a secret!") print ("It is a number from 1 to 99. I'll give you 6 tries. ") while guess != secret and tries < 6: guess = input ("What's yer guess? ") if guess < secret: print ("Too l...
[ "guess = input (\"What's yer guess? \")\n\nCalling input gives you back a string, not an int. When you then compare guess using <, you need an int in order to compare a numerical value. Try doing something along the lines of:\ntry:\n guess = int(input(\"What's yer guess? \"))\nexcept ValueError:\n # Handle ...
[ 12, 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003514154_python.txt
Q: created sorted table in gtk What's the easieest way to create a sorted table view in gtk? I'm not sure if that's the right term, but you know the one: (source: sun.com) Is there a built-in widget for this? If not, how would I go about making those columns that look slightly different, click to change sorting, etc...
created sorted table in gtk
What's the easieest way to create a sorted table view in gtk? I'm not sure if that's the right term, but you know the one: (source: sun.com) Is there a built-in widget for this? If not, how would I go about making those columns that look slightly different, click to change sorting, etc. Note I don't need multi-column ...
[ "Sorted List Stores\nUPDATE:\nAfter looking at your edit (disregarding commens):\n\nThere is no built-in widget, but ListView = TreeView + ListStore\nClicking to change sorting is harder, but probably not by much\n\nRemember that most anything is handled by their tutorial, at PyGTK.org (HTML)\nand in PDF Format. Th...
[ 2 ]
[]
[]
[ "gtk", "pygtk", "python", "uitableview", "user_interface" ]
stackoverflow_0003513480_gtk_pygtk_python_uitableview_user_interface.txt
Q: Prevent normal users to execute I need a better way to prevent normal users from executing my python script. I'm doing something like that: if __name__ == '__main__': if os.getenv('USER') == 'root': addUser = addUser() else: print 'Only root can run that!' It's working, but it's pretty ugl...
Prevent normal users to execute
I need a better way to prevent normal users from executing my python script. I'm doing something like that: if __name__ == '__main__': if os.getenv('USER') == 'root': addUser = addUser() else: print 'Only root can run that!' It's working, but it's pretty ugly! My script is about user management...
[ "Python code can be viewed and edited to circumvent any protection you put in, your best bet is to restrict executable access by user in debian so only root can execute/view/edit.\nSee chmod\n", "It's more normal to restrict access to the resources an executable needs to work than to enforce permissions at the le...
[ 12, 5 ]
[]
[]
[ "debian", "python", "root" ]
stackoverflow_0003515062_debian_python_root.txt
Q: Refactoring Index/Search View I've written an index and search view all in one if a GET request is detected it returns just the search results otherwise it returns all records. I've written this view below but I feel like I'm repeating myself a bit too much. Any ideas as to how I can slim this code down a bit woul...
Refactoring Index/Search View
I've written an index and search view all in one if a GET request is detected it returns just the search results otherwise it returns all records. I've written this view below but I feel like I'm repeating myself a bit too much. Any ideas as to how I can slim this code down a bit would be much appreciated. def index(re...
[ "Perhaps not the best way but for me this makes it a little bit more readable and minimizes repetition.\ndef index(request):\n def get_companies(company_list):\n paginator = Paginator(company_list, 10)\n\n    try:\n        page = int(request.GET.get('page', '1'))\n    except ValueError:\n     ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003506393_django_python.txt
Q: Detecting timeout erros in Python's urllib2 urlopen I'm still relatively new to Python, so if this is an obvious question, I apologize. My question is in regard to the urllib2 library, and it's urlopen function. Currently I'm using this to load a large amount of pages from another server (they are all on the same ...
Detecting timeout erros in Python's urllib2 urlopen
I'm still relatively new to Python, so if this is an obvious question, I apologize. My question is in regard to the urllib2 library, and it's urlopen function. Currently I'm using this to load a large amount of pages from another server (they are all on the same remote host) but the script is killed every now and then ...
[ "Next time the error occurs, take note of the error message. The last line will tell you the type of exception. For example, it might be a urllib2.HTTPError. Once you know the type of exception raised, you can catch it in a try...except block. For example:\nimport urllib2\nimport time\n\nfor url in urls:\n while...
[ 2, 1 ]
[]
[]
[ "python", "urllib2", "urlopen" ]
stackoverflow_0003515087_python_urllib2_urlopen.txt
Q: Can an API tell Pylint not to complain in the client code? I have some code in a reusable class that modifies some types. Here's a simplified version. class Foo: def __init__(self): self.count = 0 def increment(self): self.count += 1 # Add another method outside of the class definition. #...
Can an API tell Pylint not to complain in the client code?
I have some code in a reusable class that modifies some types. Here's a simplified version. class Foo: def __init__(self): self.count = 0 def increment(self): self.count += 1 # Add another method outside of the class definition. # Pylint doesn't care about this, and rates this file 10/10. Foo...
[ "Here is my solution inspired by the example in ActiveState cookbook recipe, provided in Yoni H's answer.\nTo the Foo class, I added this useless __getattr__ method.\ndef __getattr__(self, name):\n # This is only called when the normal mechanism fails, so in practice should never be called.\n # It is only pr...
[ 6, 2, 0 ]
[]
[]
[ "pylint", "python" ]
stackoverflow_0003509599_pylint_python.txt
Q: Google App Engine and Amazon S3 File Uploads I know this has been asked before but there is really not a clear answer. My problem is I built a file upload script for GAE and only found out after, that you can only store files up to aprox. 1MB in the data store. I can stop you right here if you can tell me that if ...
Google App Engine and Amazon S3 File Uploads
I know this has been asked before but there is really not a clear answer. My problem is I built a file upload script for GAE and only found out after, that you can only store files up to aprox. 1MB in the data store. I can stop you right here if you can tell me that if I enable billing the 1MB limit is history but I do...
[ "From the Amazon S3 documentation:\n\nThe user opens a web browser and accesses your web page.\nYour web page contains an HTTP form that contains all the information necessary for the user to upload content to Amazon S3.\nThe user uploads content directly to Amazon S3.\n\nGAE prepares and serves the web page, a spe...
[ 13, 3, 2, 1, 0 ]
[]
[]
[ "amazon_ec2", "amazon_s3", "google_app_engine", "python" ]
stackoverflow_0000972895_amazon_ec2_amazon_s3_google_app_engine_python.txt
Q: Python print statements being buffered with > output redirection I'm doing print statements in python. I'm executing my script like so: python script.py > out.log nohup & The print statements are not all showing up in out.log but the program is finishing ok. That line of code is in an .sh file I execute by doing ...
Python print statements being buffered with > output redirection
I'm doing print statements in python. I'm executing my script like so: python script.py > out.log nohup & The print statements are not all showing up in out.log but the program is finishing ok. That line of code is in an .sh file I execute by doing ./script.sh Update: The log does get all the data but not until a cert...
[ "When stdout is sent to a tty it will be line buffered and will be flushed every line, but when redirected to a file or pipe it'll be fully buffered and will only be flushed periodically when you overrun the buffer.\nYou'll have to add sys.stdout.flush() calls after each line if you want the output to be immediatel...
[ 27, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0003515757_linux_python.txt
Q: PIL save as 24 bit true color bitmap I have a png file generated by Gnuplot that I need to put into an excel document using XLWT. XLWT can't import PNG's into the document, only BMP's, so I needed to convert the PNG first. I used PIL for this. Here's the relevant code: im = Image.open('%s' % os.path.join(os.getcwd...
PIL save as 24 bit true color bitmap
I have a png file generated by Gnuplot that I need to put into an excel document using XLWT. XLWT can't import PNG's into the document, only BMP's, so I needed to convert the PNG first. I used PIL for this. Here's the relevant code: im = Image.open('%s' % os.path.join(os.getcwd(), s + '.png')) im.save('%s.bmp' % s) Ho...
[ "Nevermind! Just figured it out myself.\nChange\nim = Image.open('%s' % os.path.join(os.getcwd(), s + '.png'))\n\nTo\nim = Image.open('%s' % os.path.join(os.getcwd(), s + '.png')).convert(\"RGB\")\n\n" ]
[ 7 ]
[]
[]
[ "gnuplot", "python", "python_imaging_library", "xlwt" ]
stackoverflow_0003516144_gnuplot_python_python_imaging_library_xlwt.txt
Q: OpenID auth: which method to get a unique identifier to use as key? Using OpenID auth, which is the proper User instance method to get a unique identifier useful for creating and identifying a user on Datastore as key_name? Available methods : nickname() For OpenID users, the nickname is the OpenID identifier. ...
OpenID auth: which method to get a unique identifier to use as key?
Using OpenID auth, which is the proper User instance method to get a unique identifier useful for creating and identifying a user on Datastore as key_name? Available methods : nickname() For OpenID users, the nickname is the OpenID identifier. federated_identity() Returns the user's OpenID identifier. federated_pr...
[ "You will probably want to generate your own user ID for within your system so that users can change their OpenID providers (or even have more than one OpenID associated with their account, which many sites support). But if you did want to use the OpenID as a unique key for some reason, I think federated_identity(...
[ 2 ]
[]
[]
[ "google_app_engine", "openid", "python" ]
stackoverflow_0003516241_google_app_engine_openid_python.txt
Q: How to reassign a string after removing parts of it by index I have a string s = 'texttexttextblahblah",".' and I want to cut of some of the rightmost characters by indexing and assign it to s so that s will be equal to texttexttextblahblah". I've looked around and found how to print by indexing, but not how to r...
How to reassign a string after removing parts of it by index
I have a string s = 'texttexttextblahblah",".' and I want to cut of some of the rightmost characters by indexing and assign it to s so that s will be equal to texttexttextblahblah". I've looked around and found how to print by indexing, but not how to reassign that actual variable to be trimmed.
[ "Just reassign what you printed to the variable.\n>>> s = 'texttexttextblahblah\",\".'\n>>> s = s[:-3]\n>>> s\n'texttexttextblahblah\"'\n>>>\n\nUnless you know exactly how many text and blah's you'll have, use .find() as Brent suggested (or .index(x), which is like find, except complains when it doesn't find x).\nI...
[ 16, 8, 5, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003516571_python_string.txt
Q: Can I execute sudo make install twice from different locations? I am on Mac, Snow Lepard. In preparation to install PIL I need to install libjpeg. So, from my home directory I did: tar zxvf jpegsrc.v6b.tar.gz cd jpeg-6b cp /usr/share/libtool/config/config.sub . cp /usr/share/libtool/config/config.guess . ./config...
Can I execute sudo make install twice from different locations?
I am on Mac, Snow Lepard. In preparation to install PIL I need to install libjpeg. So, from my home directory I did: tar zxvf jpegsrc.v6b.tar.gz cd jpeg-6b cp /usr/share/libtool/config/config.sub . cp /usr/share/libtool/config/config.guess . ./configure --enable-shared --enable-static make sudo make install But actua...
[ "The question doesn't really have much to do with Python...;-). Anyway, yes, repeating the same steps in a different directory should \"overwrite\" the installation you just performed.\n" ]
[ 2 ]
[]
[]
[ "libjpeg", "macos", "python", "python_imaging_library" ]
stackoverflow_0003516680_libjpeg_macos_python_python_imaging_library.txt
Q: Once I have identified the beginning and end parts of a section of an html document using lxml, how do I get everything between them I am working with some html files. I am trying to figure out a way to consistently get to some text that exists in the documents. I know that the section I want begins with some bo...
Once I have identified the beginning and end parts of a section of an html document using lxml, how do I get everything between them
I am working with some html files. I am trying to figure out a way to consistently get to some text that exists in the documents. I know that the section I want begins with some bolded words and I know that the section ends with other bolded words. bolded_item=atree.cssselect('b') myKeys=[item for item in bolded_ite...
[ "I'd suggest using SAX for this task.\nBasic docs are available at http://lxml.de/sax.html#producing-sax-events-from-an-elementtree-or-element\nYour handler should consume events w/out any action till it receives needed bolded item, and then it writes events into new buffer/tree/whatever till it receives terminatin...
[ 1, 0 ]
[]
[]
[ "html", "lxml", "parsing", "python" ]
stackoverflow_0003499242_html_lxml_parsing_python.txt
Q: Python Auto Fill with Mechanize Could someone help me or share some code to auto fill a login with mechanize (http://wwwsearch.sourceforge.net/mechanize/)? I want to make a python script to log me into my favorite sites when I run it. Thanks! A: This will help you to login to one site and download a page for exa...
Python Auto Fill with Mechanize
Could someone help me or share some code to auto fill a login with mechanize (http://wwwsearch.sourceforge.net/mechanize/)? I want to make a python script to log me into my favorite sites when I run it. Thanks!
[ "This will help you to login to one site and download a page for example:\nimport mechanize\nbr=mechanize.Browser()\nbr.open('http://www.yourfavoritesite.com')\nbr.select_form(nr=0) #check yoursite forms to match the correct number\nbr['Username']='Username' #use the proper input type=text name\nbr['Password']='Pas...
[ 3, 1 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0003516655_mechanize_python.txt
Q: Python, using two variables in getattr? I'm trying to do the following: import sys; sys.path.append('/var/www/python/includes') import functionname x = 'testarg' fn = "functionname" func = getattr(fn, fn) func (x) but am getting an error: "TypeError: getattr(): attribute name must be string" I have tried this ...
Python, using two variables in getattr?
I'm trying to do the following: import sys; sys.path.append('/var/www/python/includes') import functionname x = 'testarg' fn = "functionname" func = getattr(fn, fn) func (x) but am getting an error: "TypeError: getattr(): attribute name must be string" I have tried this before calling getattr but it still doesn't w...
[ "It sounds like you might be wanting locals() instead of getattr()... \nx = 'testarg'\nfn = \"functionname\"\nfunc = locals()[fn]\nfunc (x)\n\nYou should be using getattr when you have an object and you want to get an attribute of that object, not a variable from the local namespace.\n", "The first argument of ge...
[ 5, 0 ]
[]
[]
[ "function", "getattr", "python" ]
stackoverflow_0003516778_function_getattr_python.txt
Q: Extending python with C module So I have a C program to interface with an i2c device. I need to interface to that device from python. I'm just wondering if it's worth porting the program into a python module or if the amount of effort involved in porting won't outweigh just executing the program using subprocess. ...
Extending python with C module
So I have a C program to interface with an i2c device. I need to interface to that device from python. I'm just wondering if it's worth porting the program into a python module or if the amount of effort involved in porting won't outweigh just executing the program using subprocess. I know I'm sure it's different for e...
[ "There are many ways you can proceed -- the Python C API, which seems to be the one you're considering, but also SWIG, Cython, ctypes... as long as your existing C code can be made into a library (with functions callable \"from the outside\"), you have a wealth of options. Personally, I'd recommend Cython -- it's ...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "c", "i2c", "python", "python_module" ]
stackoverflow_0003517011_c_i2c_python_python_module.txt
Q: Modify CRUD Form in web2py before sending to view I cannot seem to find a way to modify a form that has been created via: from gluon.tools import Crud crud = Crud(globals(), db) form = crud.create(db.table_name) Since I am using foreign keys in my table, the auto-generated form only allows an integer (which repr...
Modify CRUD Form in web2py before sending to view
I cannot seem to find a way to modify a form that has been created via: from gluon.tools import Crud crud = Crud(globals(), db) form = crud.create(db.table_name) Since I am using foreign keys in my table, the auto-generated form only allows an integer (which represents the foreign primary key), but what I want to be ...
[ "You can use database validators to it.\nIt will show a select box with the values from foreign table:\n(from http://web2py.com/book/default/chapter/07?search=requires#Database-Validators):\nIS_IN_DB\nConsider the following tables and requirement:\ndb.define_table('person', Field('name', unique=True))\ndb.define_t...
[ 3 ]
[]
[]
[ "auto_generate", "crud", "foreign_keys", "python", "web2py" ]
stackoverflow_0003517072_auto_generate_crud_foreign_keys_python_web2py.txt
Q: Web2py ticket invalid links I started playing around with web2py the other day for a new project. I really like the structure and the whole concept which feels like a breath of fresh air after spending a few years with PHP frameworks. The only thing (currently) that is bothering me is the ticketing system. Each ti...
Web2py ticket invalid links
I started playing around with web2py the other day for a new project. I really like the structure and the whole concept which feels like a breath of fresh air after spending a few years with PHP frameworks. The only thing (currently) that is bothering me is the ticketing system. Each time I make a misstake a page with ...
[ "I was in the same boat as you, I did not like the default mechanism. Luckily, customized exception handling with web2py is very straightforward. Take a look at routes.py in the root of your web2py directory. I've added the following to mine:\nroutes_onerror = [('application_name/*','/application_name/error/inde...
[ 4, 0 ]
[]
[]
[ "admin", "https", "python", "web2py" ]
stackoverflow_0003505582_admin_https_python_web2py.txt
Q: Ctypes Offset Into A Buffer I have a string buffer: b = create_string_buffer(numb) where numb is a number of bytes. In my wrapper I need to splice up this buffer. When calling a function that expects a POINTER(c_char) I can do: myfunction(self, byref(b, offset)) but in a Structure: class mystruct(Structure): ...
Ctypes Offset Into A Buffer
I have a string buffer: b = create_string_buffer(numb) where numb is a number of bytes. In my wrapper I need to splice up this buffer. When calling a function that expects a POINTER(c_char) I can do: myfunction(self, byref(b, offset)) but in a Structure: class mystruct(Structure): _fields_ = [("buf", POINTER(c_cha...
[ "ctypes.cast\n>>> import ctypes\n>>> b = ctypes.create_string_buffer(500)\n>>> b[:6] = 'foobar'\n>>> ctypes.cast(ctypes.byref(b, 4), ctypes.POINTER(ctypes.c_char))\n<ctypes.LP_c_char object at 0x100756e60>\n>>> _.contents\nc_char('a')\n\n" ]
[ 3 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003517159_ctypes_python.txt
Q: Twisted: deferred that fires repeatedly? Deferreds are a great way to do asynchronous processing in Twisted. However, they, like the name implies, are for deferred computations, which only run and terminate once, firing the callbacks once. What if I have a repeated computation, like a button being clicked? Is ther...
Twisted: deferred that fires repeatedly?
Deferreds are a great way to do asynchronous processing in Twisted. However, they, like the name implies, are for deferred computations, which only run and terminate once, firing the callbacks once. What if I have a repeated computation, like a button being clicked? Is there any Deferred-like object that can fire repea...
[ "I've set this up for now. For my limited use case it does what I want.\nclass RepeatedDeferred:\n def __init__(self):\n self.callbacks = []\n\n self.df = defer.Deferred()\n\n def addCallback(self, callback):\n self.callbacks.append(callback)\n\n self.df.addCallback(callback)\n\n ...
[ 3, 1 ]
[]
[]
[ "callback", "multithreading", "python", "twisted" ]
stackoverflow_0003514529_callback_multithreading_python_twisted.txt
Q: Python raw literal string str = r'c:\path\to\folder\' # my comment IDE: Eclipse Python2.6 When the last character in the string is a backslash, it seems like it will escape the last single quote and treat my comment as part of the string. But the raw string is supposed to ignore all escape characters, right? W...
Python raw literal string
str = r'c:\path\to\folder\' # my comment IDE: Eclipse Python2.6 When the last character in the string is a backslash, it seems like it will escape the last single quote and treat my comment as part of the string. But the raw string is supposed to ignore all escape characters, right? What could be wrong? Thanks.
[ "Raw string literals don't treat backslashes as initiating escape sequences except when the immediately-following character is the quote-character that is delimiting the literal, in which case the backslash does escape it.\nThe design motivation is that raw string literals really exist only for the convenience of e...
[ 36, 9 ]
[]
[]
[ "python", "rawstring", "string" ]
stackoverflow_0003517802_python_rawstring_string.txt
Q: Python list function argument names Is there a way to get the parameter names a function takes? def foo(bar, buz): pass magical_way(foo) == ["bar", "buz"] A: Use the inspect module from Python's standard library (the cleanest, most solid way to perform introspection). Specifically, inspect.getargspec(f) ret...
Python list function argument names
Is there a way to get the parameter names a function takes? def foo(bar, buz): pass magical_way(foo) == ["bar", "buz"]
[ "Use the inspect module from Python's standard library (the cleanest, most solid way to perform introspection).\nSpecifically, inspect.getargspec(f) returns the names and default values of f's arguments -- if you only want the names and don't care about special forms *a, **k,\nimport inspect\n\ndef magical_way(f):\...
[ 72, 17 ]
[]
[]
[ "arguments", "function", "python" ]
stackoverflow_0003517892_arguments_function_python.txt
Q: Which format should I save my python script output? I have an executable (converted to exe from python using py2exe) that outputs lists of numbers that could be from 0-50K lines long or a little bit more. While developing, I just saved them to a TXT file using simple f.write. The person wants to print this output...
Which format should I save my python script output?
I have an executable (converted to exe from python using py2exe) that outputs lists of numbers that could be from 0-50K lines long or a little bit more. While developing, I just saved them to a TXT file using simple f.write. The person wants to print this output on paper! (don't ask why lol) So, I'm wondering if I can...
[ "CSV.\nhttp://docs.python.org/library/csv.html\nhttp://en.wikipedia.org/wiki/Comma-separated_values\nThey can load a spreadsheet and print anything they want.\n", "If you can't install anything on the computer, the you might be best off outputting an HTML file with the data in a <table> that the user could view/s...
[ 6, 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003515043_python.txt
Q: python function that modifies parameters def add(a,b): for i in range(len(a)): a[i] = a[i] + b def main(): amounts = [100,200] rate = 1 add(amounts,rate) print amounts main() The function add does not have a return. I read that changes are available to only mutable objects like list....
python function that modifies parameters
def add(a,b): for i in range(len(a)): a[i] = a[i] + b def main(): amounts = [100,200] rate = 1 add(amounts,rate) print amounts main() The function add does not have a return. I read that changes are available to only mutable objects like list. But why did the person omits the return? Eith...
[ "\nBut why did the person omits the\n return? Either with or without return\n is fine. Why? This is so different\n from C++.\n\nNot at all - it's identical to C++ to all intent and purposes! Just make, in the C++ version, a void add and pass its argument a, say a std::vector<int>, by reference -- to all intents...
[ 7, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003517860_python.txt
Q: drop into an interactive session to examine a failed unit test I'd like to be able to enter an interactive session, preferably with IPython, if a unit test fails. Is there an easy way to do this? edit: by "interactive session" I mean a full Python REPL rather than a pdb shell. edit edit: As a further explanation:...
drop into an interactive session to examine a failed unit test
I'd like to be able to enter an interactive session, preferably with IPython, if a unit test fails. Is there an easy way to do this? edit: by "interactive session" I mean a full Python REPL rather than a pdb shell. edit edit: As a further explanation: I'd like to be able to start an interactive session that has access...
[ "In IPython, use %pdb before running the test\nIn [9]: %pdb\nAutomatic pdb calling has been turned ON\n\n", "Nosetests runner provides --pdb option that will put you into the debugger session on errors or failures.\nhttp://nose.readthedocs.org/en/latest/usage.html\n" ]
[ 2, 1 ]
[ "Are you really sure you want to do this? Your unit tests should do one thing, should be well-named, and should clearly print what failed. If you do all of that, the failure message will pinpoint what went wrong; no need to go look at it interactively. In fact, one of the big advantages of TDD is that it helps y...
[ -2 ]
[ "interactive", "ipython", "python", "unit_testing" ]
stackoverflow_0003517410_interactive_ipython_python_unit_testing.txt
Q: When parsing html why do I need item.text sometimes and item.text_content() others Still learning lxml. I discovered that sometimes I cannot get to the text of an item from a tree using item.text. If I use item.text_content() I am good to go. I am not sure I see why yet. Any hints would be appreciated Okay I a...
When parsing html why do I need item.text sometimes and item.text_content() others
Still learning lxml. I discovered that sometimes I cannot get to the text of an item from a tree using item.text. If I use item.text_content() I am good to go. I am not sure I see why yet. Any hints would be appreciated Okay I am not sure exactly how to provide an example without making you handle a file: here is s...
[ "Accordng to the docs the text_content method:\n\nReturns the text content of the element, including the text content of\n its children, with no markup.\n\nSo for example,\nimport lxml.html as lh\ndata = \"\"\"<a><b><c>blah</c></b></a>\"\"\"\ndoc = lh.fromstring(data)\nprint(doc)\n# <Element a at b76eb83c>\n\ndoc ...
[ 12, 4 ]
[]
[]
[ "html", "lxml", "parsing", "python" ]
stackoverflow_0003517461_html_lxml_parsing_python.txt
Q: how to implement thin client app with pyqt Here is what I would like to do, and I want to know how some people with experience in this field do this: With three POST requests I get from the http server: widgets and layout and then app logic (minimal) data Or maybe it's better to combine the first two or all thre...
how to implement thin client app with pyqt
Here is what I would like to do, and I want to know how some people with experience in this field do this: With three POST requests I get from the http server: widgets and layout and then app logic (minimal) data Or maybe it's better to combine the first two or all three. I'm thinking of using pyqt. I think I can loa...
[ "Your desire to send \"app logic\" from the server to the client without sending \"code\" is inherently self-contradictory, though you may not realize that yet -- even if the \"logic\" you're sending is in some simplified ad-hoc \"language\" (which you don't even think of as a language;-), to all intents and purpos...
[ 1, 1 ]
[]
[]
[ "networking", "pyqt", "python", "qt", "thin" ]
stackoverflow_0003517841_networking_pyqt_python_qt_thin.txt
Q: How do you override a the save method in Django and raise proper errors that will be caught by the Admin interface? I'm a little stumped here, I can't find what I'm looking for in the Django docs... What I want, is to be able to override the Save method of an Model. I want it to check for a certain set of conditio...
How do you override a the save method in Django and raise proper errors that will be caught by the Admin interface?
I'm a little stumped here, I can't find what I'm looking for in the Django docs... What I want, is to be able to override the Save method of an Model. I want it to check for a certain set of conditions - if these conditions are met, it will create the object just fine, but if the conditions are not met, I want to raise...
[ "\nI want ... to check for a certain set of conditions - if these conditions are met, it will create the object just fine, but if the conditions are not met, I want to raise an error. \n\nThis is what a ModelForm is for.\nhttp://docs.djangoproject.com/en/dev/topics/forms/modelforms/\n", "I'm not 100% sure, but I ...
[ 1, 1 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0003516227_django_django_admin_django_models_python.txt
Q: grouping strings by substring in mysql/python or mysql/.net the data will be stored in a mysql database like this: 5911 CD $4.99 Eben, Landscapes of Patmos {w.Martin Lenniger, percussion}; 2 Choral Phantasies; Laudes. (All w.Sieglinde Ahrens, organ) 5913 CD $5.99 Turina, Sevilliana; Rafaga; Hommage a T...
grouping strings by substring in mysql/python or mysql/.net
the data will be stored in a mysql database like this: 5911 CD $4.99 Eben, Landscapes of Patmos {w.Martin Lenniger, percussion}; 2 Choral Phantasies; Laudes. (All w.Sieglinde Ahrens, organ) 5913 CD $5.99 Turina, Sevilliana; Rafaga; Hommage a Tarrega; Sonata. Rodrigo, 3 Piezas Espanolas; En Los Trigales; Sar...
[ "Re (2), what you want are called \"stopwords\" -- e.g., in NLTK (which is Python, but I imagine there will be C# equivalents), per chapter 2 in its excellent online book, \n>>> from nltk.corpus import stopwords\n>>> stopwords.words('english')\n['a', \"a's\", 'able', 'about', 'above', 'according', 'accordingly', 'a...
[ 2 ]
[]
[]
[ "c#", "mysql", "python" ]
stackoverflow_0003518375_c#_mysql_python.txt
Q: Linking a static library into Boost Python (shared library) - Import Error I am building a Boost Python module (.so shared library file) which depends on another external library (STXXL) While I can build and import the example Boost Python modules, I run into problems when STXXL is thrown into the mix. Specifica...
Linking a static library into Boost Python (shared library) - Import Error
I am building a Boost Python module (.so shared library file) which depends on another external library (STXXL) While I can build and import the example Boost Python modules, I run into problems when STXXL is thrown into the mix. Specifically when running import fast_parts in python I get ImportError: ./fast_parts.so:...
[ "I'm assuming Linux, please comment if this is incorrect. What does the ldd output for libfast_parts.so look like? Does it indicate libstxxl.so is not found?\nYou might need to add /home/zenna/Downloads/stxxl-1.3.0/lib/ in your LD_LIBRARY_PATH or the rpath for libfast_parts.so.\n-Wl,-rpath,/home/zenna/Downloads/stx...
[ 0 ]
[]
[]
[ "boost", "c++", "compilation", "linker", "python" ]
stackoverflow_0003518069_boost_c++_compilation_linker_python.txt
Q: Dealing with context classes in Python 2.4 I'm trying to use the python-daemon module. It supplies the daemon.DaemonContext class to properly daemonize a script. Although I'm primarily targeting Python 2.6+, I'd like to maintain backwards compatibility to version 2.4. Python 2.5 supports importing contexts from fu...
Dealing with context classes in Python 2.4
I'm trying to use the python-daemon module. It supplies the daemon.DaemonContext class to properly daemonize a script. Although I'm primarily targeting Python 2.6+, I'd like to maintain backwards compatibility to version 2.4. Python 2.5 supports importing contexts from future, but Python 2.4 has no such facility. I fig...
[ "SyntaxError is diagnosed by the Python compiler as it compiles -- you're presumably trying to \"catch\" it from code that's being compiled as part of the same module (e.g., that's what you're doing in your code sample), so of course it won't work -- your \"catching\" code hasn't been compiled yet (because compilat...
[ 3 ]
[]
[]
[ "backwards_compatibility", "python", "with_statement" ]
stackoverflow_0003518472_backwards_compatibility_python_with_statement.txt
Q: Iterate across arbitrary dimension in numpy I have a multidimensional numpy array, and I need to iterate across a given dimension. Problem is, I won't know which dimension until runtime. In other words, given an array m, I could want m[:,:,:,i] for i in xrange(n) or I could want m[:,:,i,:] for i in xrange(n) etc...
Iterate across arbitrary dimension in numpy
I have a multidimensional numpy array, and I need to iterate across a given dimension. Problem is, I won't know which dimension until runtime. In other words, given an array m, I could want m[:,:,:,i] for i in xrange(n) or I could want m[:,:,i,:] for i in xrange(n) etc. I imagine that there must be a straightforward ...
[ "There are many ways to do this. You could build the right index with a list of slices, or perhaps alter m's strides. However, the simplest way may be to use np.swapaxes:\nimport numpy as np\nm=np.arange(24).reshape(2,3,4)\nprint(m.shape)\n# (2, 3, 4)\n\nLet axis be the axis you wish to loop over. m_swapped is the ...
[ 6, 5 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003513424_numpy_python.txt
Q: Generating a set random list of integers based on a distribution I hope I can explain this well, if I don't I'll try again. I want to generate an array of 5 random numbers that all add up to 10 but whose allocation are chosen on an interval of [0,2n/m]. I'm using numpy. The code I have so far looks like this: impo...
Generating a set random list of integers based on a distribution
I hope I can explain this well, if I don't I'll try again. I want to generate an array of 5 random numbers that all add up to 10 but whose allocation are chosen on an interval of [0,2n/m]. I'm using numpy. The code I have so far looks like this: import numpy as np n=10 m=5 #interval that numbers are generated on randN...
[ "Just generate four of the numbers using the technique above, then subtract the sum of the four from 10 to pick the last number.\n", "This generates all the possible combinations that sum to 10 and selects a random one\nfrom itertools import product\nfrom random import choice\nn=10\nm=5\nfinalList = choice([x for...
[ 1, 1 ]
[]
[]
[ "algorithm", "python", "random" ]
stackoverflow_0003518597_algorithm_python_random.txt
Q: Scrapy web scraper can not crawl link I'm very new to Scrapy. Here my spider to crawl twistedweb. class TwistedWebSpider(BaseSpider): name = "twistedweb3" allowed_domains = ["twistedmatrix.com"] start_urls = [ "http://twistedmatrix.com/documents/current/web/howto/", ] rules = ( ...
Scrapy web scraper can not crawl link
I'm very new to Scrapy. Here my spider to crawl twistedweb. class TwistedWebSpider(BaseSpider): name = "twistedweb3" allowed_domains = ["twistedmatrix.com"] start_urls = [ "http://twistedmatrix.com/documents/current/web/howto/", ] rules = ( Rule(SgmlLinkExtractor(), 'p...
[ "rules attribute belongs to CrawlSpider.Use class MySpider(CrawlSpider).\nAlso, when you use CrawlSpider you must not override parse method,\ninstead use parse_response or other similar name.\n" ]
[ 4 ]
[]
[]
[ "python", "scrapy", "screen_scraping" ]
stackoverflow_0003518303_python_scrapy_screen_scraping.txt
Q: Comma seperated file that I want to load into a dictionary I have a comma seperated file, a row looks like: "ABC234234", 23 I want to load this into a dictionary, with the key being the first part i.e. "ABC234234" I have to remote the double quotes also. What's the pythonic way of doing this? A: I would suggest ...
Comma seperated file that I want to load into a dictionary
I have a comma seperated file, a row looks like: "ABC234234", 23 I want to load this into a dictionary, with the key being the first part i.e. "ABC234234" I have to remote the double quotes also. What's the pythonic way of doing this?
[ "I would suggest (like always) opening the CSV file with the with statement (which ensures it will be closed when you're done!) -- apart from that, @carl's answer is generally fine:\nimport csv\n\nwith open('yourfile.csv', 'rb') as f:\n thedict = dict(csv.reader(f))\n\nand then freely use thedict as you require....
[ 6, 4, 3 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003518722_dictionary_python.txt
Q: Java text extraction and data structure design I have a huge set of data of tables in Open Office 3.0 document format. Table 1: (x range)|(x1,y1) |(x2,y2)|(x3,x3)|(x4,y4) (-20,90) |(-20,0) |(-5,1) |(5,1) |(10,0) ... Like wise i have n number of tables.All of these tables are fuzzy set membership ...
Java text extraction and data structure design
I have a huge set of data of tables in Open Office 3.0 document format. Table 1: (x range)|(x1,y1) |(x2,y2)|(x3,x3)|(x4,y4) (-20,90) |(-20,0) |(-5,1) |(5,1) |(10,0) ... Like wise i have n number of tables.All of these tables are fuzzy set membership functions.In simple terms they are computational mod...
[ "In order to parse an OpenOffice Document in Java (to extract data), you can use a dedicated API such as ODFDOM.\nI think this solution is very complicated for what you need. A easier solution would be to extract manually the OpenOffice table, to put it in a format more friendly to parse in Java:\n\nCSV\nDataBase (...
[ 1 ]
[]
[]
[ "data_structures", "java", "python", "serialization", "text_extraction" ]
stackoverflow_0003519015_data_structures_java_python_serialization_text_extraction.txt
Q: python string conversion for eval I have list like: ['name','country_id', 'price','rate','discount', 'qty'] and a string expression like exp = 'qty * price - discount + 100' I want to convert this expression into exp = 'obj.qty * obj.price - obj.discount + 100' as I wanna eval this expression like eval(exp or F...
python string conversion for eval
I have list like: ['name','country_id', 'price','rate','discount', 'qty'] and a string expression like exp = 'qty * price - discount + 100' I want to convert this expression into exp = 'obj.qty * obj.price - obj.discount + 100' as I wanna eval this expression like eval(exp or False, dict(obj=my_obj)) my question is ...
[ "Of course you have to be very careful using eval. Would be interesting to know why you need to use eval for this at all\nThis way makes it harder for something bad to happen if a malicious user finds a way to put non numeric data in the fields\nimport re\nexp = 'qty * price - discount + 100'\nexp = re.sub('(qty|pr...
[ 2, 1, 1 ]
[]
[]
[ "eval", "expression", "python", "regex", "string" ]
stackoverflow_0003519074_eval_expression_python_regex_string.txt
Q: Why Does Looping Beat Indexing Here? A few years ago, someone posted on Active State Recipes for comparison purposes, three python/NumPy functions; each of these accepted the same arguments and returned the same result, a distance matrix. Two of these were taken from published sources; they are both--or they appe...
Why Does Looping Beat Indexing Here?
A few years ago, someone posted on Active State Recipes for comparison purposes, three python/NumPy functions; each of these accepted the same arguments and returned the same result, a distance matrix. Two of these were taken from published sources; they are both--or they appear to me to be--idiomatic numpy code. The ...
[ "TL; DR The second code above is only looping over the number of dimensions of the points (3 times through the for loop for 3D points) so the looping isn't much there. The real speed-up in the second code above is that it better harnesses the power of Numpy to avoid creating some extra matrices when finding the dif...
[ 11, 1 ]
[]
[]
[ "memory_management", "numpy", "performance", "python" ]
stackoverflow_0003518574_memory_management_numpy_performance_python.txt
Q: Looking for strong/explicit-typed language without GIL Are there any languages which feature static type checking like in C++ with modern syntax like in Python, and does not have GIL? I belive, Python 3 with ability to explicitly declare type of each variable would be 'almost there', but GIL makes me sad. Java is ...
Looking for strong/explicit-typed language without GIL
Are there any languages which feature static type checking like in C++ with modern syntax like in Python, and does not have GIL? I belive, Python 3 with ability to explicitly declare type of each variable would be 'almost there', but GIL makes me sad. Java is nice, but I need something more 'embedable' without bulky JR...
[ "Boo\n\nBoo is an object oriented, statically\n typed programming language that seeks\n to make use of the Common Language\n Infrastructure's support for Unicode,\n internationalization and web\n applications, while using a\n Python-inspired syntax and a\n special focus on language and compiler\n extensibi...
[ 4, 4, 3, 2, 2 ]
[]
[]
[ "gil", "java", "python" ]
stackoverflow_0003511922_gil_java_python.txt
Q: How to implement Google-style pagination on app engine? See the pagination on the app gallery? It has page numbers and a 'start' parameter which increases with the page number. Presumably this app was made on GAE. If so, how did they do this type of pagination? ATM I'm using cursors but passing them around in URLs...
How to implement Google-style pagination on app engine?
See the pagination on the app gallery? It has page numbers and a 'start' parameter which increases with the page number. Presumably this app was made on GAE. If so, how did they do this type of pagination? ATM I'm using cursors but passing them around in URLs is as ugly as hell.
[ "Ben Davies's outstanding PagedQuery class will do everything that you want and more.\n", "You can simply pass in the 'start' parameter as an offset to the .fetch() call on your query. This gets less efficient as people dive deeper into the results, but if you don't expect people to browse past 1000 or so, it's m...
[ 1, 1 ]
[]
[]
[ "bigtable", "google_app_engine", "google_cloud_datastore", "pagination", "python" ]
stackoverflow_0003514230_bigtable_google_app_engine_google_cloud_datastore_pagination_python.txt
Q: Exception handling in Python http://docs.python.org/library/imaplib.html states that: exception IMAP4.error Exception raised on any errors. The reason for the exception is passed to the constructor as a string. What does "exception is passed to the constructor as a string" mean? What would the code look li...
Exception handling in Python
http://docs.python.org/library/imaplib.html states that: exception IMAP4.error Exception raised on any errors. The reason for the exception is passed to the constructor as a string. What does "exception is passed to the constructor as a string" mean? What would the code look like that can print the reason.
[ "Just use print str(exception).\n", "You can specify the reason when constructing the exception yourself, and put it into a variable when catching the exception.\ntry:\n raise imaplib.IMAP4.error('Some exception')\nexcept imaplib.IMAP4.error, error:\n print error\n\n" ]
[ 2, 1 ]
[]
[]
[ "exception", "exception_handling", "python" ]
stackoverflow_0003519494_exception_exception_handling_python.txt
Q: Python Regex, re.sub, replacing multiple parts of pattern? I can't seem to find a good resource on this.. I am trying to do a simple re.place I want to replace the part where its (.*?), but can't figure out the syntax on how to do this.. I know how to do it in PHP, so I've been messing around with what I think it ...
Python Regex, re.sub, replacing multiple parts of pattern?
I can't seem to find a good resource on this.. I am trying to do a simple re.place I want to replace the part where its (.*?), but can't figure out the syntax on how to do this.. I know how to do it in PHP, so I've been messing around with what I think it could be based on that (which is why it has the $1 but I know th...
[ ">>> import re\n>>> originalstring = 'fksf var:asfkj;'\n>>> pattern = '.*?var:(.*?);'\n>>> pattern_obj = re.compile(pattern, re.MULTILINE)\n>>> replacement_string=\"\\\\1\" + 'test'\n>>> pattern_obj.sub(replacement_string, originalstring)\n'asfkjtest'\n\nEdit: The Python Docs can be pretty useful reference.\n", "...
[ 19, 7 ]
[ "The python docs are online, and the one for the re module is here. http://docs.python.org/library/re.html\nTo answer your question though, Python uses \\1 rather than $1 to refer to matched groups.\n" ]
[ -2 ]
[ "python", "regex" ]
stackoverflow_0003519487_python_regex.txt
Q: Validating an XMPP jid with python? What is the correct way to validate an xmpp jid? The syntax is described here:, but I don't really understand it. Also, it seems pretty complicated, so using a library to do it would seem like a good idea. I'm currently using xmpppy, but I can't seem to find how to validate a ji...
Validating an XMPP jid with python?
What is the correct way to validate an xmpp jid? The syntax is described here:, but I don't really understand it. Also, it seems pretty complicated, so using a library to do it would seem like a good idea. I'm currently using xmpppy, but I can't seem to find how to validate a jid with it. Any help appreciated!
[ "First off, the current best reference for JIDs is RFC 6122.\nI was just going to give you the regex in here, but got a little carried away, and implemented all of the spec:\nimport re\nimport sys\nimport socket\nimport encodings.idna\nimport stringprep\n\n# These characters aren't allowed in domain names that are ...
[ 20 ]
[]
[]
[ "python", "validation", "xmpp" ]
stackoverflow_0003514342_python_validation_xmpp.txt
Q: Writing python client for SOAP with suds I want to convert a perl SOAP client into a python SOAP client. The perl client is initialized like $url = 'https://host:port/cgi-devel/Service.cgi'; $uri = 'https://host/Service'; my $soap = SOAP::Lite -> uri($uri) -> proxy($url); I tried to replicate this in py...
Writing python client for SOAP with suds
I want to convert a perl SOAP client into a python SOAP client. The perl client is initialized like $url = 'https://host:port/cgi-devel/Service.cgi'; $uri = 'https://host/Service'; my $soap = SOAP::Lite -> uri($uri) -> proxy($url); I tried to replicate this in python 2.4.2 with suds 0.3.6 doing from suds.cli...
[ "urllib2 module doesn't add Content-Length (required for POST method) header automatically when Request object is constructed manually as suds does. You have to patch suds, probably suds.transport.HttpTransport.open() method or suds.transport.Request class.\n", "I had the same error, then switched to using a loca...
[ 3, 3, 0 ]
[]
[]
[ "https", "python", "soap", "suds" ]
stackoverflow_0001476814_https_python_soap_suds.txt
Q: How can I speed up update/replace operations in PostgreSQL? We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects). For sanity rea...
How can I speed up update/replace operations in PostgreSQL?
We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects). For sanity reasons we have created our own Data Mapper-like layer that works re...
[ "The usual way I do these things in pg is: load raw data matching target table into temp table (no constraints) using copy, merge(the fun part), profit.\nI wrote a merge_by_key function specifically for these situations:\nhttp://mbk.projects.postgresql.org/\nThe docs aren't terribly friendly, but I'd suggest giving...
[ 4, 2, 2, 1, 1, 1 ]
[]
[]
[ "postgresql", "psycopg2", "python", "sql" ]
stackoverflow_0000962361_postgresql_psycopg2_python_sql.txt
Q: How to convert unicode objects to normal objects in Python I currently have a deep object, and it is all unicode (sadly). I am to a point where a variable is either going to be a dict, or a bool. In this case, I do if type( my_variable ) is BooleanType: But this is not triggered because the type is actually Unicod...
How to convert unicode objects to normal objects in Python
I currently have a deep object, and it is all unicode (sadly). I am to a point where a variable is either going to be a dict, or a bool. In this case, I do if type( my_variable ) is BooleanType: But this is not triggered because the type is actually Unicode for all values. How do I convert this unicode object to a norm...
[ "Do not use type unless you are really really sure that you want to.\nIn this case, you don't -- especially checking for bool, given Python's flexibility for what can be considered as boolean! For instance, what if you are given None? How about an empty string? How about []?\nThe solution to this problem is the use...
[ 1, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0003520120_python_unicode.txt
Q: Set Host-header when using Python and urllib2 I'm using my own resolver and would like to use urllib2 to just connect to the IP (no resolving in urllib2) and I would like set the HTTP Host-header myself. But urllib2 is just ignoring my Host-header: txheaders = { 'User-Agent': UA, "Host: ": nohttp_url } robots = ur...
Set Host-header when using Python and urllib2
I'm using my own resolver and would like to use urllib2 to just connect to the IP (no resolving in urllib2) and I would like set the HTTP Host-header myself. But urllib2 is just ignoring my Host-header: txheaders = { 'User-Agent': UA, "Host: ": nohttp_url } robots = urllib2.Request("http://" + ip + "/robots.txt", txda...
[ "You have included \": \" in the \"Host\" string.\ntxheaders = { \"User-Agent\": UA, \"Host\": nohttp_url }\nrobots = urllib2.Request(\"http://\" + ip + \"/robots.txt\", txdata, txheaders)\n\n" ]
[ 10 ]
[]
[]
[ "http", "python", "urllib2" ]
stackoverflow_0003520966_http_python_urllib2.txt
Q: How do I schedule a Python script to run as long as Windows XP is running? I wrote a temperature logger Python script and entered it as a scheduled task in Windows XP. It has the following command line: C:\Python26\pythonw.exe "C:\path\to\templogger.py" It writes data to a file in local public folder (e.g. fully...
How do I schedule a Python script to run as long as Windows XP is running?
I wrote a temperature logger Python script and entered it as a scheduled task in Windows XP. It has the following command line: C:\Python26\pythonw.exe "C:\path\to\templogger.py" It writes data to a file in local public folder (e.g. fully accessible by all who login locally). So far, I was able to achieve this object...
[ "Is it possible to run a Python script as a service in Windows? If possible, how?\nhttp://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html\n", "Your scenario is exactly the required use case for a service, unfortunately tasks are ill suited for what you are looking to do. That said writing ...
[ 3, 2 ]
[]
[]
[ "python", "scheduled_tasks", "windows_xp" ]
stackoverflow_0003520900_python_scheduled_tasks_windows_xp.txt
Q: pyGTK detect all window move events I'm trying to capture the configure-event for every window to create a windows 7-esque snap feature. I know there are solutions involving compiz-fusion, but my installation is running within vmware and doesn't have hardware acceleration to run compiz. I figured a simple python s...
pyGTK detect all window move events
I'm trying to capture the configure-event for every window to create a windows 7-esque snap feature. I know there are solutions involving compiz-fusion, but my installation is running within vmware and doesn't have hardware acceleration to run compiz. I figured a simple python script could do what I wanted, but I can't...
[ "A quick search reveals this page, which, though written in C, communicates the basics pretty well (you'll have to grep it to find for \"Moving Window\")\nThe configure-event is binded to your application's window. \nTo do what you're going to want to do, you'll also have to find out the screen size, which resides ...
[ 1 ]
[]
[]
[ "events", "linux", "pygtk", "python" ]
stackoverflow_0003128536_events_linux_pygtk_python.txt
Q: Class menu in Tkinter Gui I'm working on a Gui and I'd like to know if it is possible to make the menu property of a window a separate class on my script for a clearer and more enhancement prone code. my code currently is : class Application(Frame): """ main window application """ def __init__(self, boss = N...
Class menu in Tkinter Gui
I'm working on a Gui and I'd like to know if it is possible to make the menu property of a window a separate class on my script for a clearer and more enhancement prone code. my code currently is : class Application(Frame): """ main window application """ def __init__(self, boss = None): (...) self.menu = M...
[ "Yes, it's possible:\nimport tkinter as tk\n# import Tkinter as tk # if using python 2\nimport sys\n\nclass MenuBar(tk.Menu):\n def __init__(self, parent):\n tk.Menu.__init__(self, parent)\n\n fileMenu = tk.Menu(self, tearoff=False)\n self.add_cascade(label=\"File\",underline=0, menu=fileMe...
[ 14 ]
[]
[]
[ "class", "menu", "python", "tkinter", "user_interface" ]
stackoverflow_0003520494_class_menu_python_tkinter_user_interface.txt
Q: Does Python support something like literal objects? In Scala I could define an abstract class and implement it with an object: abstrac class Base { def doSomething(x: Int): Int } object MySingletonAndLiteralObject extends Base { override def doSomething(x: Int) = x*x } My concrete example in Python: clas...
Does Python support something like literal objects?
In Scala I could define an abstract class and implement it with an object: abstrac class Base { def doSomething(x: Int): Int } object MySingletonAndLiteralObject extends Base { override def doSomething(x: Int) = x*x } My concrete example in Python: class Book(Resource): path = "/book/{id}" def get(r...
[ "Use a decorator to convert the inherited class to an object at creation time\nI believe that the concept of such an object is not a typical way of coding in Python, but if you must then the decorator class_to_object below for immediate initialisation will do the trick. Note that any parameters for object initialis...
[ 7, 2, 1 ]
[]
[]
[ "object_literal", "oop", "python", "scala", "singleton" ]
stackoverflow_0003520052_object_literal_oop_python_scala_singleton.txt
Q: Retrieving stdout from subprocess in Windows I can call FFmpeg with subprocess.Popen and retrieve the data I need, as it occurs (to get progress), but only in console. I've looked around and seen that you can't get the data "live" when running with pythonw. Yet, waiting until the process finishes to retrieve the d...
Retrieving stdout from subprocess in Windows
I can call FFmpeg with subprocess.Popen and retrieve the data I need, as it occurs (to get progress), but only in console. I've looked around and seen that you can't get the data "live" when running with pythonw. Yet, waiting until the process finishes to retrieve the data is moot, since I'm trying to wrap a PyQT GUI a...
[ "process = subprocess.Popen(your_cmd, shell=true, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n\ncount=0\nwhile True:\n buff = process.stdout.readline()\n\n if buff == '':\n count += 1\n\n if buff == '' and process.poll() != None:\n break\n\n sys.stdout.wr...
[ 4, 0 ]
[]
[]
[ "ffmpeg", "pyqt", "python", "subprocess", "windows" ]
stackoverflow_0003521887_ffmpeg_pyqt_python_subprocess_windows.txt
Q: Django mod-python error Can someone please tell what this strange error is Mod_python error: "PythonHandler django.core.handlers.modpython" Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 287, in HandlerDispatch log=debug) File "/usr/lib/python2.4/site-p...
Django mod-python error
Can someone please tell what this strange error is Mod_python error: "PythonHandler django.core.handlers.modpython" Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 287, in HandlerDispatch log=debug) File "/usr/lib/python2.4/site-packages/mod_python/apache.py"...
[ "That you're missing the Cookie package (which is not part of Django), but it should be Builtin. \nIf you're using Python 3 please note that Cookie has been renamed to http.cookies, and that Django is incompatible with Python not 2.x.\nThat is what you're missing: http://docs.python.org/library/cookie.html.\nEdit\n...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003522029_django_python.txt
Q: html to text conversion using python language I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML...
html to text conversion using python language
I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, b...
[ "you would need to use urllib2 python library to get the html from the website and then parse through the html to grab the text that you want. \nUse BeautifulSoup to parse through the html\nimport BeautifulSoup\nresp = urllib2.urlopen(\"http://stackoverflow.com\")\nrawhtml = resp.read()\n#parse through html to get ...
[ 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003521999_python.txt
Q: Django Template Syntax Error in Google App Engine I tried launching my Google App Engine app on localhost, and got a Django error I am stuck on. "TemplateSyntaxError: Template 'base/_base.html' cannot be extended, because it doesn't exist" I put the templates in a /templates, and then _base.html & index.html in /...
Django Template Syntax Error in Google App Engine
I tried launching my Google App Engine app on localhost, and got a Django error I am stuck on. "TemplateSyntaxError: Template 'base/_base.html' cannot be extended, because it doesn't exist" I put the templates in a /templates, and then _base.html & index.html in /templates/base . Thanks! Emile @ proudn00b.com The Erro...
[ "Another thing you can double check is to make sure one of the paths in the TEMPLATE_DIRS setting points to the root directory for your templates. \nAlso make sure it's a full absolute path in the setting, not relative to the project.\n", "I think you need to look in your templates. The important part of the tra...
[ 1, 0, 0 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0003516918_django_templates_google_app_engine_python.txt
Q: Loading mako templates from files I'm new to python and currently trying to use mako templating. I want to be able to take an html file and add a template to it from another html file. Let's say I got this index.html file: <html> <head> <title>Hello</title> </head> <body> <p>Hello, ${name}!</p> </body> <...
Loading mako templates from files
I'm new to python and currently trying to use mako templating. I want to be able to take an html file and add a template to it from another html file. Let's say I got this index.html file: <html> <head> <title>Hello</title> </head> <body> <p>Hello, ${name}!</p> </body> </html> and this name.html file: world ...
[ "return mytemplate.render(name=open(<path-to-file>).read())\n\n", "Thanks for the replies.\nThe idea is to use the mako framework since it does things like cache and check if the file has been updated...\nthis code seems to eventually work:\n@route(':filename')\ndef static_file(filename): \n mylookup = Temp...
[ 2, 2, 1 ]
[]
[]
[ "mako", "python", "templates" ]
stackoverflow_0003521629_mako_python_templates.txt
Q: Removing broken tags and poorly formatted html from some text i have a huge database of scraped forum posts that i am inserting into a website. however alot of people try to use html in their forum posts and often times do it wrong. because of this, there are always stray <strike> <b> </strike> </div> </b> tags i...
Removing broken tags and poorly formatted html from some text
i have a huge database of scraped forum posts that i am inserting into a website. however alot of people try to use html in their forum posts and often times do it wrong. because of this, there are always stray <strike> <b> </strike> </div> </b> tags in the posts which will end up messing up the webpage format when i ...
[ "Have a look at HTML Tidy\nThere is a also a Python wrapper lib: µTidylib\nAlternatively there is HTML Purifier\n", "Beautiful Soup does a decent job at HTML cleanup.\n", "Look at lxml also.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "html_parsing", "python" ]
stackoverflow_0003522058_html_parsing_python.txt
Q: Python Server Help I have written a small HTTP server and everything is working fine locally, but I am not able to connect to the server from any other computer, including other computers on the network. I'm not sure if it is a server problem, or if I just need to make some adjustments to Windows. I turned the fir...
Python Server Help
I have written a small HTTP server and everything is working fine locally, but I am not able to connect to the server from any other computer, including other computers on the network. I'm not sure if it is a server problem, or if I just need to make some adjustments to Windows. I turned the firewall off, so that can't...
[ "Without any code sample I can only assume that your server is listening on some private interface like localhost/127.0.0.1 and not something that is connected to the rest of your network.\n", "Some things to check:\n\nCan you connect to the server via your machine's IP instead of localhost? I.e. if your machine ...
[ 2, 0 ]
[]
[]
[ "http", "python", "windows" ]
stackoverflow_0003522641_http_python_windows.txt
Q: How to get the name of dir from where a python script is called (not exaclty where it ran) I have a Python script, named script.py. It's located on ~/scripts/script.py. I have an alias in ~/.bash_aliases: alias script='python ~/scripts/script.py' I have some directories in a checked out repository, for example: ~...
How to get the name of dir from where a python script is called (not exaclty where it ran)
I have a Python script, named script.py. It's located on ~/scripts/script.py. I have an alias in ~/.bash_aliases: alias script='python ~/scripts/script.py' I have some directories in a checked out repository, for example: ~/repository/project_dir/module_name/ I run on my terminal, inside ~/repository/project_dir/modu...
[ "import os\nprint os.getcwd()\n\nFor more details, check out the python docs.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003522785_python.txt
Q: Rotating images using PHP and jQuery the fast way I wrote a python script that rotates an image 90 degrees. I am including the python code in case you want to see it; #! /usr/bin/python # This Python file uses the following encoding: utf-8 #argv[1] needs to be send formatted meaning spaces and paranthesis ARE pro...
Rotating images using PHP and jQuery the fast way
I wrote a python script that rotates an image 90 degrees. I am including the python code in case you want to see it; #! /usr/bin/python # This Python file uses the following encoding: utf-8 #argv[1] needs to be send formatted meaning spaces and paranthesis ARE problems __author__="john" __date__ ="$Aug 17, 2010 1:48...
[ "If you are happy to do this just in the browser, the tricks in this article will let you rotate any html content, including image tags.\n-webkit-transform: rotate(-90deg); \n-moz-transform: rotate(-90deg); \nfilter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);\n\n", "You seem to be creating the rota...
[ 1, 0, 0 ]
[]
[]
[ "image", "jquery", "php", "python", "rotation" ]
stackoverflow_0003522739_image_jquery_php_python_rotation.txt
Q: Python 2 or Python 3 as the student's first language Which is more suited as the platform for a first course in computing: Python 2 or Python 3? Reason for asking your opinion: Python 2 is used in the vast majority of installations worlwide, but Python 3 is the coming thing. A: Teach them both (imho). Teach the...
Python 2 or Python 3 as the student's first language
Which is more suited as the platform for a first course in computing: Python 2 or Python 3? Reason for asking your opinion: Python 2 is used in the vast majority of installations worlwide, but Python 3 is the coming thing.
[ "Teach them both (imho).\nTeach the Python 2 (in the most pythonic way) and than present your students the 2to3 changes, and their meaning (print \"string\" => print(\"string\") why?)\nBy the way, if you use 2.7 http://docs.python.org/dev/library/stdtypes.html#memoryview is an interesting new feature!\n", "I woul...
[ 6, 4, 3, 0, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003522380_python_python_3.x.txt
Q: Problem with pyflakes in emacs on Windows I followed this link here to try and set up emacs for python dev on windows. Although everything seems fine, pyflakes is creating problems and not giving me the syntax checking. Everytime I open a '.py' file, I get the error "Failed to launch syntax check process 'pyflakes...
Problem with pyflakes in emacs on Windows
I followed this link here to try and set up emacs for python dev on windows. Although everything seems fine, pyflakes is creating problems and not giving me the syntax checking. Everytime I open a '.py' file, I get the error "Failed to launch syntax check process 'pyflakes' with args 'foo.py': searching for program: No...
[ "Got it to work finally!\nThanks to phils for pointing me in the right direction. After googling, found this and with the help of google translator (The page is in Russian) was able to finally get syntax checking to work!\nDetails in english:\nAfter installing pyflakes the usual way, do the following:\n\nCreate fil...
[ 5, 2 ]
[]
[]
[ "emacs", "pyflakes", "python" ]
stackoverflow_0003513975_emacs_pyflakes_python.txt
Q: Quickly remove first n lines from many text files I need to create an output text file by deleting the first two lines of the input file. At the moment I'm using sed "1,2d" input.txt > output.txt I need to do this for thousands of files, so am using python: import os for filename in somelist: os.system('sed "1,2...
Quickly remove first n lines from many text files
I need to create an output text file by deleting the first two lines of the input file. At the moment I'm using sed "1,2d" input.txt > output.txt I need to do this for thousands of files, so am using python: import os for filename in somelist: os.system('sed "1,2d" %s-in.txt > %s-out.txt'%(filename,filename)) but th...
[ "Use tail. Doubt anything could be significantly faster:\ntail -n +3 input.txt > output.txt\n\nWrap it in your loop of choice. But I really doubt sed is a whole ton slower - as you say, disk i/o is usually the ultimate bottleneck.\n", "I think this will be faster than launching sed:\nimport os\nimport shutil\n\np...
[ 10, 4, 3 ]
[]
[]
[ "file_io", "performance", "python", "sed" ]
stackoverflow_0003521812_file_io_performance_python_sed.txt
Q: Google App Engine, Python and IPython I want to use IPython under GAE to debug scripts locally: import ipdb; ipdb.set_trace() but GAE restricts loading some modules from sys.path. Can I bypass this somehow? A: You can hack the GAE SDK's restrictions of course (you do have its sources on your computer, and it's ...
Google App Engine, Python and IPython
I want to use IPython under GAE to debug scripts locally: import ipdb; ipdb.set_trace() but GAE restricts loading some modules from sys.path. Can I bypass this somehow?
[ "You can hack the GAE SDK's restrictions of course (you do have its sources on your computer, and it's open-source code!-), but, if you do, it won't catch the cases in which your code erroneously tries to import modules it won't be allowed to use on Google's servers. So I suggest, at the very least, if you do perf...
[ 0 ]
[]
[]
[ "google_app_engine", "ipython", "python" ]
stackoverflow_0003521816_google_app_engine_ipython_python.txt
Q: Writing certain lines to a file in python I have a large file called fulldataset. I would like to write lines from fulldataset to a new file called newdataset. I only want to write the lines from fulldataset though that contain the id numbers present in the listfile. Also all the id numbers start with XY. The id n...
Writing certain lines to a file in python
I have a large file called fulldataset. I would like to write lines from fulldataset to a new file called newdataset. I only want to write the lines from fulldataset though that contain the id numbers present in the listfile. Also all the id numbers start with XY. The id numbers occur in the middle of each line though....
[ "I don't understand your code. Here's the code to do what you've asked:\nids = set( datafile.readlines( ) )\nfor line in fulldataset:\n if any( id in line for id in ids ):\n smallerdataset.write( line )\n\n\nEDIT: I did the best I could with incomplete data. The fact that the IDs in the fulldataset are pr...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003523846_python.txt
Q: Python assertion error, converting string to int I am trying to rewrite my lib written in PHP into python. It handles all sphinx requests. In the init function, I am trying to set default search and match modes, but I have run into a little problem. I get the modes from a config file. In PHP, you need to use a co...
Python assertion error, converting string to int
I am trying to rewrite my lib written in PHP into python. It handles all sphinx requests. In the init function, I am trying to set default search and match modes, but I have run into a little problem. I get the modes from a config file. In PHP, you need to use a constant as an input: $this->sphinx->SetMatchMode(consta...
[ "Python doesn't have a direct equivalent of the PHP constant() function. If the constant in question is imported from a module, the cleanest way to do it is like this:\nimport myconstants\nnum = int(getattr(myconstants, self.config['match_mode']))\n\nOr if it's defined at global scope within the current module, yo...
[ 3, 1, 0 ]
[]
[]
[ "assertion", "python", "sphinx" ]
stackoverflow_0003523932_assertion_python_sphinx.txt
Q: Python module search path I have a project like that : foo/ | main.py | bar/ | | module1.py | | module2.py | | __init__.py with main.py doing import bar.module1 and module1.py doing import module2. This works using python 2.6 but not with python 3.1 (ImportError: No module named module2) Why did the behaviour ch...
Python module search path
I have a project like that : foo/ | main.py | bar/ | | module1.py | | module2.py | | __init__.py with main.py doing import bar.module1 and module1.py doing import module2. This works using python 2.6 but not with python 3.1 (ImportError: No module named module2) Why did the behaviour change ? How to restore it ?
[ "In module1.py, do a: from . import module2\nmain.py\nimport bar.module1\nprint(bar.module1.module2.thing)\n\nbar/init.py\n#\n\nbar/module1.py\n#import module2 # fails in python31\nfrom . import module2 # intrapackage reference, works in python26 and python31\n\nbar/module2.py\nthing = \"blah\"\n\nAs for why/how, t...
[ 6 ]
[]
[]
[ "module", "path", "python" ]
stackoverflow_0003523827_module_path_python.txt
Q: Trouble setting up sqlite3 with django! :/ I'm in the settings.py module, and I'm supposed to add the directory to the sqlite database. How do I know where the database is and what the full directory is? I'm using Windows 7. A: The absolute path of the database directory is what you need. For e.g. if your data...
Trouble setting up sqlite3 with django! :/
I'm in the settings.py module, and I'm supposed to add the directory to the sqlite database. How do I know where the database is and what the full directory is? I'm using Windows 7.
[ "The absolute path of the database directory is what you need. For e.g. if your database is named my.db and lives in C:\\users\\you\\ then:\nDATABASE_ENGINE = 'sqlite3'\nDATABASE_NAME = 'C:/users/you/my.db' \n\nUpdate \nAFAIK you do not have to create the database yourself. The database will be created when you ru...
[ 3, 1 ]
[]
[]
[ "database", "django", "python", "sqlite" ]
stackoverflow_0003524236_database_django_python_sqlite.txt
Q: Using a variable as an object key in Django Template Tags I have two 4 tier objects that I am passing to the django template. I am currently for looping through each tier, and going down a level if it exists. I ended up having key, key2 and key3 that represents the current location in the object while looping. I w...
Using a variable as an object key in Django Template Tags
I have two 4 tier objects that I am passing to the django template. I am currently for looping through each tier, and going down a level if it exists. I ended up having key, key2 and key3 that represents the current location in the object while looping. I would like to reference the other object that has the same tiers...
[ "That cannot be done this way. Look into writing a template tag or filter for this.\n", "I ended up doing the sorting and comparing before the data was sent to the template so this question is no longer needed. Feel free to post other options.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003517928_django_django_templates_python.txt
Q: Are twisted RPCs guaranteed to arrive in order? I'm using twisted to implement a client and a server. I've set up RPC between the client and the server. So on the client I do protocol.REQUEST_UPDATE_STATS(stats), which translates into sending a message with transport.write on the client transport that is some enco...
Are twisted RPCs guaranteed to arrive in order?
I'm using twisted to implement a client and a server. I've set up RPC between the client and the server. So on the client I do protocol.REQUEST_UPDATE_STATS(stats), which translates into sending a message with transport.write on the client transport that is some encoded version of ["update_stats", stats]. When the serv...
[ "They will arrive in the order that the request is received by the Python process. This includes the connection setup time plus the packets containing the request data. So no, this is not guaranteed to be the order that the sending processes sent the request, because of network latency, dropped packets, sender-side...
[ 1 ]
[]
[]
[ "concurrency", "consistency", "python", "rpc", "twisted" ]
stackoverflow_0003524384_concurrency_consistency_python_rpc_twisted.txt
Q: Python ~ accessing tuple members in template class I am new to Python - be forewarned! I have a template class that takes a list as an argument and applies the members of the list to the template. Here's the first class: class ListTemplate: def __init__(self, input_list=[]): self.input_list = input_li...
Python ~ accessing tuple members in template class
I am new to Python - be forewarned! I have a template class that takes a list as an argument and applies the members of the list to the template. Here's the first class: class ListTemplate: def __init__(self, input_list=[]): self.input_list = input_list def __str__(self): return "\n".join([sel...
[ "If you are using Python 2.6 or newer, you can use the format method of strings instead of the % operator. This allows you to specify the index of the given arguments:\n>>> template = 'First value: {0}, Second value: {1}, First again: {0}'\n>>> values = (123, 456)\n>>> template.format(*values)\n'First value: 123, S...
[ 0, 0 ]
[]
[]
[ "dictionary", "python", "sqlite" ]
stackoverflow_0003524478_dictionary_python_sqlite.txt
Q: Improvizing a drop-in replacement for the "with" statement for Python 2.4 Can you suggest a way to code a drop-in replacement for the "with" statement that will work in Python 2.4? It would be a hack, but it would allow me to port my project to Python 2.4 more nicely. EDIT: Removed irrelevant metaclass sketch A: ...
Improvizing a drop-in replacement for the "with" statement for Python 2.4
Can you suggest a way to code a drop-in replacement for the "with" statement that will work in Python 2.4? It would be a hack, but it would allow me to port my project to Python 2.4 more nicely. EDIT: Removed irrelevant metaclass sketch
[ "Just use try-finally.\nReally, this may be nice as a mental exercise, but if you actually do it in code you care about you will end up with ugly, hard to maintain code.\n", "You could (ab)use decorators to do this, I think. The following works, eg:\ndef execute_with_context_manager(man):\n def decorator(f):\n...
[ 7, 4, 1, 1, 1 ]
[]
[]
[ "python", "with_statement" ]
stackoverflow_0001547526_python_with_statement.txt
Q: Why the second time I run "readlines" on the same file nothing is returned? >>> f = open('/tmp/version.txt', 'r') >>> f <open file '/tmp/version.txt', mode 'r' at 0xb788e2e0> >>> f.readlines() ['2.3.4\n'] >>> f.readlines() [] >>> I've tried this in Python's interpreter. Why does this happen? A: You need to seek...
Why the second time I run "readlines" on the same file nothing is returned?
>>> f = open('/tmp/version.txt', 'r') >>> f <open file '/tmp/version.txt', mode 'r' at 0xb788e2e0> >>> f.readlines() ['2.3.4\n'] >>> f.readlines() [] >>> I've tried this in Python's interpreter. Why does this happen?
[ "You need to seek to the beginning of the file. Use f.seek(0) to return to the begining:\n>>> f = open('/tmp/version.txt', 'r')\n>>> f\n<open file '/tmp/version.txt', mode 'r' at 0xb788e2e0>\n>>> f.readlines()\n['2.3.4\\n']\n>>> f.seek(0)\n>>> f.readlines()\n['2.3.4\\n']\n>>>\n\n", "Python keeps track of where y...
[ 20, 6, 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003524528_python.txt
Q: Creation of simple CRUD website using Python which framework? I need to create a simple python website showing customer by salesman and sales by customer. No update of data at all at this time. Which framework might be best. I am not a web guru by any means can read HTML, and Understand CSS. Data is in MySQL. ...
Creation of simple CRUD website using Python which framework?
I need to create a simple python website showing customer by salesman and sales by customer. No update of data at all at this time. Which framework might be best. I am not a web guru by any means can read HTML, and Understand CSS. Data is in MySQL. This is a quick and dirty. Thanks
[ "Probably Django is your best bet as it has a simple ORM and an automatic admin interface which might prove useful. You might be able to simple \"switch off\" the ability to update records in the admin interface and just use that.\n", "\"Best\" is really an opinion question. My personal preference is for Django. ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003524733_python.txt
Q: Does this regex mean it has to start with A, end with Z? re.search "\A[0-9A-Za-z_-]+\Z" Does this regex mean it has to start with A, end with Z? re.search("\A[0-9A-Za-z_-]+\Z", sometext) A: No, those are anchors. \A means start of string, and \Z means end of string. Similarly ^ means start of line and $ means e...
Does this regex mean it has to start with A, end with Z? re.search "\A[0-9A-Za-z_-]+\Z"
Does this regex mean it has to start with A, end with Z? re.search("\A[0-9A-Za-z_-]+\Z", sometext)
[ "No, those are anchors.\n\\A means start of string, and \\Z means end of string. Similarly ^ means start of line and $ means end of line.\nSee the documentation for the re module.\n\n\\A - Matches only at the start of the string.\n \\Z - Matches only at the end of the string.\n\n", "What is \"it\"?\nIf you're ta...
[ 7, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003524788_python_regex.txt
Q: Problems matching caret in Python regex I have the following regular expression, which I think should match any character that is not alphanumeric, '!', '?', or '.' re.compile('[^A-z ?!.]') However, I get the following weird result in iPython: In [21]: re.sub(a, ' ', 'Hey !$%^&*.#$%^&.') Out[21]: 'Hey ! ^ . ^...
Problems matching caret in Python regex
I have the following regular expression, which I think should match any character that is not alphanumeric, '!', '?', or '.' re.compile('[^A-z ?!.]') However, I get the following weird result in iPython: In [21]: re.sub(a, ' ', 'Hey !$%^&*.#$%^&.') Out[21]: 'Hey ! ^ . ^ .' The result is the same when I escape the...
[ "You have an error in your regular expression. Note that the case of the a and z is important. A-z includes all characters between ASCII value 65 (A) and 122 (Z), which includes the caret character (ASCII code 94).\nTry this instead:\nre.compile('[^A-Za-z ?!.]')\n\nExample:\nimport re\nregex = re.compile('[^A-Za-z ...
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003524867_python_regex.txt
Q: How to handle a one line for loop without putting it in a List? Maybe the question is a bit vague, but what I mean is this code: 'livestream' : [cow.legnames for cow in listofcows] Now the problem is cow.legnames is also a list so I will get a list in a list when I try to return it with Json. How should I make it...
How to handle a one line for loop without putting it in a List?
Maybe the question is a bit vague, but what I mean is this code: 'livestream' : [cow.legnames for cow in listofcows] Now the problem is cow.legnames is also a list so I will get a list in a list when I try to return it with Json. How should I make it to return a single list. This is the json that would be returned. 'l...
[ "In addition to shahjapan's reduce you can use this syntax to flatten list.\n[legname for cow in listofcows for legname in cow.legnames]\n\n", "The name listofcows implies there may be, possibly in a distant future, several cows. Flattening a list of list with more than one item would be simply wrong.\nBut if the...
[ 10, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003524339_python.txt
Q: Python, creating a new variable from a dictionary? not as straightforward as it seems? I'm trying to create a new variable that will consist of an existing dictionary so that I can change things in this new dictionary without it affecting the old one. When I try this below, which I think would be the obvious way t...
Python, creating a new variable from a dictionary? not as straightforward as it seems?
I'm trying to create a new variable that will consist of an existing dictionary so that I can change things in this new dictionary without it affecting the old one. When I try this below, which I think would be the obvious way to do this, it still seems to edit my original dictionary when I make edits to the new one.. ...
[ "You're creating a reference, instead of a copy. In order to make a complete copy and leave the original untouched, you need copy.deepcopy(). So:\nfrom copy import deepcopy\ndictionary_new = deepcopy(dictionary_old)\n\nJust using a = dict(b) or a = b.copy() will make a shallow copy and leave any lists in your dicti...
[ 7, 6, 3, 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003525453_dictionary_python.txt
Q: Simplifying complex class hierarchy With the goal of maximizing code reuse, I have created a rather complex class hierarchy for my Python code. It goes something like this: class ElectionMethod class IterativeMethod class SNTV ... class NonIterativeMethod class OrderDependent ...
Simplifying complex class hierarchy
With the goal of maximizing code reuse, I have created a rather complex class hierarchy for my Python code. It goes something like this: class ElectionMethod class IterativeMethod class SNTV ... class NonIterativeMethod class OrderDependent class CambridgeSTV ......
[ "If the only difficulty is finding where something is implemented, perhaps you don't need to refactor. Instead, look for extensions to your current editor, or switch to one that supports jumping-to-definitions.\nFor example, emacs with ropemacs installed jumps to definitions when the the cursor is placed over an o...
[ 2, 2, 0 ]
[]
[]
[ "class_hierarchy", "python" ]
stackoverflow_0003524681_class_hierarchy_python.txt
Q: wxPython: switching text control focus on tab press I made a frame that asks the user to put in a bunch of information in several text control fields. How can I make it so that when you hit the 'tab' key your cursor moves to the next text control? A: If you put a wx.Panel as the only child of the ScrolledWindow ...
wxPython: switching text control focus on tab press
I made a frame that asks the user to put in a bunch of information in several text control fields. How can I make it so that when you hit the 'tab' key your cursor moves to the next text control?
[ "If you put a wx.Panel as the only child of the ScrolledWindow and put the other widgets on the panel, then it should work automatically. You could also use ScrolledPanel instead.\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003525005_python_wxpython.txt
Q: passing R function arguments in rpy I have the following two lines of code that both run fine in both R and Python (via Rpy): [R] rcut = cut(vector, brks) [Python] rcut = r.cut(vector, brks) However, if I want to add the argument of include.lowest=TRUE, it runs as expected in R: [R] rcut = cut(vector, brks, inclu...
passing R function arguments in rpy
I have the following two lines of code that both run fine in both R and Python (via Rpy): [R] rcut = cut(vector, brks) [Python] rcut = r.cut(vector, brks) However, if I want to add the argument of include.lowest=TRUE, it runs as expected in R: [R] rcut = cut(vector, brks, include.lowest=TRUE) But it doesn't work in R...
[ "I don't know rpy, but could it be due to using \"TRUE\" (a character) instead of TRUE (a logical)?\nEDIT: The rpy documentation seems to indicate using r.TRUE:\nhttp://rpy.sourceforge.net/rpy/doc/rpy_html/R-boolean-objects.html#R-boolean-objects\n", "I know nothing about Rpy, but I would guess it needs to be inc...
[ 5, 1 ]
[]
[]
[ "python", "r", "rpy2" ]
stackoverflow_0003525658_python_r_rpy2.txt
Q: String concatenation produces incorrect output in Python? I have this code: filenames=["file1","FILE2","file3","fiLe4"] def alignfilenames(): #build a string that can be used to add labels to the R variables. #format goal: suffixes=c(".fileA",".fileB") filestring='suffixes=c(".' for filename in fi...
String concatenation produces incorrect output in Python?
I have this code: filenames=["file1","FILE2","file3","fiLe4"] def alignfilenames(): #build a string that can be used to add labels to the R variables. #format goal: suffixes=c(".fileA",".fileB") filestring='suffixes=c(".' for filename in filenames: filestring=filestring+str(filename)+'",".' ...
[ "Does this do what you want?\n>>> filenames=[\"file1\",\"FILE2\",\"file3\",\"fiLe4\"]\n>>> c = \"suffixes=c(%s)\" % (\",\".join('\".%s\"' %f for f in filenames))\n>>> c\n'suffixes=c(\".file1\",\".FILE2\",\".file3\",\".fiLe4\")'\n\nUsing a string.join is a much better way to add a common delimiter to a list of items...
[ 11, 2, 1 ]
[]
[]
[ "concatenation", "python", "r", "string" ]
stackoverflow_0003525659_concatenation_python_r_string.txt
Q: web2py list reference I am trying to get the list:reference field type to work for web2py, but for some reason I am getting an error. I am trying the example on http://web2py.com/book/default/chapter/06: db.define_table('tag',Field('name'),format='%(name)s') db.define_table('product', Field('name'), Field(...
web2py list reference
I am trying to get the list:reference field type to work for web2py, but for some reason I am getting an error. I am trying the example on http://web2py.com/book/default/chapter/06: db.define_table('tag',Field('name'),format='%(name)s') db.define_table('product', Field('name'), Field('tags','list:reference tag'...
[ "You have an old web2py version. This feature was released in 1.83.2 the same time as the 3rd ed of the book.\n" ]
[ 2 ]
[]
[]
[ "foreign_key_relationship", "foreign_keys", "python", "web2py" ]
stackoverflow_0003524083_foreign_key_relationship_foreign_keys_python_web2py.txt
Q: Google app engine python problem I'm having a problem with the datastore trying to replicate a left join to find items from model a that don't have a matching relation in model b: class Page(db.Model): url = db.StringProperty(required=True) class Item(db.Model): page = db.ReferenceProperty(Page, required=...
Google app engine python problem
I'm having a problem with the datastore trying to replicate a left join to find items from model a that don't have a matching relation in model b: class Page(db.Model): url = db.StringProperty(required=True) class Item(db.Model): page = db.ReferenceProperty(Page, required=True) name = db.StringProperty(req...
[ "You cannot query for items using a \"property is null\" filter. However, you can add a boolean property to Page that signals if it has items or not:\nclass Page(db.Model):\n url = db.StringProperty(required=True)\n has_items = db.BooleanProperty(default=False)\n\nThen override the \"put\" method of Item to f...
[ 3, 1 ]
[ "Did you try it like :\nPage.all().filter(\"item_set = \", None)\n\nShould work.\n" ]
[ -1 ]
[ "google_app_engine", "python" ]
stackoverflow_0003521373_google_app_engine_python.txt
Q: Translating curl to python urllib2 Can someone please show me how to convert this curl call into call using python urllib2 curl -X POST -H "Content-Type:application/json" -d "{\"data\":{}}" -H "Authorization: GoogleLogin auth=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789...XYZ" https://w...
Translating curl to python urllib2
Can someone please show me how to convert this curl call into call using python urllib2 curl -X POST -H "Content-Type:application/json" -d "{\"data\":{}}" -H "Authorization: GoogleLogin auth=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789...XYZ" https://www.googleapis.com/prediction/v1/training...
[ "Found it here:\nhttp://blog.notdot.net/2010/06/Trying-out-the-new-Prediction-API\n" ]
[ 1 ]
[]
[]
[ "curl", "libcurl", "python", "urllib", "urllib2" ]
stackoverflow_0003516250_curl_libcurl_python_urllib_urllib2.txt
Q: Are there any IDE's that support Python 3 syntax? I recently saw an announcement and article outlining the release of the first Python 3.0 release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax. A: Python 3 is just not that different from Python...
Are there any IDE's that support Python 3 syntax?
I recently saw an announcement and article outlining the release of the first Python 3.0 release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.
[ "Python 3 is just not that different from Python 2.x. In terms of syntax per se, things that will actually need to be handled differently by the parser, the only major change is in the replacement of the print statement with the print function.\nMost of the features of Python can be easily probed via introspection...
[ 6, 5, 3, 1, 1, 1, 1, 0 ]
[]
[]
[ "ide", "python", "python_3.x", "syntax" ]
stackoverflow_0000207763_ide_python_python_3.x_syntax.txt
Q: Python variable resolving Given the following code: a = 0 def foo(): # global a a += 1 foo() When run, Python complains: UnboundLocalError: local variable 'a' referenced before assignment However, when it's a dictionary... a = {} def foo(): a['bar'] = 0 foo() The thing runs just fine... Anyone know why we...
Python variable resolving
Given the following code: a = 0 def foo(): # global a a += 1 foo() When run, Python complains: UnboundLocalError: local variable 'a' referenced before assignment However, when it's a dictionary... a = {} def foo(): a['bar'] = 0 foo() The thing runs just fine... Anyone know why we can reference a in the 2nd chu...
[ "The difference is that in the first example you are assigning to a which creates a new local name a that hides the global a.\nIn the second example you are not making an assignment to a so the global a is used.\nThis is covered in the documentation.\n\nA special quirk of Python is that – if no global statement is ...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003525985_python.txt
Q: Python - why is it not reading my variables? I'm a python newbie and I don't understand why it won't read my IP and ADDR variables in the function dns.zone.query(IP, ADDR)??? import dns.query import dns.zone import sys IP = sys.stdin.readline() ADDR = sys.stdin.readline() z = dns.zone.from_xfr(dns.query.xfr(IP ,...
Python - why is it not reading my variables?
I'm a python newbie and I don't understand why it won't read my IP and ADDR variables in the function dns.zone.query(IP, ADDR)??? import dns.query import dns.zone import sys IP = sys.stdin.readline() ADDR = sys.stdin.readline() z = dns.zone.from_xfr(dns.query.xfr(IP , ADDR)) names = z.nodes.keys() names.sort() for n...
[ "readline() will include a trailing newline. You can use sys.stdin.readline().strip()\n", "Try sys.stdin.readline().strip(). You need to remove the newlines.\n", "I would try with:\nIP = sys.stdin.readline().strip()\nADDR = sys.stdin.readline().strip()\n\nAdd some prints after the variables to debug it:\nprint...
[ 6, 2, 2 ]
[]
[]
[ "function", "python", "variables" ]
stackoverflow_0003526065_function_python_variables.txt
Q: String Division in Python I have a list of strings that all follow a format of parts of the name divided by underscores. Here is the format: string="somethingX_somethingY_one_two" What I want to know how to do it extract "one_two" from each string in the list and rebuild the list so that each entry only has "somet...
String Division in Python
I have a list of strings that all follow a format of parts of the name divided by underscores. Here is the format: string="somethingX_somethingY_one_two" What I want to know how to do it extract "one_two" from each string in the list and rebuild the list so that each entry only has "somethingX_somethingY". I know that ...
[ "You can use split and a list comprehension:\nl = ['_'.join(s.split('_')[:2]) for s in l]\n\n", "If you're literally trying to remove \"_one_two\" from the end of the strings, then you can do this:\ntail_len = len(\"_one_two\")\nstrs = [s[:-tail_len] for s in strs]\n\nIf you want to remove the last two underscore...
[ 6, 3, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003526098_python_string.txt
Q: When should I submit my Django form's results? The contents of my form must be submitted to another application server for validation and execution (specifically, I call a RESTful web service with the posted values in the form). The service will either return a 200 SUCCESS or a 400/409 error with a body that descr...
When should I submit my Django form's results?
The contents of my form must be submitted to another application server for validation and execution (specifically, I call a RESTful web service with the posted values in the form). The service will either return a 200 SUCCESS or a 400/409 error with a body that describes the exact field errors. When should I do this s...
[ "\nvalidation and execution \n\nNo execution or stateful changes in the form clean(). Please. The form's clean() should only mess with data on the form, not anywhere else.\nIf there is a stateful change, it must be in a view function inside a non-GET request handler.\n", "I usually encapsulate these type of log...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003525956_django_python.txt
Q: Pydev can't find matplotlib modules I just installed matplotlib on my windows 7 Python 2.6.5 machine with the win32 installer . I've tried some examples from the matplotlib site to test the installation, under Idle everthing works fine but Pydev 1.9 (Eclipse 3.6) cant find any of the sub modules. e.g import matp...
Pydev can't find matplotlib modules
I just installed matplotlib on my windows 7 Python 2.6.5 machine with the win32 installer . I've tried some examples from the matplotlib site to test the installation, under Idle everthing works fine but Pydev 1.9 (Eclipse 3.6) cant find any of the sub modules. e.g import matplotlib doesn't cause any errors but from...
[ "Seems that your file is called matplotlib.py. Then it's clear why this doesn't work: The current directory is always prepended to the system path, and your file will be found first. Since it doesn't contain a transforms submodule, the import will fail. import matplotlib itself works because there is a module calle...
[ 4 ]
[]
[]
[ "eclipse", "importerror", "matplotlib", "pydev", "python" ]
stackoverflow_0003526389_eclipse_importerror_matplotlib_pydev_python.txt
Q: Substring Comparison in python If i have List PhoneDirectory Eg: ['John:009878788677' , 'Jefrey:67654654645' , 'Maria:8787677766'] Which is the function that can be use to compare the Presence of Substring (Eg: Joh) in each entry in the List . I have tried using if(PhoneDirectory.find(Joh) != -1) but it doesnt ...
Substring Comparison in python
If i have List PhoneDirectory Eg: ['John:009878788677' , 'Jefrey:67654654645' , 'Maria:8787677766'] Which is the function that can be use to compare the Presence of Substring (Eg: Joh) in each entry in the List . I have tried using if(PhoneDirectory.find(Joh) != -1) but it doesnt work kindly Help..
[ "If you want to check each entry separately:\nfor entry in PhoneDirectory:\n if 'John' in entry: ...\n\nIf you just want to know if any entry satisfies the condition and don't care which one:\nif any('John' in entry for entry in PhoneDirectory):\n ...\n\nNote that any will do no \"wasted\" work -- it will ret...
[ 19, 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003524611_python.txt