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: Suds ignoring cache setting? I'm using suds 0.3.8, Python 2.4.3, and Django 1.1.1. The code I inherited has a long duration for the cached files, but it's expiring on the default cadence of once every 24 hours. The external servers hosting the schemas are spotty, so the site is going down nightly and I'm at the ...
Suds ignoring cache setting?
I'm using suds 0.3.8, Python 2.4.3, and Django 1.1.1. The code I inherited has a long duration for the cached files, but it's expiring on the default cadence of once every 24 hours. The external servers hosting the schemas are spotty, so the site is going down nightly and I'm at the end of my rope. Any idea what is j...
[ "Answering my own question:\nThis ended up not being a version issue, but user error. Unfortunately the suds documentation isn't as clear as it could be. Reading it, one would think the code above would work, but (on suds v0.39+) it should be written as:\nimp = Import('http://domain2.com/url')\nimp.filter.add('ht...
[ 11, 0 ]
[]
[]
[ "caching", "django", "python", "suds" ]
stackoverflow_0006153652_caching_django_python_suds.txt
Q: What's the "u'" at the beginning of every field in MongoDB? There's nothing here because the question fit into the title field. A: Probably, you're using the Python client, and seeing Unicode strings.
What's the "u'" at the beginning of every field in MongoDB?
There's nothing here because the question fit into the title field.
[ "Probably, you're using the Python client, and seeing Unicode strings.\n" ]
[ 7 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0006203896_mongodb_pymongo_python.txt
Q: Python and Phidgets: want to send event/message from object to its parent I have a Phidgets stepper controller (Stepper class) and it allows event handlers to be methods of the class: self.setOnAttachHandler(self.StepperAttached) self.setOnDetachHandler(self.StepperDetached) These are useful as they can perform t...
Python and Phidgets: want to send event/message from object to its parent
I have a Phidgets stepper controller (Stepper class) and it allows event handlers to be methods of the class: self.setOnAttachHandler(self.StepperAttached) self.setOnDetachHandler(self.StepperDetached) These are useful as they can perform tasks when the stepper controller is attached/detached from the PC. I have creat...
[ "The canonical way to do this is to pass a reference of the parent object down into the children.\nfrom Phidgets.Devices.Stepper import Stepper\n\nclass Parent(object):\n \"Parent Class\"\n\n def stepperAttached(self, event):\n print 'Connected to device ', event.device.getSerialNum()\n\n def eventH...
[ 1 ]
[]
[]
[ "handler", "message", "python" ]
stackoverflow_0005629006_handler_message_python.txt
Q: Word tokenization using python regular expressions I am trying to split strings into lists of "tags" in python. The splitting should handle strings such as "HappyBirthday" and remove most punctuation but preserve hyphens, and apostrophes. My starting point is: tags = re.findall("([A-Z]{2,}(?=[A-Z]|$)|[A-Z][a-z]*)...
Word tokenization using python regular expressions
I am trying to split strings into lists of "tags" in python. The splitting should handle strings such as "HappyBirthday" and remove most punctuation but preserve hyphens, and apostrophes. My starting point is: tags = re.findall("([A-Z]{2,}(?=[A-Z]|$)|[A-Z][a-z]*)|\w+-\w+|[\w']+" I would want to turn this sample data:...
[ "I suggest the following:\nre.findall(\"[A-Z]{2,}(?![a-z])|[A-Z][a-z]+(?=[A-Z])|[\\'\\w\\-]+\",s)\n\nThis yields for your example:\n[\"Jeff's\", 'dog', 'is', 'un-American', 'Some', 'Times', 'BUT', 'NOT', 'Always']\n\nExplanation: The RegExp is made up of 3 alternatives:\n\n[A-Z]{2,}(?![a-z]) matches words with all ...
[ 24, 3 ]
[]
[]
[ "python", "regex", "string", "tags" ]
stackoverflow_0006202549_python_regex_string_tags.txt
Q: Django - Restricting ModelChoiceField to valid values Models.py: class Comment(models.Model): user = models.ForeignKey(User) document = models.ForeignKey(Document) section = models.ForeignKey(Section, null=True, blank=True) description = models.TextField(null=True, blank=True) Forms.py: class Comm...
Django - Restricting ModelChoiceField to valid values
Models.py: class Comment(models.Model): user = models.ForeignKey(User) document = models.ForeignKey(Document) section = models.ForeignKey(Section, null=True, blank=True) description = models.TextField(null=True, blank=True) Forms.py: class CommentForm(ModelForm): class Meta: model = Comment...
[ "If all you need to do is adjust the admin site you can override the formfield_for_foreignkey method on your django admin class.\nFrom the docs:\n\nModelAdmin.formfield_for_foreignkey(self,db_field, request, **kwargs)\nThe formfield_for_foreignkey method on a ModelAdmin allows you to override the\n default formfie...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0006204370_django_django_models_python.txt
Q: Serving an image from PIL dynamically I am using PIL (Python Imaging Library), and Paste to make a very simple web page. I have a function that returns just an image tag: def home(self): return '<img src="photo" alt="photo"/>' And I also have a function called photo that (ideally) returns the image to be put ...
Serving an image from PIL dynamically
I am using PIL (Python Imaging Library), and Paste to make a very simple web page. I have a function that returns just an image tag: def home(self): return '<img src="photo" alt="photo"/>' And I also have a function called photo that (ideally) returns the image to be put in the img tag: def photo(self): img = ...
[ "Do not return a list with the image, but the image itself.\nReplace\nreturn [final_img]\n\nwith\nreturn final_img\n\n" ]
[ 1 ]
[]
[]
[ "paste", "python", "python_imaging_library" ]
stackoverflow_0006194865_paste_python_python_imaging_library.txt
Q: Python signal: reading return from signal handler function Simple question; How do you read the return value of a function that is called as a signal handler? import signal def SigHand(sig, frm): return 'SomeValue' signal.signal(signal.SIGCHLD, SigHand) signal.pause() Is there a way to read the return value...
Python signal: reading return from signal handler function
Simple question; How do you read the return value of a function that is called as a signal handler? import signal def SigHand(sig, frm): return 'SomeValue' signal.signal(signal.SIGCHLD, SigHand) signal.pause() Is there a way to read the return value 'SomeValue' other than setting it as a global?
[ "You could create a simple class with a return value attribute.\n>>> import signal\n>>> class SignalHandler(object):\n... def __init__(self):\n... self.retval = None\n... def handle(self, sig, frm):\n... self.retval = sig\n... \n>>> s = SignalHandler()\n>>> s.retval\n>>> signal.signal(signal...
[ 3 ]
[]
[]
[ "python", "return_value", "signals" ]
stackoverflow_0006204443_python_return_value_signals.txt
Q: YouTube download link generator in Python How to convert something like http://www.youtube.com/watch?v=ZYffV7qhvTc into something like http://something.flv [the downloadable file of corresponding video] in Python? A: youtube-dl. On the command line: youtube-dl -g http://www.youtube.com/watch?v=ZYffV7qhvTc ...
YouTube download link generator in Python
How to convert something like http://www.youtube.com/watch?v=ZYffV7qhvTc into something like http://something.flv [the downloadable file of corresponding video] in Python?
[ "youtube-dl. On the command line:\nyoutube-dl -g http://www.youtube.com/watch?v=ZYffV7qhvTc\n\nIf you want it in pure Python, have a look at the source code and call download with the appropriate setup.\n" ]
[ 5 ]
[]
[]
[ "python", "youtube" ]
stackoverflow_0006204832_python_youtube.txt
Q: Does the PyMongo driver aggregate data ...after it retrieves all of it from MongoDB and transferring it over the network? What I'm trying to ask is - in a traditional DB scenario, the COUNT, SUM etc are performed at the DB end. Does PyMongo transfer all the records over the network and then do the aggregation? For...
Does the PyMongo driver aggregate data
...after it retrieves all of it from MongoDB and transferring it over the network? What I'm trying to ask is - in a traditional DB scenario, the COUNT, SUM etc are performed at the DB end. Does PyMongo transfer all the records over the network and then do the aggregation? For example, I'm looking at the query from PyMo...
[ "The count() method of pymongo.cursor.Cursor actually sends a 'count' command to the server that only returns the count, not the documents. You can do the same thing yourself:\n>>> db = c.foo\n>>> for doc in db.things.find(): print doc\n... \n{u'_id': ObjectId('4de671821121812a0087101b'), u'foo': u'bar'}\n{u'_id': ...
[ 3 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0006204407_mongodb_pymongo_python.txt
Q: Function calls in logging configuration file I had the following logging configuration in code that I now want to set through a configuration file. formatter = logging.Formatter('%s:'%getpass.getuser() + '%(asctime)s:%(levelname)s:%(module)s:%(lineno)d:%(message)s') In the configuration file, I have > [forma...
Function calls in logging configuration file
I had the following logging configuration in code that I now want to set through a configuration file. formatter = logging.Formatter('%s:'%getpass.getuser() + '%(asctime)s:%(levelname)s:%(module)s:%(lineno)d:%(message)s') In the configuration file, I have > [formatter_frmtr] > format=getpass.getuser() + '%(as...
[ "Use the techniques described in the logging documentation to add additional cobtext to your logging messages.\n" ]
[ 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0006204177_logging_python.txt
Q: Django models - how to filter number of ForeignKey objects I have a models A and B, that are like this: class A(models.Model): title = models.CharField(max_length=20) (...) class B(models.Model): date = models.DateTimeField(auto_now_add=True) (...) a = models.ForeignKey(A) Now I have some A and B objec...
Django models - how to filter number of ForeignKey objects
I have a models A and B, that are like this: class A(models.Model): title = models.CharField(max_length=20) (...) class B(models.Model): date = models.DateTimeField(auto_now_add=True) (...) a = models.ForeignKey(A) Now I have some A and B objects, and I'd like to get a query that selects all A objects that ...
[ "The question and selected answer are from 2008 and since then this functionality has been integrated into the django framework. Since this is a top google hit for \"django filter foreign key count\" I'd like to add an easier solution with a recent django version using Aggregation.\nfrom django.db.models import Co...
[ 151, 7, 3, 1 ]
[]
[]
[ "database_design", "django", "python" ]
stackoverflow_0000258296_database_design_django_python.txt
Q: Python logging - exc_info only for file handler I define root logger and handlers for it: _root = logging.getLogger() _sh = logging.StreamHandler() _fh = logging.FileHandler('./error.log', delay = True) _root.addHandler(_sh) _root.addHandler(_fh) And module logger instance: _log = logging.getLogger("Main") # In o...
Python logging - exc_info only for file handler
I define root logger and handlers for it: _root = logging.getLogger() _sh = logging.StreamHandler() _fh = logging.FileHandler('./error.log', delay = True) _root.addHandler(_sh) _root.addHandler(_fh) And module logger instance: _log = logging.getLogger("Main") # In other file _log = logging.getLogger("Configuration") ...
[ "Create a logging.Formatter subclass for your console handler which returns an empty string from its formatException method.\nThe exception text is cached in the record (in attribute exc_text): if this is a false value (e.g. empty string), then formatException() will be called to repopulate it, otherwise it won't b...
[ 6, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0006177520_logging_python.txt
Q: Wrap C struct with array member for access in python: SWIG? cython? ctypes? I want to access a C function that returns a struct containing double arrays (where the lengths of these arrays is given by other int members of the struct) from python. The declaration is typedef struct { int dim; int vertices; int ...
Wrap C struct with array member for access in python: SWIG? cython? ctypes?
I want to access a C function that returns a struct containing double arrays (where the lengths of these arrays is given by other int members of the struct) from python. The declaration is typedef struct { int dim; int vertices; int quadrature_degree; int polynomial_degree; int ngi; int quadrature_familiy; ...
[ "Cython rules:\ncdef extern from \"the header.h\":\n\nctypedef struct element:\n int dim\n int vertices\n int quadrature_degree\n int polynomial_degree\n int ngi\n int quadrature_familiy\n double *weight\n double *l\n double *n\n double *dn\n\nvoid get_element(int dim, int vertices, int quad_degree, int p...
[ 9, 6, 1, 0, 0 ]
[]
[]
[ "c", "cython", "python", "struct", "swig" ]
stackoverflow_0006165293_c_cython_python_struct_swig.txt
Q: Working on a way to return the text of a button after the button is clicked in tkinter I'm trying to create a list of buttons that are clicked with this lambda function: button1.config(command=(lambda x: (clicked.append(x)))(button1.cget("text"))) It seems to sort of work but it prints the button text immediately...
Working on a way to return the text of a button after the button is clicked in tkinter
I'm trying to create a list of buttons that are clicked with this lambda function: button1.config(command=(lambda x: (clicked.append(x)))(button1.cget("text"))) It seems to sort of work but it prints the button text immediately i.e. it doesn't wait for user to click the button. Any ideas on how to make it responsive...
[ "Trying to do all this in a lambda is the wrong approach. It's simply too confusing, if not impossible to do what you want. Instead, create a method that does the work, and use lambda only as a way to call that function:\nfrom Tkinter import *\nclass GraphicsInterface:\n\n def __init__(self):\n self.windo...
[ 3, 2 ]
[]
[]
[ "button", "python", "tkinter" ]
stackoverflow_0006195702_button_python_tkinter.txt
Q: Is there a good regular expression for multiline matching of received SIP invites? I really need python regexp which would give me this information: Data: Received from 1.1.1.1 18:41:51:330 (123 bytes): INVITE: sip:dsafsdf@fsdafas.com To: sdfasdfasdfas From: "test" Via: sdafsdfasdfasd Sent from 1.1.1.1 1...
Is there a good regular expression for multiline matching of received SIP invites?
I really need python regexp which would give me this information: Data: Received from 1.1.1.1 18:41:51:330 (123 bytes): INVITE: sip:dsafsdf@fsdafas.com To: sdfasdfasdfas From: "test" Via: sdafsdfasdfasd Sent from 1.1.1.1 18:42:51:330 (123 bytes): INVITE: sip:dsafsdf@fsdafas.com From: "test" To: sdfas...
[ "One-line answer, assuming you suck the entire header into a string with embedded newlines (or cr/nl's):\nsorted(re.findall(\"Received [^\\r\\n]+ (\\d{2}:\\d{2}:\\d{2}:\\d{3})[^\\\"]+From: \\\"([^\\r\\n]+)\\\"\", data))[-1][1]\n\nThe trick to doing it with one RE is using [^\\r\\n] instead of . when you want to sca...
[ 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006204902_python_regex.txt
Q: Checking that float modulo int is finite ordinal In a for-loop, I'm integrating with respect to time with constant, fractional time step, dt. I only want to save the simulation results for integral (finite ordinal) time points. My solution is as follows, dt = 0.1 steps = 100 for step in range(steps): if (step...
Checking that float modulo int is finite ordinal
In a for-loop, I'm integrating with respect to time with constant, fractional time step, dt. I only want to save the simulation results for integral (finite ordinal) time points. My solution is as follows, dt = 0.1 steps = 100 for step in range(steps): if (step*dt) % 1 == 0.0: print step I've never really...
[ "This is dangerous, in any programming language. In your example, 0.1 cannot be represented exactly by in floating-point, so that test will never pass (well I suppose it may do after 2^24 iterations or so). In many cases, the step size may not have an exact representation in floating-point, so that the accumulate...
[ 2, 1 ]
[]
[]
[ "floating_point", "modulo", "python" ]
stackoverflow_0006205445_floating_point_modulo_python.txt
Q: How to find datetime 10 mins after current time? I want to find out the datetime 10 mins after current time. Let's say we have from datetime import datetime now = datetime.now() new_now = datetime.strptime(now, '%a, %d %b %Y %H:%M:%S %Z') I want to find this now and new_now 10 minutes later. How can I do t...
How to find datetime 10 mins after current time?
I want to find out the datetime 10 mins after current time. Let's say we have from datetime import datetime now = datetime.now() new_now = datetime.strptime(now, '%a, %d %b %Y %H:%M:%S %Z') I want to find this now and new_now 10 minutes later. How can I do that?
[ "This is a duplicate of this question. You basically just need to add a timedelta of 10 minutes to get the time you want.\nfrom datetime import datetime, timedelta\nnow = datetime.now()\nnow_plus_10 = now + timedelta(minutes = 10)\n\n", "now_plus_10m = now + datetime.timedelta(minutes = 10)\n\nSee arguments you c...
[ 180, 13, 11 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0006205442_datetime_python.txt
Q: Techniques for writing good python code What are the well-known and generally recognized (not subjective) techniques for writing good python code. Structuring it (in opposite to spaghetti code). Good practices for decomposition and decision to make new function or class and similar practical things. You can post a...
Techniques for writing good python code
What are the well-known and generally recognized (not subjective) techniques for writing good python code. Structuring it (in opposite to spaghetti code). Good practices for decomposition and decision to make new function or class and similar practical things. You can post a link where are described and demonstrating t...
[ "See: PEP 8\n", "Code like a pythonista http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html\n", "General sense applies, and follow the style guide: \nhttp://www.python.org/dev/peps/pep-0008/\n" ]
[ 5, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006205817_python.txt
Q: NumPy/SciPy: Move mask over Image and check for equality I am trying to do image processing using NumPy and scipy. I have a template image corresponding to a background, and I want to find out all the places where it occurs in the input image and set the corresponding array positions in the output to 1, else set t...
NumPy/SciPy: Move mask over Image and check for equality
I am trying to do image processing using NumPy and scipy. I have a template image corresponding to a background, and I want to find out all the places where it occurs in the input image and set the corresponding array positions in the output to 1, else set them to 0. How can I do this?
[ "You can use scipy.ndimage.correlate to correlate your template against the image. Then look for bright spots which will give you your matches. Example:\nimport scipy.ndimage\nfrom numpy import mean, std\n\n# a, b contain image and template in numpy arrays\ncorrelation = scipy.ndimage.correlate(a, b)\nmatches = (co...
[ 3 ]
[]
[]
[ "image_processing", "numpy", "python", "scipy" ]
stackoverflow_0006202799_image_processing_numpy_python_scipy.txt
Q: Include Python scripts with Plone Add-on I have a Plone Add-on (created through Zope) that includes Javascript and page template files. Some of the Javascript functions need to call Python scripts (through AJAX calls) - how to I include these Python scripts in my add-on without going through the ZMI? I have a "br...
Include Python scripts with Plone Add-on
I have a Plone Add-on (created through Zope) that includes Javascript and page template files. Some of the Javascript functions need to call Python scripts (through AJAX calls) - how to I include these Python scripts in my add-on without going through the ZMI? I have a "browser" folder which contains a "configure.zcml...
[ "You register your python as Views on the content object:\n<browser:page\n for=\"**INTERFACE**\"\n name=\"**name**\"\n class=\"**class**\"\n attribute=\"**method**\"\n permission=\"zope2.View\"\n />\n\nWhere INTERFACE is an interface of the object you want to have the view of,\nname is the view name (ie, http://pat...
[ 7 ]
[]
[]
[ "add_on", "plone", "python", "scripting" ]
stackoverflow_0006205376_add_on_plone_python_scripting.txt
Q: Is there an elegant way to keep track of sets of connected items in Python? For a certain piece of code, I needed to find a way to recognise certain aliases. Thing is, it is not known beforehand what those aliases are. These are my requirements: If A and B are aliases, and B and C are aliases, A and C should be a...
Is there an elegant way to keep track of sets of connected items in Python?
For a certain piece of code, I needed to find a way to recognise certain aliases. Thing is, it is not known beforehand what those aliases are. These are my requirements: If A and B are aliases, and B and C are aliases, A and C should be aliases as well. Two sets of aliases should be merged when they are connected in a...
[ "Have you considered using a disjoint set? It is virtually O(1) in speed, easy to implement, and seems to match your requirements exactly.\n", "This is something you can map on a graph so I'd do:\nfrom networkx import Graph\nfrom networkx.algorithms.components.connected import connected_components\n\n# see aliase...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006205476_python.txt
Q: asynchronous global variable behavior with intra module globals in python So I have a global variables module global_var.py that looks like this: x = 1 y = 2 When I want to access these variables all I can do something like this: import global_var # read var print global_var.x # change var global_var.x = 0 What...
asynchronous global variable behavior with intra module globals in python
So I have a global variables module global_var.py that looks like this: x = 1 y = 2 When I want to access these variables all I can do something like this: import global_var # read var print global_var.x # change var global_var.x = 0 What I have noticed is that sometimes if I change a global variable and immediately...
[ "The behavior you described isn't something that should ever happen if you're just doing the thing you said you're doing. Double check your code, perhaps you don't actually set a new value in certain cases you think you do; or perhaps you read before you write sometimes; or maybe you have threads, and the exact or...
[ 3 ]
[]
[]
[ "global_variables", "python" ]
stackoverflow_0006206021_global_variables_python.txt
Q: VIMPDB: missing +clientserver on Snow Leopard I'm trying to install VIMPDB on my macport's VIM distibution (Snow Leopard). (I need vim python debugging) Since macport's VIM seems to have the +clientserver configuration disabled, and VIMPDB needs it enabled, how should I proceed? Note: I know that it's possible wit...
VIMPDB: missing +clientserver on Snow Leopard
I'm trying to install VIMPDB on my macport's VIM distibution (Snow Leopard). (I need vim python debugging) Since macport's VIM seems to have the +clientserver configuration disabled, and VIMPDB needs it enabled, how should I proceed? Note: I know that it's possible with MacVim - so it must be possible with vim, as well...
[ "No clientserver flag in variants of vim port file.\n/opt/local/var/macports/sources/rsync.macports.org/release/ports/editors/vim/Portfile\nI think you can add needed configuration option by hands.\nvariant python26 conflicts python25 python27 python31 description {Enable Python scripting} {\n configure.args-ap...
[ 0 ]
[]
[]
[ "macos", "osx_snow_leopard", "python", "vim" ]
stackoverflow_0006203137_macos_osx_snow_leopard_python_vim.txt
Q: What happened to the -e option for pip? The pip documentation mentions -e option to pip, and this is also used on some BuildBot developer 'getting started' notes. However, I have pip 1.0.1 and that running: pip -e master reports Usage: pip COMMAND [OPTIONS] pip: error: no such option: -e Version 1.0.1 of pip s...
What happened to the -e option for pip?
The pip documentation mentions -e option to pip, and this is also used on some BuildBot developer 'getting started' notes. However, I have pip 1.0.1 and that running: pip -e master reports Usage: pip COMMAND [OPTIONS] pip: error: no such option: -e Version 1.0.1 of pip seems to be the latest, in that running pip to...
[ "It's still there! But, -e is an option only to pip install, not to pip itself.\n$ pip install -e\nUsage: /usr/local/bin/pip install [OPTIONS] PACKAGE_NAMES...\n\n/usr/local/bin/pip install: error: -e option requires an argument\n\n" ]
[ 15 ]
[]
[]
[ "pip", "python", "virtualenv" ]
stackoverflow_0006205880_pip_python_virtualenv.txt
Q: How to write small DSL parser with operator module in python See below matrix data: A B C D E F G 1 89 92 18 7 90 35 60 2 62 60 90 91 38 30 50 3 59 91 98 81 67 88 70 4 20 28 31 9 91 6 18 5 80 27 66 1 33 91 18 6 82 30 47 8 39 22 32 7 14 11 70 ...
How to write small DSL parser with operator module in python
See below matrix data: A B C D E F G 1 89 92 18 7 90 35 60 2 62 60 90 91 38 30 50 3 59 91 98 81 67 88 70 4 20 28 31 9 91 6 18 5 80 27 66 1 33 91 18 6 82 30 47 8 39 22 32 7 14 11 70 39 18 10 56 8 98 95 84 47 28 62 99 I need to define "...
[ "How important is the example syntax of your DSL? The simplest approach would be to use the Python expression syntax and eval(). Otherwise it might be possible to translate from your form to something eval()able.\n", "Like this.\nclass Rule( object ):\n def __init__( self, text ):\n self.text= text\n ...
[ 1, 1 ]
[]
[]
[ "dsl", "operation", "python" ]
stackoverflow_0006205592_dsl_operation_python.txt
Q: Automatically add the SHA-1 checksum of a column as another column in a SQLAlchemy table I am working with an SQLAlchemy database. I have a simple schema with columns id, data, and timestamp. The timestamp column is automatically populated with the current date/time as follows: Column('timestamp', DateTime, nullab...
Automatically add the SHA-1 checksum of a column as another column in a SQLAlchemy table
I am working with an SQLAlchemy database. I have a simple schema with columns id, data, and timestamp. The timestamp column is automatically populated with the current date/time as follows: Column('timestamp', DateTime, nullable=False, default=datetime.now) I want to add another column containing the SHA-1 checksum of...
[ "The SqlAlchemy MapperExtension allows you to create code-side triggers/hooks for events. \nhttp://www.sqlalchemy.org/docs/06/orm/interfaces.html?\nBasically you'd want to create a before_insert and before_update that performs the extra actions. I've got an example using this to help make sure I copy content from o...
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006205459_python_sqlalchemy.txt
Q: Django, passing information when modifying queryset for ModelForm Database: Document has many Sections, Sections has many Comments On each document page, there is a comment form that lets you pick the section (using a ModelChoiceField). The problem is that the ModelChoiceField will contain ALL sections for all doc...
Django, passing information when modifying queryset for ModelForm
Database: Document has many Sections, Sections has many Comments On each document page, there is a comment form that lets you pick the section (using a ModelChoiceField). The problem is that the ModelChoiceField will contain ALL sections for all documents. So to limit them I do this: class CommentForm(ModelForm): d...
[ "You can pass the document id when initialising the form:\nclass CommentForm(ModelForm):\n def __init__(self, doc_id=None, *args, **kwargs):\n if doc_id:\n self.fields['section'].queryset = Section.objects.filter(document__id=doc_id)\n\nand in the view\ndef my_view(request):\n ...\n doc =...
[ 5 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0006206241_django_django_forms_python.txt
Q: Python: Importing an "import file" I am importing a lot of different scripts, so at the top of my file it gets cluttered with import statements, i.e.: from somewhere.fileA import ... from somewhere.fileB import ... from somewhere.fileC import ... ... Is there a way to move all of these somewhere else and then all...
Python: Importing an "import file"
I am importing a lot of different scripts, so at the top of my file it gets cluttered with import statements, i.e.: from somewhere.fileA import ... from somewhere.fileB import ... from somewhere.fileC import ... ... Is there a way to move all of these somewhere else and then all I have to do is import that file instea...
[ "I strongly advise against what you want to do. You are doing the global include file mistake again. Although only one module is importing all your modules (as opposed to all modules importing the global one), the remaining point is that if there's a valid reason for all those modules to be collected under a common...
[ 38, 24 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0006206204_python_python_import.txt
Q: In a unit test, how can the parameter passed to a custom exception be determined? class AppError(Exception): pass class MissingInputError(AppError): em = {1101: "Date input is missing. Please verify.", \ 1102: "Key input is missing. Please verify.", \ 1103: "Stn input is missing. Please v...
In a unit test, how can the parameter passed to a custom exception be determined?
class AppError(Exception): pass class MissingInputError(AppError): em = {1101: "Date input is missing. Please verify.", \ 1102: "Key input is missing. Please verify.", \ 1103: "Stn input is missing. Please verify."} # and so on ... ... def validate(self): """ Method of Input cla...
[ "You can pass a regular expression that runs against the message:\nimport unittest\n\nclass MyError(Exception):\n pass\n\ndef raiseError():\n raise MyError(100)\n\nclass TestStuff(unittest.TestCase):\n def testError(self):\n self.assertRaisesRegexp(MyError, '100', raiseError)\n\nunittest.main() \...
[ 3, 2 ]
[]
[]
[ "custom_exceptions", "python", "unit_testing" ]
stackoverflow_0006206150_custom_exceptions_python_unit_testing.txt
Q: Is it a good practice to add names to __all__ using a decorator? Is this a good practice in Python (from Active State Recipes -- Public Decorator)? import sys def public(f): """Use a decorator to avoid retyping function/class names. * Based on an idea by Duncan Booth: http://groups.google.com/group/comp.la...
Is it a good practice to add names to __all__ using a decorator?
Is this a good practice in Python (from Active State Recipes -- Public Decorator)? import sys def public(f): """Use a decorator to avoid retyping function/class names. * Based on an idea by Duncan Booth: http://groups.google.com/group/comp.lang.python/msg/11cbb03e09611b8a * Improved via a suggestion by Dave A...
[ "The more idiomatic way to do this in Python is to mark the private functions as private by starting their name with an underscore:\ndef public(x):\n ...\n\n\ndef _private_helper(y):\n ...\n\nMore people will be familiar with this style (which is also supported by the language: _private_helper will not be e...
[ 17, 8, 1, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0006206089_coding_style_python.txt
Q: Inspecting HTTP POST headers in Python without downloading body A web server responds to a POST request with a file to download (has Content-Disposition header). Using urllib or mechanize opener at what point will the response body be downloaded? opener = mechanize.build_opener(HTTPRefererProcessor, HTTPEquivProce...
Inspecting HTTP POST headers in Python without downloading body
A web server responds to a POST request with a file to download (has Content-Disposition header). Using urllib or mechanize opener at what point will the response body be downloaded? opener = mechanize.build_opener(HTTPRefererProcessor, HTTPEquivProcessor, HTTPRefreshProcessor) r = make_post_request() # makes Request o...
[ "HTTP is a connection-less protocol, meaning that there is no channel established, in which a server could write data in several steps. So If a POST or a GET request is send to a sever, it MUST responds with a complete response, as it can't know, if itwas the 1st or 2nd request. Cookies, AJAX, Comet helps to emulat...
[ 3, 1 ]
[]
[]
[ "http", "python", "urllib2" ]
stackoverflow_0006206689_http_python_urllib2.txt
Q: Pattern Matching Python I'm currently stuck on trying to make a naive algorithm which given a piece of a pattern e.g aabba search for it in a text e.g abbbbaababaabbaaabbaa one letter at a time. It will compare a with the text if that is right then compares the next letter and if that's wrong the whole pattern w...
Pattern Matching Python
I'm currently stuck on trying to make a naive algorithm which given a piece of a pattern e.g aabba search for it in a text e.g abbbbaababaabbaaabbaa one letter at a time. It will compare a with the text if that is right then compares the next letter and if that's wrong the whole pattern will shift one and compare a w...
[ "I guess here's what you need, the following code does character-by-character comparison. You may also replace the calls to find by iterations over text which includes checks whether the first character of text matches the first character of pattern:\ndef my_find(text, pattern):\n '''Find the start index of a pa...
[ 1 ]
[ "def my_find(haystack, needle):\n n_len = len(needle)\n start = 0\n while start <= (len(haystack)-n_len+1):\n if haystack[start:start+n_len-1] == needle:\n return True\n start += 1\n\nThis is, as far as I can understand, your algorithm. Not tested, will test and let you know if it ...
[ -1, -1 ]
[ "python" ]
stackoverflow_0006196128_python.txt
Q: Trouble with pycurl.POSTFIELDS I'm familiar with CURL in PHP but am using it for the first time in Python with pycurl. I keep getting the error: Exception Type: error Exception Value: (2, '') I have no idea what this could mean. Here is my code: data = {'cmd': '_notify-synch', 'tx': str(request.GE...
Trouble with pycurl.POSTFIELDS
I'm familiar with CURL in PHP but am using it for the first time in Python with pycurl. I keep getting the error: Exception Type: error Exception Value: (2, '') I have no idea what this could mean. Here is my code: data = {'cmd': '_notify-synch', 'tx': str(request.GET.get('tx')), 'at': paypal_p...
[ "I do like that:\npost_params = [\n ('ASYNCPOST',True),\n ('PREVIOUSPAGE','yahoo.com'),\n ('EVENTID',5),\n]\nresp_data = urllib.urlencode(post_params)\nmycurl.setopt(pycurl.POSTFIELDS, resp_data)\nmycurl.setopt(pycurl.POST, 1)\n...\nmycurl.perform()\n\n", "I know this is an old post but I've just spent m...
[ 4, 2, 1 ]
[]
[]
[ "curl", "django", "libcurl", "pycurl", "python" ]
stackoverflow_0002017112_curl_django_libcurl_pycurl_python.txt
Q: Python: how to save a Binary Tree? I was wondering how to save a Binary Tree that I have previously created. Does anyone know how to do it? Thank you so much. PD: Here there is a link about how to implement a binary tree, I am using this pice od code: http://code.activestate.com/recipes/286239-binary-ordered-tree/...
Python: how to save a Binary Tree?
I was wondering how to save a Binary Tree that I have previously created. Does anyone know how to do it? Thank you so much. PD: Here there is a link about how to implement a binary tree, I am using this pice od code: http://code.activestate.com/recipes/286239-binary-ordered-tree/
[ "One easy solution: \n- extend the current class to have a load and save method\n- add a unique id to each node\n- implement to do a top down parsing and save each node to a xml with a structure like that\n<node id=\"mynicelycrafteduniqueid\">\n <data>...</data>\n <leftChild>childuniqueId</leftChild>\n <ri...
[ 6, 5, 2, 1 ]
[]
[]
[ "binary_tree", "persistence", "python" ]
stackoverflow_0006197363_binary_tree_persistence_python.txt
Q: Python/GAE social network / cms? After much research, I've come up with a list of what I think might be the best way of putting together a Python based social network/cms, but have some questions about how some of these components fit together. Before I ask about the particular components, here are some of the key...
Python/GAE social network / cms?
After much research, I've come up with a list of what I think might be the best way of putting together a Python based social network/cms, but have some questions about how some of these components fit together. Before I ask about the particular components, here are some of the key features of the site to be built: a ...
[ "As someone who has deployed a Django site to GAE, I can tell you that you are not going to reach the ideal solution. Django on GAE misses some of the best aspects of Django because the ORM doesn't work right. The best compromise may be to use Django-nonrel to add the features back in.\nThis introduces it's own pro...
[ 3 ]
[]
[]
[ "django", "google_app_engine", "pinax", "python", "wxpython" ]
stackoverflow_0003680022_django_google_app_engine_pinax_python_wxpython.txt
Q: How to reduce queries in django model has_relation method? Here are two example Django models. Pay special attention to the has_pet method. class Person(models.Model): name = models.CharField(max_length=255) def has_pet(self): return bool(self.pets.all().only('id')) class Pet(models.Model): n...
How to reduce queries in django model has_relation method?
Here are two example Django models. Pay special attention to the has_pet method. class Person(models.Model): name = models.CharField(max_length=255) def has_pet(self): return bool(self.pets.all().only('id')) class Pet(models.Model): name = models.CharField(max_length=255) owner = models.Foreig...
[ "If you want a list of all the people with pets you can do that in a single query:\nPerson.objects.exclude(pets=None)\n\nSounds like you want to iterate over a single list of people, using annotations would probably make sense:\nfor person in Person.objects.annotate(has_pet=Count('pets')):\n if person.has_pet: ...
[ 4 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0006207557_django_django_models_django_queryset_python.txt
Q: Regex to replace %variables% I've been yanking clumps of hair out for 30 minutes doing this one... I have a dictionary, like so: {'search': 'replace', 'foo': 'bar'} And a string like this: Foo bar %foo% % search %. I'd like to replace each variable with it's equivalent text from the dictionary: Foo bar bar r...
Regex to replace %variables%
I've been yanking clumps of hair out for 30 minutes doing this one... I have a dictionary, like so: {'search': 'replace', 'foo': 'bar'} And a string like this: Foo bar %foo% % search %. I'd like to replace each variable with it's equivalent text from the dictionary: Foo bar bar replace. My current regex fails, s...
[ "If you're flexible with your syntax in your string, Python has a built in mechanism for that:\n>>> print 'Hello, %(your_name)s, my name is %(my_name)s' % {'your_name': 'Blender', 'my_name': 'Ken'}\nHello, Blender, my name is Ken\n\nAlternatively, if you want that syntax, I'd avoid regular expressions and just do t...
[ 8, 4, 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006206804_python_regex.txt
Q: Using "with" statement for CSV files in Python Is it possible to use the with statement directly with CSV files? It seems natural to be able to do something like this: import csv with csv.reader(open("myfile.csv")) as reader: # do things with reader But csv.reader doesn't provide the __enter__ and __exit__ me...
Using "with" statement for CSV files in Python
Is it possible to use the with statement directly with CSV files? It seems natural to be able to do something like this: import csv with csv.reader(open("myfile.csv")) as reader: # do things with reader But csv.reader doesn't provide the __enter__ and __exit__ methods, so this doesn't work. I can however do it in ...
[ "The primary use of with statement is an exception-safe cleanup of an object used in the statement. with makes sure that files are closed, locks are released, contexts are restored, etc.\nDoes csv.reader have things to cleanup in case of exception?\nI'd go with:\nwith open(\"myfile.csv\") as f:\n for row in csv....
[ 21, 4, 2, 1, 0 ]
[]
[]
[ "csv", "python", "with_statement" ]
stackoverflow_0000441130_csv_python_with_statement.txt
Q: how to convert csv into dict format I have a.csv file as below: OLD,NEW AA,XX BB,YY CC,ZZ I wanna convert it to dict format, say dict1 = {'AA':'XX','BB':'YY','CC':'ZZ'} Should I use DictReader or join string? A: with open('file.csv') as f: f.readline() # ignore first line (header) mydict = dict(csv...
how to convert csv into dict format
I have a.csv file as below: OLD,NEW AA,XX BB,YY CC,ZZ I wanna convert it to dict format, say dict1 = {'AA':'XX','BB':'YY','CC':'ZZ'} Should I use DictReader or join string?
[ "with open('file.csv') as f:\n f.readline() # ignore first line (header)\n mydict = dict(csv.reader(f, delimiter=','))\n\nprint mydict\n\n" ]
[ 13 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0006207785_csv_python.txt
Q: Receiving commandline input while listening for connections in Python I am trying to write a program that has clients connect to it while the server is still able to send commands to all of the clients. I am using the "Twisted" solution. How can I go about this? Here is the code I have so far (I understand that Tw...
Receiving commandline input while listening for connections in Python
I am trying to write a program that has clients connect to it while the server is still able to send commands to all of the clients. I am using the "Twisted" solution. How can I go about this? Here is the code I have so far (I understand that Twisted already uses non-blocking sockets): import threading print 'threading...
[ "Since you're already using twisted, you should also use it for the console part, instead of using raw_input in a thread.\nTwisted's event loop can monitor any file descriptor for changes, including the standard input, so you can get event-based callbacks on a new line entered -- It works asynchronously without nee...
[ 6 ]
[]
[]
[ "client", "python", "sockets", "twisted" ]
stackoverflow_0006207669_client_python_sockets_twisted.txt
Q: Using python to edit html, but lxml converts nice html entities to strange encoding I'm trying to use python (with pyquery and lxml) to alter and clean up some html. Eg. html = "<div><!-- word style><bleep><omgz 1,000 tags><--><p>It&#146;s a spicy meatball!</div>" The lxml.html.clean function, clean_html(), works...
Using python to edit html, but lxml converts nice html entities to strange encoding
I'm trying to use python (with pyquery and lxml) to alter and clean up some html. Eg. html = "<div><!-- word style><bleep><omgz 1,000 tags><--><p>It&#146;s a spicy meatball!</div>" The lxml.html.clean function, clean_html(), works well, except that it replaces the nice html entities like &#146; with some unicode str...
[ "There are a few things that - if you know them - will lead to the easiest/best solution:\n\nclean_html() returns the same type you provide it with: if you give it a string, it will return a string, but if you give it an Element or ElementTree, it will return an Element or ElementTree respectively\nyou can control ...
[ 12, 2, 1 ]
[]
[]
[ "character_encoding", "html_parsing", "lxml", "python" ]
stackoverflow_0004876716_character_encoding_html_parsing_lxml_python.txt
Q: Complex action on Django menu I have a small app for a local hockey league, I wanted to know if it was possible to write an action on the admin of the games, so that when I check 2 games, it exchanges the teams that are about to play. Example team A vs team B -- team C vs team D, if I swap this with the action men...
Complex action on Django menu
I have a small app for a local hockey league, I wanted to know if it was possible to write an action on the admin of the games, so that when I check 2 games, it exchanges the teams that are about to play. Example team A vs team B -- team C vs team D, if I swap this with the action menu it should be team C vs team B -- ...
[ "You have to define a method like this:\ndef exchange_team(modeladmin, request, queryset):\n if queryset.count() == 2:\n #your interchange code...\n\nAnd reference it in your admin class:\nclass TeamAdmin(admin.ModelAdmin):\n ...\n actions = ['exchange_team']\n\nadmin.register(Team, TeamAdmin)\n\n" ...
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0006207958_django_django_admin_python.txt
Q: Help with a regular expression - Python Lets assume I have the following string: string = "xxx abc123 xxx" I want the regular expression to replace the digits in the string that begin with 'abc'. I have tried the following, but with no luck: re.sub(r'\d{1,3}\babc','456',string) Thanks. A: re.sub(r'(?<=abc)\d{1...
Help with a regular expression - Python
Lets assume I have the following string: string = "xxx abc123 xxx" I want the regular expression to replace the digits in the string that begin with 'abc'. I have tried the following, but with no luck: re.sub(r'\d{1,3}\babc','456',string) Thanks.
[ "re.sub(r'(?<=abc)\\d{1,3}', '456', string)\n\n" ]
[ 5 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006207962_python_regex.txt
Q: Python - Threading, Timing, or function use? I am having an issue formulating an idea on how to work this problem. Please help. My project consists of an N x N grid with a series of blocks that are supposed to move in a random direction and random velocity within this grid (every .1 seconds, the location of the ...
Python - Threading, Timing, or function use?
I am having an issue formulating an idea on how to work this problem. Please help. My project consists of an N x N grid with a series of blocks that are supposed to move in a random direction and random velocity within this grid (every .1 seconds, the location of the block is updated with the velocity). I have three "...
[ "Your best bet is probably to handle all of them at once in a single update function rather than attempting to use Threads. This is primarily because the Global Interpreter Lock will prevent multiple threads from processing concurrently anyway. What you're after then is something like this:\ndef tick():\n for bo...
[ 2, 0 ]
[]
[]
[ "java", "multithreading", "python", "timing" ]
stackoverflow_0006207985_java_multithreading_python_timing.txt
Q: Where do scheduled python programs "print"? If I schedule print "Hello World!"; to run every hour with crontab, where will Hello World! be printed? Is there a log file? If I do it with Java or C instead of Python, will it make any difference? Thanks! A: They will be sent to the email address defined at the top o...
Where do scheduled python programs "print"?
If I schedule print "Hello World!"; to run every hour with crontab, where will Hello World! be printed? Is there a log file? If I do it with Java or C instead of Python, will it make any difference? Thanks!
[ "They will be sent to the email address defined at the top of the crontab, or to the crontab's owner by default. See the crontab(5) man page for more details.\n" ]
[ 2 ]
[]
[]
[ "crontab", "python" ]
stackoverflow_0006208274_crontab_python.txt
Q: Python sleep function does not catch interrupt signal I cannot catch the INT signal in the main thread, please advise me how to fix the problem. I wish that the sleep method could be interrupted by CTRL+C, but it waits till the timer is ended.. import pygtk pygtk.require('2.0') import gtk import time import urlli...
Python sleep function does not catch interrupt signal
I cannot catch the INT signal in the main thread, please advise me how to fix the problem. I wish that the sleep method could be interrupted by CTRL+C, but it waits till the timer is ended.. import pygtk pygtk.require('2.0') import gtk import time import urllib2 import re import signal import sys import __main__ fro...
[ "Signals are only delivered to one thread. Either only the first thread, or the first available thread depending on the operating system.\nYou'll have to implement you're own logic to shutdown the other threads, or make them daemon threads so they don't prevent the process from exiting.\n", "Believe it or not, th...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006208183_python.txt
Q: Import Python module with PyImport_ImportModuleEx for a gedit plugin I'm learning Python and I try to use Python Markdown in a gedit plugin. Here's how my files are organized: ~/.gnome2/gedit/plugins/mytest.gedit-plugin ~/.gnome2/gedit/plugins/mytest/ ~/.gnome2/gedit/plugins/mytest/__init__.py ~/.gnome2/gedit/plug...
Import Python module with PyImport_ImportModuleEx for a gedit plugin
I'm learning Python and I try to use Python Markdown in a gedit plugin. Here's how my files are organized: ~/.gnome2/gedit/plugins/mytest.gedit-plugin ~/.gnome2/gedit/plugins/mytest/ ~/.gnome2/gedit/plugins/mytest/__init__.py ~/.gnome2/gedit/plugins/mytest/markdown/ ~/.gnome2/gedit/plugins/mytest/markdown/__init__.py ~...
[ "If you want to use markdown without modifying it then you're going to have to put it somewhere where the Python library expects it, such as in site-packages/. Otherwise, you will have to modify it to use relative imports instead of absolute imports.\n" ]
[ 2 ]
[]
[]
[ "gedit", "import", "python" ]
stackoverflow_0006208369_gedit_import_python.txt
Q: Why can @decorator not decorate a staticmethod or a classmethod? Why can decorator not decorate a staticmethod or a classmethod? from decorator import decorator @decorator def print_function_name(function, *args): print '%s was called.' % function.func_name return function(*args) class My_class(object): ...
Why can @decorator not decorate a staticmethod or a classmethod?
Why can decorator not decorate a staticmethod or a classmethod? from decorator import decorator @decorator def print_function_name(function, *args): print '%s was called.' % function.func_name return function(*args) class My_class(object): @print_function_name @classmethod def get_dir(cls): ...
[ "classmethod and staticmethod return descriptor objects, not functions. Most decorators are not designed to accept descriptors.\nNormally, then, you must apply classmethod and staticmethod last when using multiple decorators. And since decorators are applied in \"bottom up\" order, classmethod and staticmethod no...
[ 85, 37, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0001987919_decorator_python.txt
Q: Python: words replacing in huge text I have a huge text and a list of words ~10K. What is the fastest way in Python to replace all this words in text with some other word? EDIT: Text size >1Gb, text is human written, and "extremely tokenized" (any runs of alphanumeric characters and any other single symbols was ...
Python: words replacing in huge text
I have a huge text and a list of words ~10K. What is the fastest way in Python to replace all this words in text with some other word? EDIT: Text size >1Gb, text is human written, and "extremely tokenized" (any runs of alphanumeric characters and any other single symbols was splitted into new tokens) a number of word...
[ "Input format and search / replace pairings info is going to necessary to refine this answer if it comes close to start with, but this would be my initial stab at it (assuming some form of regularity in the input data, space delimited in my example code below).\nreplacements = {\n 's1': 'r1',\n 's2': 'r2'\n ...\...
[ 3, 1, 0, 0 ]
[]
[]
[ "python", "replace", "text" ]
stackoverflow_0006208232_python_replace_text.txt
Q: How can I automate antivirus/WSUS patch testing of my Windows driver and binary? My (rather small) company develops a popular Windows application, but one thing we've always struggled with is testing - it frequently is only tested by the developers on a system similar to the one they developed it on, and when an u...
How can I automate antivirus/WSUS patch testing of my Windows driver and binary?
My (rather small) company develops a popular Windows application, but one thing we've always struggled with is testing - it frequently is only tested by the developers on a system similar to the one they developed it on, and when an update is pushed out to customers, there is a segment of our base that experiences issu...
[ "Interesting problem. One thing to avoid is using the antivirus APIs to check to see if your application triggers them. You want a real live deployment of your application, on the expected operating system, with a real live AV install monitoring it. That way you'll trigger the heuristics monitoring as well as the s...
[ 1 ]
[]
[]
[ "automation", "cots", "functional_testing", "python", "testing" ]
stackoverflow_0006208385_automation_cots_functional_testing_python_testing.txt
Q: Python: joining 2 lists of the same size Let's say I have 2 following lists: list1 = [1,1,1,1] list2 = [3,3,3,3] I want the result of join to be: list3 [4,4,4,4] What's would be the best way to do it? A: Extremely similar to Ignacio's answer, but for a tiny bit more brevity: list3 = [sum(i) for i in zip(list1, ...
Python: joining 2 lists of the same size
Let's say I have 2 following lists: list1 = [1,1,1,1] list2 = [3,3,3,3] I want the result of join to be: list3 [4,4,4,4] What's would be the best way to do it?
[ "Extremely similar to Ignacio's answer, but for a tiny bit more brevity:\nlist3 = [sum(i) for i in zip(list1, list2)]\n\nor\nlist3 = map(sum, zip(list1, list2))\n\nI prefer the map version myself.\nEdit: As JBernardo rightly points out, if using Python 2.x you should replace zip with its iterator counterpart in ite...
[ 10, 9 ]
[]
[]
[ "list", "python", "sum" ]
stackoverflow_0006208522_list_python_sum.txt
Q: Python requiring an attribute be converted to a string from sys import exit from random import randint class Map(object): def death(): print quips[randint (0, len(quips)-1)] exit(1) def princess_lives_here(): print "You see a beautiful Princess with a shiny crown." print "She offers you some ...
Python requiring an attribute be converted to a string
from sys import exit from random import randint class Map(object): def death(): print quips[randint (0, len(quips)-1)] exit(1) def princess_lives_here(): print "You see a beautiful Princess with a shiny crown." print "She offers you some cake." eat_it = raw_input(">") if eat_it == "eat i...
[ "Maybe you want something like this? \nclass Map(object):\n\n def __init__(self):\n\n self.quips = [\n \"You died. You suck at this.\",\n \"Your mom would be proud, if she were smarter\",\n \"Such a luser.\",\n \"I have a small puppy that's better at this.\"\n ]\n\n def death(self)...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "attributes", "class", "python", "string" ]
stackoverflow_0006208418_attributes_class_python_string.txt
Q: Django not create database table Hey, I've a database already created. Now I've updated UserProfile with: class UserProfile(models.Model): user = models.ForeignKey(User, unique = True, related_name = 'user') follows = models.ManyToManyField("self", related_name = 'follows') <-- NEW LINE so python manage.p...
Django not create database table
Hey, I've a database already created. Now I've updated UserProfile with: class UserProfile(models.Model): user = models.ForeignKey(User, unique = True, related_name = 'user') follows = models.ManyToManyField("self", related_name = 'follows') <-- NEW LINE so python manage.py sqlall myapp returns me: [...] CREAT...
[ "manage.py syncdb will not modify existing tables to add or remove fields. You will need to either manually modify your database, or use a tool like South to create automated database migrations (which is what I highly recommend)\n", "have you added your app to INSTALLED_APPS in settings.pys:\nsettings.py\nINSTA...
[ 6, 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006208636_django_python.txt
Q: Read through an unstructured xls file I have an .xls file which contains one column with 2,000 rows. I want to iterate through the file and print out the data points which start with "cheap". However, the following code doesn't work. Help! import xlrd wb = xlrd.open_workbook("file.xls") wb.sheet_names() sh = wb....
Read through an unstructured xls file
I have an .xls file which contains one column with 2,000 rows. I want to iterate through the file and print out the data points which start with "cheap". However, the following code doesn't work. Help! import xlrd wb = xlrd.open_workbook("file.xls") wb.sheet_names() sh = wb.sheet_by_index(0) lst = [sh] for item in l...
[ "it should look like:\nimport xlrd\nwb = xlrd.open_workbook(\"file.xls\")\n\nwb.sheet_names()\n\nsh = wb.sheet_by_index(0)\n\nfor item in sh.col(0):\n value = unicode(item.value)\n if value.startswith(\"cheap\"):\n print value\n\n" ]
[ 2 ]
[]
[]
[ "file", "python", "xls" ]
stackoverflow_0006208615_file_python_xls.txt
Q: Why does importing as modules and writing creates a different result? def matrixdets(a): x=(a[0][0] * a[1][1] * a[2][2]) + \ (a[0][1] * a[1][2] * a[2][0]) + \ (a[0][2] * a[1][0] * a[2][1]) print(x) I wrote this code to find a certain value of a matrix. It returns a number when I type the funct...
Why does importing as modules and writing creates a different result?
def matrixdets(a): x=(a[0][0] * a[1][1] * a[2][2]) + \ (a[0][1] * a[1][2] * a[2][0]) + \ (a[0][2] * a[1][0] * a[2][1]) print(x) I wrote this code to find a certain value of a matrix. It returns a number when I type the function in python. However, when i import this as a module, it just returns th...
[ "As Graeme said, it doesn't return anything. When you import it, the function gets compiled at the time of importation. \nDoes your module define a and then run matrixdets on it? It will do that even when you import the function from a module, since importing a module executes all the code inside it.\nYou need to b...
[ 0 ]
[]
[]
[ "function", "matrix", "module", "python", "return" ]
stackoverflow_0006208476_function_matrix_module_python_return.txt
Q: Flask message flashing fails across redirects I'm currently working on a project using Flask and Google App Engine. Calling get_flashed_messages() returns empty when I flash a message then use a redirect(): @views.route('/todo/add', methods=["POST"]) def add_todo(): flash('hey') return redirect(url_for('to...
Flask message flashing fails across redirects
I'm currently working on a project using Flask and Google App Engine. Calling get_flashed_messages() returns empty when I flash a message then use a redirect(): @views.route('/todo/add', methods=["POST"]) def add_todo(): flash('hey') return redirect(url_for('todo_list')) However, if I comment out # SERVER_NAM...
[ "I got it!\nThe trick is to set server name to something with dots.\nSo 'localhost' became 'app.local' and app.local should be added to /etc/hosts, pointing to the same address as localhost.\nFrom the docs:\n\nPlease keep in mind that not only\n Flask has the problem of not knowing\n what subdomains are, your web...
[ 10, 3 ]
[]
[]
[ "flask", "google_app_engine", "python" ]
stackoverflow_0006196598_flask_google_app_engine_python.txt
Q: Python method lookup, static vs. instance Until like one hour ago, I was convinced that in python Foo ().bar () was nothing more than a short hand for Foo.bar (Foo () ) which passes the instance as first parameter. In this example the last two lines do (apparently) the same thing: class Foo (object): def bar (...
Python method lookup, static vs. instance
Until like one hour ago, I was convinced that in python Foo ().bar () was nothing more than a short hand for Foo.bar (Foo () ) which passes the instance as first parameter. In this example the last two lines do (apparently) the same thing: class Foo (object): def bar (self): print "baz" qux = Foo () qux.bar () Foo...
[ "Static methods and class methods are special descriptors. Since the descriptor's __get__() method's arguments include both the class and any relevant instance, they can screw with the arguments to the method in any way they like.\n", "On the difference between Foo().bar(), Foo.bar(Foo()) and Foo.bar() (as an an...
[ 2, 2, 0 ]
[]
[]
[ "monkeypatching", "python", "static" ]
stackoverflow_0006207299_monkeypatching_python_static.txt
Q: In need of a python script to upload a file with IP address every few minutes I'm using windows server 2008, and one of the things I need to do in order to pair to a domain name is send a file with the computers current IP address (it's not static) to a server via sftp every few minutes. The problem is that I'm no...
In need of a python script to upload a file with IP address every few minutes
I'm using windows server 2008, and one of the things I need to do in order to pair to a domain name is send a file with the computers current IP address (it's not static) to a server via sftp every few minutes. The problem is that I'm not sure how to do this.
[ "I would send it via XMPP. You can set up a listener service for the server. \nSend an xmpp message using a python library\nHere are some ideas on XMPP servers to run on your IIS server (listening to recieve the incoming messages from clients http://metajack.im/2008/08/26/choosing-an-xmpp-server/\nPretzel looks n...
[ 0 ]
[]
[]
[ "autorun", "ip_address", "python" ]
stackoverflow_0006208664_autorun_ip_address_python.txt
Q: How is memory management in PHP different from that in Python? What is the difference in how they are handled? Specifically, why is it common to find Python used in production-level long lived applications like web-servers while PHP isn't given their similar efficiency levels? A: PHP was designed as a hypertext ...
How is memory management in PHP different from that in Python?
What is the difference in how they are handled? Specifically, why is it common to find Python used in production-level long lived applications like web-servers while PHP isn't given their similar efficiency levels?
[ "PHP was designed as a hypertext scripting language. Every process was designed to end after a very short time. So memory management and GC basically didn't matter.\nHowever the ease and popularity of PHP have invoked its usage in long lived programs such as daemons, extensive calculations, socket servers etc.\nPHP...
[ 8 ]
[]
[]
[ "garbage_collection", "memory_management", "php", "python", "webserver" ]
stackoverflow_0006158033_garbage_collection_memory_management_php_python_webserver.txt
Q: Python: getopt, batch files, and paths with spaces I'm using getopt to parse options and arguments. I wrote a batch file to call a python script so I don't have to type the same command over and over. When I printed out the list of arguments, the path was split on spaces and each was parsed separately. The path is...
Python: getopt, batch files, and paths with spaces
I'm using getopt to parse options and arguments. I wrote a batch file to call a python script so I don't have to type the same command over and over. When I printed out the list of arguments, the path was split on spaces and each was parsed separately. The path is enclosed in double quotes, but I'm not sure what the pr...
[ "We'll need to see code to be sure but make sure you quote the argument everywhere not just on the command line.\nCommand line...\n$script.sh \"/my/path with/spaces\"\n\nBash Script...\n#!/bin/bash\npython /path/to/script \"$1\"\n\n" ]
[ 2 ]
[]
[]
[ "batch_file", "python" ]
stackoverflow_0006209165_batch_file_python.txt
Q: Best practise for Progress Bar in Python's PyGTK I would like to get feedback on others' opinions of best practice for how to implement a progress bar in Python's PyGTK. The work that the progress bar was to represent was very significant computationally. Therefore, I wanted the work to be done in a separate proc...
Best practise for Progress Bar in Python's PyGTK
I would like to get feedback on others' opinions of best practice for how to implement a progress bar in Python's PyGTK. The work that the progress bar was to represent was very significant computationally. Therefore, I wanted the work to be done in a separate process (thus giving the operating system the possibility ...
[ "I realise now that I do not have enough reputation to make this a community wiki, so I hope someone else can change this to wiki-status. Thanks.\nI am by no means an expert Python programmer, however I have spent some time trying to find an acceptable solution. I hope that the following code may act as a startin...
[ 4 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0006209207_multithreading_python.txt
Q: IRC function dilemma [EDIT] Sorry about the title being off. I was thinking of a different problem I was having, and accidentally crossed the two. Hi everyone, I'm writing my IRC bot skeleton in Python currently. To explain a couple things before I ask my question, I am writing a IRC bot complete with a plug-in sy...
IRC function dilemma
[EDIT] Sorry about the title being off. I was thinking of a different problem I was having, and accidentally crossed the two. Hi everyone, I'm writing my IRC bot skeleton in Python currently. To explain a couple things before I ask my question, I am writing a IRC bot complete with a plug-in system that will receive sig...
[ "It sounds like you need to decide between or read up more on Publish/subscribe and Chain of Responsibility. Unfortunately I don't have much experience in this area. Just happened to read a related article recently.\n" ]
[ 1 ]
[]
[]
[ "irc", "python", "recursion" ]
stackoverflow_0006208859_irc_python_recursion.txt
Q: Why does my regex not work on input from file.read()? I have a section of code that I need to remove from multiple files that starts like this: <?php //{{56541616 and ends like this: //}}18420732 ?> where both strings of numbers can be any sequence of letters and numbers (not the same). I wrote a Python program ...
Why does my regex not work on input from file.read()?
I have a section of code that I need to remove from multiple files that starts like this: <?php //{{56541616 and ends like this: //}}18420732 ?> where both strings of numbers can be any sequence of letters and numbers (not the same). I wrote a Python program that will return the entire input string except for this pr...
[ "Your regex only uses \\n for lines. Your text editor may insert a carriage return and newline combination: \\r\\n. Try changing \\n in your regex to (\\r\\n|\\r|\\n).\n", "Keep the \\n in your regular expressions and open the file as:\ninput_file= open(filename, 'rU')\n\nNote the extra U in the mode. This will...
[ 1, 0 ]
[]
[]
[ "file_io", "python", "quotes", "regex", "string" ]
stackoverflow_0006194967_file_io_python_quotes_regex_string.txt
Q: Dealing with the Tkinter Text Widgets Indexing System. How do I split a floating point number. For example : 1.24345 would return 24345 1455.24 would return 24 1455.0 would return 0 Edit : My solution inspired by Nick ODell. This is oriented specifically toward the Tkinter Text widget. index = '140.2020' split...
Dealing with the Tkinter Text Widgets Indexing System.
How do I split a floating point number. For example : 1.24345 would return 24345 1455.24 would return 24 1455.0 would return 0 Edit : My solution inspired by Nick ODell. This is oriented specifically toward the Tkinter Text widget. index = '140.2020' split = index.split('.') nindex = [int(i) for i in split] print ...
[ "Assuming that 'index' is a string since you are dealing with a text widget index:\nint(index.split('.')[-1])\n\nIf you really do have a floating point number, you need to convert it to a string first:\nint(str(index).split('.')[-1])\n\n", "The Tkinter Text Widget\n\nNote that line/column indexes may look\n like...
[ 5, 5, 0 ]
[ "Use divmod \nfor num in [1.24345, 1455.24]: \n whole, dec = divmod(num, 1) \n print num, whole, dec \n" ]
[ -1 ]
[ "indexing", "python", "text", "tkinter" ]
stackoverflow_0006194193_indexing_python_text_tkinter.txt
Q: generating and mapping two sets of numbers I have 2 numbers 25798709 and 25716544 representing the minimum and maximum values of some consecutive numbers with each number differing from the preceeding number by one eg. 25798709,25798710, 25798711................25716544 I want a python code that will convert thes...
generating and mapping two sets of numbers
I have 2 numbers 25798709 and 25716544 representing the minimum and maximum values of some consecutive numbers with each number differing from the preceeding number by one eg. 25798709,25798710, 25798711................25716544 I want a python code that will convert these figures to 1,2,3,4,5,.............. and map th...
[ "Oneliner:\nprint(*['{0}\\t{1}'.format(*i) for i in enumerate(range(MIN,MAX+1), 1)], sep='\\n')\n\nFor python2.6 or 2.7 just add from __future__ import print_function\n", "Here you are:\nmapping = dict(enumerate(range(25716544, 25798709)))\nfor i in iter(mapping):\n print i, '->', mapping[i]\n\nI should warn y...
[ 1, 0, 0, 0 ]
[]
[]
[ "mapping", "numbers", "python" ]
stackoverflow_0006208277_mapping_numbers_python.txt
Q: Why are these two values different when I assign one to the other? The code below gives different values for c and d when I print them import csv datafile = open('test1.csv', 'r') datareader = csv.reader(datafile) c = [] for row in datareader: c.append(row) d = [[0]*2]*2 i=0 while i < 2: j=0 whil...
Why are these two values different when I assign one to the other?
The code below gives different values for c and d when I print them import csv datafile = open('test1.csv', 'r') datareader = csv.reader(datafile) c = [] for row in datareader: c.append(row) d = [[0]*2]*2 i=0 while i < 2: j=0 while j < 2: d[i][j] = float(c[i][j]) j=j+1 i=i+1 pri...
[ "This line:\nd = [[0]*2]*2\n\ndoesn't create copies of the inner lists, it just creates multiple references to the same list. Replace it with an explicit declaration:\nd = [[0, 0], [0, 0]]\n\n", "Lists are mutable elements. You're not creating multiple lists when you do things like [[0]]*10 but creates 10 referen...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006202281_python.txt
Q: Problems getting stress.py to work with Cassandra I am trying to run the stress.py stress test included with Cassandra. When I attempt to run ./stress.py I get the following output: Traceback (most recent call last): File "/usr/lib/python2.6/multiprocessing/process.py", line 232, in _bootstrap self.run() F...
Problems getting stress.py to work with Cassandra
I am trying to run the stress.py stress test included with Cassandra. When I attempt to run ./stress.py I get the following output: Traceback (most recent call last): File "/usr/lib/python2.6/multiprocessing/process.py", line 232, in _bootstrap self.run() File "./stress.py", line 238, in run self.cclient.ba...
[ "UnavailableException means too many nodes are down. Use \"nodetool ring\" to find out which.\nAlso: unless you're customizing stress.py, the java stress tool is significantly faster. (With python you need roughly 1:1 client machines to cassandra machines to fully saturate it; with java it's more like 1:5.)\n" ]
[ 2 ]
[]
[]
[ "cassandra", "python" ]
stackoverflow_0006204080_cassandra_python.txt
Q: SVN having credential problems with Jenkins running as SYSTEM I have Jenkins running a python script that makes some SVN calls, my problem is that Jenkins tries to run this script as SYSTEM user which doesn't seem to have permission to access the SVN. It prompts me for a password for 'SYSTEM' upon my svn call. If ...
SVN having credential problems with Jenkins running as SYSTEM
I have Jenkins running a python script that makes some SVN calls, my problem is that Jenkins tries to run this script as SYSTEM user which doesn't seem to have permission to access the SVN. It prompts me for a password for 'SYSTEM' upon my svn call. If I run the python script by itself, I have no problems accessing the...
[ "Create a new Jenkins job, and use Subversion as the revision control system. Put in the URL of the Subversion repository you want to manipulate in your Python script. Under the URL will appear a link to let you set the login. Click the link and log in.\nOnce you're done, you can delete the job. The whole purpose w...
[ 2 ]
[]
[]
[ "credentials", "jenkins", "python", "svn", "windows_7" ]
stackoverflow_0006208922_credentials_jenkins_python_svn_windows_7.txt
Q: Parse small string for name and email? I have a string: John Smith <jsmith@gmail.com> I would like to get two variables: name (John Smith) and email (jsmith@gmail.com) How might I do that? Thanks for the help! A: There are more forms of valid Internet Email address than you probably realize. I would suggest usi...
Parse small string for name and email?
I have a string: John Smith <jsmith@gmail.com> I would like to get two variables: name (John Smith) and email (jsmith@gmail.com) How might I do that? Thanks for the help!
[ "There are more forms of valid Internet Email address than you probably realize. I would suggest using somebody else's code to parse them, like email.utils.parseaddr.\nFor example, the following is a valid address:\n\"Rocky J. Squirrel\" <rocky.squirrel@gmail.com>\n\nHere, the name is Rocky J. Squirrel, not \"Rock...
[ 18 ]
[]
[]
[ "email", "python" ]
stackoverflow_0006209910_email_python.txt
Q: Using the len() function with unicode values Python newbie here. I have an excel file with 5000 rows and 1 columns. I'm importing them into Python and will then use if...else statements to check for specific conditions. So my data looks like: (in excel) Kansas Colorado Missouri Iowa New York New Mexico mycar car t...
Using the len() function with unicode values
Python newbie here. I have an excel file with 5000 rows and 1 columns. I'm importing them into Python and will then use if...else statements to check for specific conditions. So my data looks like: (in excel) Kansas Colorado Missouri Iowa New York New Mexico mycar car thisisacar ... There here is the code to import it...
[ "len(value) should work fine -- I suggest there's probably some trailing whitespace or similar, so try using len(value.strip()) and see if that solves your problem :)\n", "Your code doesn't work for mycar and thisisacar.\nMaybe you should try something like:\nx = (value.strip() for value in sh.col(0) if 'car' in ...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006209895_python.txt
Q: Why doesn't this work (wxpython/color dialog) class iFrame(wx.Frame): def __init__(blah blah blah): wx.Frame.__init.__(blah blah blah) self.panel = wx.Panel(self, -1) self.panel.SetBackgroundColour((I put a random RGB here for test purposes)) c_color = wx.Button(self.p...
Why doesn't this work (wxpython/color dialog)
class iFrame(wx.Frame): def __init__(blah blah blah): wx.Frame.__init.__(blah blah blah) self.panel = wx.Panel(self, -1) self.panel.SetBackgroundColour((I put a random RGB here for test purposes)) c_color = wx.Button(self.panel, -1, 'Press To Change Color') c_colo...
[ "The line dlg = wx.ColourDialog().SetChooseFull(1) seems like a bug -- isn't SetChooseFull a method on wx.ColourData?\nI made a few changes to get it working and commented the code to illustrate:\ndef OnCC(self, evt):\n data = wx.ColourData()\n data.SetChooseFull(True)\n\n # set the first custom color (ind...
[ 3 ]
[]
[]
[ "colordialog", "python", "wxpython" ]
stackoverflow_0006210032_colordialog_python_wxpython.txt
Q: Using the dbm module in Python 3 I'm learning about database files and the dbm module in Python 3.1.3, and am having trouble using some of the methods from the anydbm module in Python 2. The keys method works fine, import dbm db = dbm.open('dbm', 'c') db['modest'] = 'mouse' db['dream'] = 'theater' for key in db....
Using the dbm module in Python 3
I'm learning about database files and the dbm module in Python 3.1.3, and am having trouble using some of the methods from the anydbm module in Python 2. The keys method works fine, import dbm db = dbm.open('dbm', 'c') db['modest'] = 'mouse' db['dream'] = 'theater' for key in db.keys(): print(key) yields: b'mode...
[ "I think this depends which implementation it chooses to use. On my system, dbm in Python 3 chooses to use ndbm, which is equivalent to the dbm module in Python 2. When I use that module explicitly, I see the same limitations.\nIt appears anydbm in Python 2 chooses dumbdbm, which is slower, but does support the ful...
[ 2, 1 ]
[]
[]
[ "database", "dbm", "python", "python_3.x" ]
stackoverflow_0006204318_database_dbm_python_python_3.x.txt
Q: Parsing a tab-delimited text file to replace columns with one vertical list (Python) I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list. I have the following code: for line in open('feddocs_2011.txt', '...
Parsing a tab-delimited text file to replace columns with one vertical list (Python)
I'm very new to Python and I know this is a pretty basic question. I have a text file with columns of data. I want to remove the columns and make it one long list. I have the following code: for line in open('feddocs_2011.txt', 'r'): segmentedLine = line.split("/t") print segmentedLine This seems to create a ...
[ "You've got the lines split properly in the first loop. What you want to do then is have a second for loop to iterate over each tab-separated item. That'll look like this:\nfor line in open('feddocs_2011.txt', 'r'):\n segmentedLine = line.split(\"\\t\")\n for item in segmentedLine:\n print item\n\nOr m...
[ 5, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006209949_python.txt
Q: How to use squid proxy server to modify html page before sending to client I am looking to setup a proxy server and I want to run some python script(or any other language) to filter out some content on the html pages, the client requests through proxy server. Is there a way to do that? Thanks A: Take a look at I...
How to use squid proxy server to modify html page before sending to client
I am looking to setup a proxy server and I want to run some python script(or any other language) to filter out some content on the html pages, the client requests through proxy server. Is there a way to do that? Thanks
[ "Take a look at ICAP and ECAP: http://wiki.squid-cache.org/Features/ICAP and http://wiki.squid-cache.org/Features/eCAP. They accomplish the same goal - ICAP is via an external helper daemon (which you'd need to code on your own) and ECAP uses plugins.\n", "It is not the task of Squid to modify your HTML.\nUse som...
[ 3, 0 ]
[]
[]
[ "html", "http", "proxy", "python", "squid" ]
stackoverflow_0005799319_html_http_proxy_python_squid.txt
Q: Python Web Framework for Small Team I have 4 days off and I will use this time to rewrite our RoR (Ruby on Rails) Application in a python web framework just for fun ;-] (and why not make the switch, RoR is great but keep changing all the time, can be exhausting.) I don't know the python web framework very well, I'...
Python Web Framework for Small Team
I have 4 days off and I will use this time to rewrite our RoR (Ruby on Rails) Application in a python web framework just for fun ;-] (and why not make the switch, RoR is great but keep changing all the time, can be exhausting.) I don't know the python web framework very well, I've glad web.py, django, cherry.py, pylons...
[ "I think most of the big frameworks will fit your requirements so maybe you might look at it from the perspective of the app you are writing. How much do you want to work \"out of the box\". Will you need user management? Will you need an admin panel etc.\nI use Django and it's great when you don't want to rewrite ...
[ 4, 3, 1, 0, 0 ]
[]
[]
[ "cherrypy", "django", "pylons", "python" ]
stackoverflow_0006207211_cherrypy_django_pylons_python.txt
Q: Getting script error in YouTube Python download script When I try to download the playlist with the youtube-dl Python script I get this error. no fmt_url_map or conn information found in video info Error no fmt_url_map or conn information found in video info with specific video explains the problem and solution,...
Getting script error in YouTube Python download script
When I try to download the playlist with the youtube-dl Python script I get this error. no fmt_url_map or conn information found in video info Error no fmt_url_map or conn information found in video info with specific video explains the problem and solution, but I don't know how can I apply the solution. What do I ne...
[ "It works perfectly fine with videos:\n$ git clone https://github.com/rg3/youtube-dl.git\n$ ./youtube-dl http://www.youtube.com/watch?v=VHkPiU9YAQk\n\nThen you can play the video \"VHkPiU9YAQk.mp4\"\nAlso with playlists:\n$ ./youtube-dl --playlist-start=1 --playlist-end=1 http://www.youtube.com/my_playlists?p=AA0F...
[ 1 ]
[]
[]
[ "download", "python", "youtube" ]
stackoverflow_0006211110_download_python_youtube.txt
Q: QuickFix C# or Python We are about to implement a small automated securities trader. The trader will be build on top of the excellent quickfix FIX engine. After due though, we narrowed our options down to implementing it in C# or in Python. Please specify the pros and cons of each language for this task, in term ...
QuickFix C# or Python
We are about to implement a small automated securities trader. The trader will be build on top of the excellent quickfix FIX engine. After due though, we narrowed our options down to implementing it in C# or in Python. Please specify the pros and cons of each language for this task, in term of: Performance (The fact ...
[ "I like both languages and a think both would be a good choice. The GIL might really be the most important difference. But I'm not sure if it's a problem in your case. The GIL only affects code running in pure Python. I assume that your tool depends more on I/O than on raw number crunching. If your I/O libraries ha...
[ 2, 0 ]
[]
[]
[ "c#", "python", "quickfix" ]
stackoverflow_0006210869_c#_python_quickfix.txt
Q: get array values in python I have the values arr1 as 25,26 and arr2 values as A,B Its always that the number of values in arr1 and arr2 are equal My question is that for i in arr1.split(","): print i //prints 25 and 26 is it not possible to get the values of arr2 in the same loop or sho...
get array values in python
I have the values arr1 as 25,26 and arr2 values as A,B Its always that the number of values in arr1 and arr2 are equal My question is that for i in arr1.split(","): print i //prints 25 and 26 is it not possible to get the values of arr2 in the same loop or should another loop be written onl...
[ "You can use zip() function:\nfor zipped in zip(arr1.split(\",\") , arr2.split(\",\")):\n someDictionary[zipped[0]] = zipped[1]\n\nzip() creates tuple for each pair of items in collections, then you map one to another. If your 'arrays' have diffrent length, you can use map():\na = [1,3,4]\nb = [3,4]\nprint map(N...
[ 7, 5, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006211668_python.txt
Q: How do I work with "image data as a byte string", using Python? First I'm going to explain what I'm trying to do and then explain my problem. Okay so I've been making prototypes on a project that I hope to be working on over the summer. The project is a small media player and one of the requirements is to display ...
How do I work with "image data as a byte string", using Python?
First I'm going to explain what I'm trying to do and then explain my problem. Okay so I've been making prototypes on a project that I hope to be working on over the summer. The project is a small media player and one of the requirements is to display the albulm artwork of an mp3 file. After some research I found this ...
[ "Have you tried pygame.image.fromstring()? \nnote: since it's raw data, you'll need to know in advance a few details such as the resolution and colour depth. \n" ]
[ 1 ]
[]
[]
[ "byte", "image", "pygame", "python" ]
stackoverflow_0006211702_byte_image_pygame_python.txt
Q: Empty STARTED task in Django Admin Monitor Have empty record in Django Admin Monitor in Tasks section. It appears once per few hours. Everything works good, but looks like sometimes data is missed. Backend is custom for Amazon SQS. I am almost sure that problem is here, but I can't reproduce this. Maybe some one ...
Empty STARTED task in Django Admin Monitor
Have empty record in Django Admin Monitor in Tasks section. It appears once per few hours. Everything works good, but looks like sometimes data is missed. Backend is custom for Amazon SQS. I am almost sure that problem is here, but I can't reproduce this. Maybe some one have proposition what can cause such behavior or...
[ "sometime happened also to me, but only when I'm playing with the cam, sometimes when I stop it and restart after a bit seems that cam lost some info.\nI think that your celery cam sometime miss some infos or don't receive some signal for some reason. Make also sure that you have just one celerycam process running...
[ 0 ]
[]
[]
[ "celery", "python" ]
stackoverflow_0005950055_celery_python.txt
Q: Share a resource between two processes I want to know the best practices followed to share a queue (resource) between two processes in Python. Here is a what each process is doing: Process_1: continuously gets data (in json format) from a streaming api Process_2: is a daemon (similar to Sander Marechal's code) whi...
Share a resource between two processes
I want to know the best practices followed to share a queue (resource) between two processes in Python. Here is a what each process is doing: Process_1: continuously gets data (in json format) from a streaming api Process_2: is a daemon (similar to Sander Marechal's code) which commits data (one at a time) into a datab...
[ "multiprocessing.pool isn't what you want in this case - it is useful for having multiple units of work done 'in the background' (concurrently), not so much for managing a shared resource. Since you appear to have the format of the communications worked out, and they communicate in only one direction, what you want...
[ 6 ]
[]
[]
[ "producer_consumer", "python", "shared_resource" ]
stackoverflow_0006211654_producer_consumer_python_shared_resource.txt
Q: tput cup in python on the commandline Is there an elegant solution to do this shell script in Python without importing os ? tput cup 14 15; echo -ne "\033[1;32mtest\033[0m" ; tput cup 50 0 This just has been gnawing in my mind for some time now :) Thanks A: Thanks Ignacio Vazquez-Abrams for your input, it w...
tput cup in python on the commandline
Is there an elegant solution to do this shell script in Python without importing os ? tput cup 14 15; echo -ne "\033[1;32mtest\033[0m" ; tput cup 50 0 This just has been gnawing in my mind for some time now :) Thanks
[ "Thanks Ignacio Vazquez-Abrams for your input, it was a great push in the right direction.\nIn the end i came up with this little code that will help me conquer the world :)\nfrom curses import *\nsetupterm()\n\n#cols = tigetnum(\"cols\")\n#lines = tigetnum(\"lines\")\n#print str(cols) + \"x\" + str(lines)\n\nplace...
[ 7, 6, 5 ]
[]
[]
[ "printing", "python", "terminal" ]
stackoverflow_0006199285_printing_python_terminal.txt
Q: Can I open UNIX POSIX ports from Python? Can I open UNIX POSIX ports from Python 2.7 ( I don't need IP port, just UNIX POSIX) ? Does anybody have experience with this ? A: I assume you are talking about Unix domain sockets (I'm not sure what you mean by "UNIX POSIX port"... IP sockets have ports, Unix sockets do...
Can I open UNIX POSIX ports from Python?
Can I open UNIX POSIX ports from Python 2.7 ( I don't need IP port, just UNIX POSIX) ? Does anybody have experience with this ?
[ "I assume you are talking about Unix domain sockets (I'm not sure what you mean by \"UNIX POSIX port\"... IP sockets have ports, Unix sockets don't). The standard system calls are available through a thin wrapper.\nimport socket\ns = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\ns.bind(\"/path/to/socket\")\ns...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006212109_python.txt
Q: Getting a number of digits I've been searching for a way in python to get only 4 digits on the right of the comma of a decimal number, but i couldn't find. Took a look on this post,---> Rounding decimals with new Python format function ,but the function written there... >>> n = 4 >>> p = math.pi >>> ...
Getting a number of digits
I've been searching for a way in python to get only 4 digits on the right of the comma of a decimal number, but i couldn't find. Took a look on this post,---> Rounding decimals with new Python format function ,but the function written there... >>> n = 4 >>> p = math.pi >>> '{0:.{1}f}'.format(p, n) '3....
[ "\"%.3f\" % math.pi\n\nI know its using the old syntax but I personally prefer it. \n", "What you have is fine (rounding the 5 up to a 6)\nIf you want truncation instead of rounding you could go:\nfrom math import pi as p\nprint p\nprint int(p*10**4)/10.0**4\n\np=str(p).split(\".\")\np[1]=p[1][:4]\nprint \".\".jo...
[ 7, 2, 1 ]
[]
[]
[ "decimal", "python", "rounding" ]
stackoverflow_0006212220_decimal_python_rounding.txt
Q: Get email subject and sender using imaplib? I am getting the following response after executing the code shown below the response. How can I parse through this response to get the sender (John Smith) and the subject (test)? [('13010 (BODY[HEADER.FIELDS (SUBJECT FROM)] {57}', 'From: John Smith <jsmith@gmail.com>\r\...
Get email subject and sender using imaplib?
I am getting the following response after executing the code shown below the response. How can I parse through this response to get the sender (John Smith) and the subject (test)? [('13010 (BODY[HEADER.FIELDS (SUBJECT FROM)] {57}', 'From: John Smith <jsmith@gmail.com>\r\nSubject: test\r\n\r\n'), ')'] - conn.fetch(mess...
[ "Perhaps the question/answer here will help. Try something like this:\nfrom email.parser import HeaderParser\ndata = conn.fetch(message, '(BODY[HEADER.FIELDS (SUBJECT FROM)])')\nheader_data = data[1][0][1]\nparser = HeaderParser()\nmsg = parser.parsestr(header_data)\n\nand then msg should be a dictionary.\n", "Yo...
[ 8, 4 ]
[]
[]
[ "imap", "imaplib", "python" ]
stackoverflow_0006209616_imap_imaplib_python.txt
Q: Upgrading Pyramid/SQLAlchemy web apps I've got a standard run of the mill Pylons Pyramid application, that uses SQLAlchemy for its database persistence. I have set up an SQLAlchemy-migrate repo and have it functioning, but I really want to have the ability to use paster to upgrade and downgrade the database, or at...
Upgrading Pyramid/SQLAlchemy web apps
I've got a standard run of the mill Pylons Pyramid application, that uses SQLAlchemy for its database persistence. I have set up an SQLAlchemy-migrate repo and have it functioning, but I really want to have the ability to use paster to upgrade and downgrade the database, or at least some way of having the user (after i...
[ "You can create your own paster command, e.g. upgrade-app, and then call it from anywhere with paster --plugin=appname upgrade-app /path/to/production.ini appname. You can refer to how pyramid implements the PShellCommand.\n", "It's not quite what you're looking for, but one way I handle this is with Fabric comma...
[ 1, 0 ]
[]
[]
[ "paster", "pyramid", "python", "sqlalchemy", "sqlalchemy_migrate" ]
stackoverflow_0006092888_paster_pyramid_python_sqlalchemy_sqlalchemy_migrate.txt
Q: string manipulation: partly convert to lowercase As the title says: What's best way of converting a string from any-case to lowercase keeping a portion unchanged? e.g. a string like: FormatDate(%M)==2 or stArTDate(%Y/%m)==11/3 and I want to convert it to formatdate(%M)==2 or startdate(%Y/%m)==11/3 i.e. change it t...
string manipulation: partly convert to lowercase
As the title says: What's best way of converting a string from any-case to lowercase keeping a portion unchanged? e.g. a string like: FormatDate(%M)==2 or stArTDate(%Y/%m)==11/3 and I want to convert it to formatdate(%M)==2 or startdate(%Y/%m)==11/3 i.e. change it to lowercase except the part in between the braces (). ...
[ "Do your strings always look exactly like this? If so, maybe this is enough:\np1,p2 = instr.split('(',1)\nlc = '%s(%s' % (p1.lower(), p2)\n\n", "I don't think you can get much more \"Pythonic\" than this:\nPython 2.7.1 (r271:86832, May 27 2011, 21:41:45) \n[GCC 4.2.1 (Apple Inc. build 5664)] on darwin\nType \"hel...
[ 5, 3, 2, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006212936_python.txt
Q: Database Library/ORM mapper without configuration I'm currently planning an application that does work on an object relational database. The work is simple: just fetch data, analyse it, display it to the user and write back some changes. To support a wide range of databases I'm currently searching for access libra...
Database Library/ORM mapper without configuration
I'm currently planning an application that does work on an object relational database. The work is simple: just fetch data, analyse it, display it to the user and write back some changes. To support a wide range of databases I'm currently searching for access library that meets all (or at least some) of the following r...
[ "You could use SQLAlchemy which uses zxJDBC on Jython. Django can also run on Jython, so that's another option. Both let you use Python to declare your models. Django's ORM is a bit less verbose, while SQLAlchemy is arguably more powerful, and tends to offer finer control. There is also a nice declarative wrapper f...
[ 1 ]
[]
[]
[ "database", "java", "jython", "python" ]
stackoverflow_0006212602_database_java_jython_python.txt
Q: Is it possible to access parent class's members from a nested class in an aggregation My Question is, say i declare a class within a class, as a sort of an aggregation: class A: self.foo = 20 self.bar = 30 def someFunc(self): class B: # some code here BObject = B() is i...
Is it possible to access parent class's members from a nested class in an aggregation
My Question is, say i declare a class within a class, as a sort of an aggregation: class A: self.foo = 20 self.bar = 30 def someFunc(self): class B: # some code here BObject = B() is it possible to access the foo/bar variables from within class B ? If yes, then how ? I have ...
[ "class A(object):\n foo = 20\n bar = 30\n def build_b(self):\n class B(object):\n foo = self.foo\n bar = self.bar\n return B()\n\nThen you could do:\n>>> b_obj = A().build_b()\n\n>>> b_obj.foo, b_obj.bar\n<<< (20, 30)\n\nBut, you should really break class B out of class ...
[ 1, 0 ]
[]
[]
[ "aggregation", "class", "python" ]
stackoverflow_0006212105_aggregation_class_python.txt
Q: How to SWIG in VS2010? Hey Everybody, I'm trying to SWIG a multi file project that I made in VS2010 (c++) to python. I've managed to link the Python26.lib file, and have SWIG generating a wrapper .cpp file for my main .cpp file. I've set my code to build a .dll with the extension .pyd. This is the .i file I h...
How to SWIG in VS2010?
Hey Everybody, I'm trying to SWIG a multi file project that I made in VS2010 (c++) to python. I've managed to link the Python26.lib file, and have SWIG generating a wrapper .cpp file for my main .cpp file. I've set my code to build a .dll with the extension .pyd. This is the .i file I have currently: %module HiveG...
[ "Ok, I'm using swig and VS2010 with no problems... \nIn your case, it looks more like you have problems with linking. Beyond the check of libraries, dont forget to check 32-64 bit libraries you are linking. Try to link all as x86 target as fail-safe. And don't use AnyCpu.\n\nHow to use SWIG under VS2010.\nlets defi...
[ 11, 0 ]
[]
[]
[ "c++", "python", "swig", "visual_studio_2010" ]
stackoverflow_0005969173_c++_python_swig_visual_studio_2010.txt
Q: accessing the return value of function that was bound to an event (tkinter) Basically, what I've done is bound a click event to a function. For example: self.button1.bind("<Button-1>",self.chooseDice) What I want now is to access the result of chooseDice() in another function. What is the best way to go about d...
accessing the return value of function that was bound to an event (tkinter)
Basically, what I've done is bound a click event to a function. For example: self.button1.bind("<Button-1>",self.chooseDice) What I want now is to access the result of chooseDice() in another function. What is the best way to go about doing that? class GraphicsInterface: #we want to initialize the game board he...
[ "You are already doing what you need to do. Your example code sets self.diceList to some value. Anywhere else in your code you can directly use self.diceList.\nBy the way -- you're writing code that is going to be hard to maintain over time. For example, what if you change the dice label to \"Dice One\" or simply \...
[ 2, 1, 1 ]
[]
[]
[ "bind", "events", "python", "tkinter" ]
stackoverflow_0006209660_bind_events_python_tkinter.txt
Q: Google App engine - submitting form field "field[key]" So my question is, how I can get form values as list when submitting this particular form: <form action="/foobar" method="post"> <input type="text" value="text 1" name="text[key_1]" /> <input type="text" value="text 2" name="text[key_2]" /> <input type="text"...
Google App engine - submitting form field "field[key]"
So my question is, how I can get form values as list when submitting this particular form: <form action="/foobar" method="post"> <input type="text" value="text 1" name="text[key_1]" /> <input type="text" value="text 2" name="text[key_2]" /> <input type="text" value="text 3" name="text[key_3]" /> <input type="text" val...
[ "I guess you are using webapp framework. To get key/value pairs. you can do something like this\nif your method is GET,\nself.request.str_GET.items()\n\nelse\nself.request.str_POST.items()\n\nMore reference here \n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006212282_google_app_engine_python.txt
Q: Finding the calculation that generates a NaN I have a moderately large piece (a few thousand lines) of Python/Numpy/Scipy code that is throwing up NaNs with certain inputs. I've looked for, and found, some of the usual suspects (log(0) and the like), but none of the obvious ones seem to be the culprits in this cas...
Finding the calculation that generates a NaN
I have a moderately large piece (a few thousand lines) of Python/Numpy/Scipy code that is throwing up NaNs with certain inputs. I've looked for, and found, some of the usual suspects (log(0) and the like), but none of the obvious ones seem to be the culprits in this case. Is there a relatively painless way (i.e., apar...
[ "I would start with numpy.seterr.\nThere, an invalid operation is defined as \"result is not an expressible number, typically indicates that a NaN was produced\". By default, this seems to be set to \"ignore\".\n", "You can use numpy.seterr to set floating point error handling behaviour globally for all numpy rou...
[ 9, 3 ]
[]
[]
[ "debugging", "nan", "numpy", "python", "scipy" ]
stackoverflow_0006213869_debugging_nan_numpy_python_scipy.txt
Q: Working with Beaker Cache and SQLAlchemy I'm trying to use beaker cache with SQLAlchemy but I've been receiving errors. Here are my table definitions. class Post(Base): .... .... user = relation(User, primaryjoin = User.id == id) tags = relation('Tags', backref = 'posts') class Tags(Base): ... ... ...
Working with Beaker Cache and SQLAlchemy
I'm trying to use beaker cache with SQLAlchemy but I've been receiving errors. Here are my table definitions. class Post(Base): .... .... user = relation(User, primaryjoin = User.id == id) tags = relation('Tags', backref = 'posts') class Tags(Base): ... ... user = relation(User, primaryjoin = User.id ...
[ "when you grab objects from cache, you should associate them with a session object, eg.\nobj_from_cache = get_from_cache(key)\nsession.merge(obj_from_cache)\n\n" ]
[ 2 ]
[]
[]
[ "beaker", "caching", "python", "sqlalchemy" ]
stackoverflow_0005033382_beaker_caching_python_sqlalchemy.txt
Q: OR Condition Return Error in GQL ( Google app engine) Why? When i use the OR condion in GQL it return error messege tht "BadQueryError: Parse Error: Expected no additional symbols at symbol OR . Why? db.GqlQuery("Select * from vendor where access='public' OR organisation_id='"+ orgid +"'") A: GQL does not h...
OR Condition Return Error in GQL ( Google app engine) Why?
When i use the OR condion in GQL it return error messege tht "BadQueryError: Parse Error: Expected no additional symbols at symbol OR . Why? db.GqlQuery("Select * from vendor where access='public' OR organisation_id='"+ orgid +"'")
[ " GQL does not have an OR operator. However, it does have an IN operator, \nwhich provides a limited form of OR.\n\nDocs clearly says that GQL doesn't have an OR operator..\nYou could do something like this ..Make two queries and combine the results...\n vendors=vendor.all()\n pub_vendors = vendors.filter(\"ac...
[ 3 ]
[]
[]
[ "google_app_engine", "gql", "gqlquery", "python" ]
stackoverflow_0006214431_google_app_engine_gql_gqlquery_python.txt
Q: CouchDB POST response, which was sent via curl via Python's subprocess module, is getting lost (curl code 53). Why is that? I'm trying to add a document to couchDB from python using curl via the subprocess module. I can do it fine from the command line but not from python. Here is the command line code curl -X POS...
CouchDB POST response, which was sent via curl via Python's subprocess module, is getting lost (curl code 53). Why is that?
I'm trying to add a document to couchDB from python using curl via the subprocess module. I can do it fine from the command line but not from python. Here is the command line code curl -X POST http://doug:enter@localhost:5984/mydb/ -H "Content-Type: application/json" -d {} The document is created each and every time w...
[ "You aren't including shell=True. Subprocess won't use your shell if you don't, so you'll have differences from running on the command line.\nretcode = subprocess.call(args, shell=True)\n\nThat should fix your problem. Note that this may cause args to not work quite correctly, as it may want a string instead. If th...
[ 2 ]
[]
[]
[ "couchdb", "python", "subprocess" ]
stackoverflow_0006214439_couchdb_python_subprocess.txt
Q: Counting with python dictionaries and adding functionality a = 0 b = 0 c = 0 d = 0 fruit = { 'lemons': [], 'apples': [], 'cherries': [], 'oranges': [], } def count(): fruit = input("What fruit are you getting at the store? ") if fruit == 'lemons': fruit['lemons'] = a + 1 elif fruit == 'a...
Counting with python dictionaries and adding functionality
a = 0 b = 0 c = 0 d = 0 fruit = { 'lemons': [], 'apples': [], 'cherries': [], 'oranges': [], } def count(): fruit = input("What fruit are you getting at the store? ") if fruit == 'lemons': fruit['lemons'] = a + 1 elif fruit == 'apples': fruit['apples'] = b + 1 elif fruit ...
[ "You seem to have multiple variables called fruit, that's a bad idea. And if you're just counting, you should start with 0, not []. You can write your code way easier as:\nimport collections\nresult = collections.defaultdict(int)\ndef count():\n fruit = input(\"What fruit are you getting at the store? \")\n r...
[ 4, 0 ]
[]
[]
[ "counter", "dictionary", "python" ]
stackoverflow_0006214534_counter_dictionary_python.txt
Q: Python and performance of list comprehensions Suppose you have got a list comprehension in python, like Values = [ f(x) for x in range( 0, 1000 ) ] with f being just a function without side effects. So all the entries can be computed independently. Is Python able to increase the performance of this list comprehen...
Python and performance of list comprehensions
Suppose you have got a list comprehension in python, like Values = [ f(x) for x in range( 0, 1000 ) ] with f being just a function without side effects. So all the entries can be computed independently. Is Python able to increase the performance of this list comprehension compared with the "obvious" implementation; e....
[ "In Python 3.2 they added concurrent.futures, a nice library for solving problems concurrently. Consider this example:\nimport math, time\nfrom concurrent import futures\n\nPRIMES = [112272535095293, 112582705942171, 112272535095293, 115280095190773, 115797848077099, 1099726899285419, 112272535095293, 1125827059421...
[ 9, 8, 0 ]
[]
[]
[ "list_comprehension", "performance", "python" ]
stackoverflow_0006214091_list_comprehension_performance_python.txt
Q: python sqlite3 not working try: c = db.cursor() c.execute("insert or replace into registrations values " + "(?, ?, datetime('now'))", (user, identity)) print '\t<update>true</update>' except Exception,inst: print inst.args insert create table not working. How do I fetch the exception...
python sqlite3 not working
try: c = db.cursor() c.execute("insert or replace into registrations values " + "(?, ?, datetime('now'))", (user, identity)) print '\t<update>true</update>' except Exception,inst: print inst.args insert create table not working. How do I fetch the exception details?
[ "If you read this Python PEP, it should describe the exception classes for the Sqlite Python module. \nHave you tried something like this:\ntry:\n db_cursor.execute('some hopefully valid SQL;')\nexcept sqlite3.Error, msg:\n print msg\n\n" ]
[ 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006215200_python_sqlite.txt
Q: python: Using the choice box to get data besides getString() I have defined an object that has several attribute.. class thing(object): def __init__(self, type, name, attrA, attrB, attrC): self.type = type self.name = name self.attrA = attrA self.attrB = attrB self.attrC...
python: Using the choice box to get data besides getString()
I have defined an object that has several attribute.. class thing(object): def __init__(self, type, name, attrA, attrB, attrC): self.type = type self.name = name self.attrA = attrA self.attrB = attrB self.attrC = attrC lets say then I have a list of things self.things=[thing...
[ "Associating data or objects with wx.Choice or wx.ComboBox is pretty easy. You can see an example using the latter here:\nhttp://www.blog.pythonlibrary.org/2010/12/16/wxpython-storing-object-in-combobox-or-listbox-widgets/\nThe basic idea is to pass an empty list to the control's constructor and then iterate over t...
[ 2 ]
[]
[]
[ "list", "python", "wxpython" ]
stackoverflow_0006214878_list_python_wxpython.txt