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: Pass to python method based on length of a list I have a list called 'optionlist' which may change length from day to day, but I want a tkinter dropdown box to be able to select something from it. Here's an example of how to define a tkinter optionmenu: opt1 = OptionMenu(root, var1, 'A', 'B', 'C') A, B, and C ...
Pass to python method based on length of a list
I have a list called 'optionlist' which may change length from day to day, but I want a tkinter dropdown box to be able to select something from it. Here's an example of how to define a tkinter optionmenu: opt1 = OptionMenu(root, var1, 'A', 'B', 'C') A, B, and C are the options you can select. The problem presented...
[ "You want the * operator:\nopt1 = OptionMenu(root, var1, *optionlist)\n\n" ]
[ 11 ]
[]
[]
[ "parameters", "python" ]
stackoverflow_0000735878_parameters_python.txt
Q: PyQt connect method bug when used in a for loop which creates widgets from a list I have a GUI program, It auto create buttons from a name list, and connect to a function prints its name. but when I run this program, I press all the buttons, they all return the last button's name. I wonder why this thing happen...
PyQt connect method bug when used in a for loop which creates widgets from a list
I have a GUI program, It auto create buttons from a name list, and connect to a function prints its name. but when I run this program, I press all the buttons, they all return the last button's name. I wonder why this thing happens. can any one help? import sys from PyQt4.QtCore import * from PyQt4.QtGui import * im...
[ "I see at least one bug in your code.\nReplace: \n lambda :logging.debug(name)\n\nBy:\n lambda name=name: logging.debug(name)\n\nSee Why results of map() and list comprehension are different? for details.\n" ]
[ 3 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0000736651_pyqt_python.txt
Q: Ping FeedBurner in Django App I have a django site, and some of the feeds are published through FeedBurner. I would like to ping FeedBurner whenever I save an instance of a particular model. FeedBurner's website says to use the XML-RPC ping mechanism, but I can't find a lot of documentation on how to implement it....
Ping FeedBurner in Django App
I have a django site, and some of the feeds are published through FeedBurner. I would like to ping FeedBurner whenever I save an instance of a particular model. FeedBurner's website says to use the XML-RPC ping mechanism, but I can't find a lot of documentation on how to implement it. What's the easiest way to do the X...
[ "You can use Django's signals feature to get a callback after a model is saved:\nimport xmlrpclib\nfrom django.db.models.signals import post_save\nfrom app.models import MyModel\n\ndef ping_handler(sender, instance=None, **kwargs):\n if instance is None:\n return\n rpc = xmlrpclib.Server('http://ping.f...
[ 12, 2, 1 ]
[]
[]
[ "django", "python", "xml_rpc" ]
stackoverflow_0000736413_django_python_xml_rpc.txt
Q: Import XML into SQL database I'm working with a 20 gig XML file that I would like to import into a SQL database (preferably MySQL, since that is what I am familiar with). This seems like it would be a common task, but after Googling around a bit I haven't been able to figure out how to do it. What is the best way ...
Import XML into SQL database
I'm working with a 20 gig XML file that I would like to import into a SQL database (preferably MySQL, since that is what I am familiar with). This seems like it would be a common task, but after Googling around a bit I haven't been able to figure out how to do it. What is the best way to do this? I know this ability i...
[ "You can use the getiterator() function to iterate over the XML file without parsing the whole thing at once. You can do this with ElementTree, which is included in the standard library, or with lxml.\nfor record in root.getiterator('record'):\n add_element_to_database(record) # Depends on your database interfac...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "python", "sql", "xml" ]
stackoverflow_0000723757_python_sql_xml.txt
Q: How to read ID3 Tag in an MP3 using Python? Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-) A: Dive into Python uses MP3 ID3 tags as an example. A: Mutagen https://bitbucket.org/lazka/mutagen Ed...
How to read ID3 Tag in an MP3 using Python?
Does anyone has an experience of reading and writing ID3 tags in an MP3 file or a WMA file? There are some libraries but I would like to do it from the scratch. :-)
[ "Dive into Python uses MP3 ID3 tags as an example.\n", "Mutagen https://bitbucket.org/lazka/mutagen\nEdited 14/09/23 with current code host location\neyeD3 http://eyed3.nicfit.net/\n", "Try eyeD3, it's a program and a module.\n", "A quick google showed up http://id3-py.sourceforge.net/\nMaybe this works for y...
[ 14, 13, 3, 2 ]
[]
[]
[ "id3", "mp3", "python", "tags" ]
stackoverflow_0000736813_id3_mp3_python_tags.txt
Q: Pygame: Sprite animation Theory - Need Feedback After some tweaking of some code I got from someone to cause a characters images to move in regards to its direction and up down left right input I've put this together: (hope the code isn't too messy) Character Move Code + IMG The Sprite sheet only runs lengthwise, ...
Pygame: Sprite animation Theory - Need Feedback
After some tweaking of some code I got from someone to cause a characters images to move in regards to its direction and up down left right input I've put this together: (hope the code isn't too messy) Character Move Code + IMG The Sprite sheet only runs lengthwise, so basically each sprite section is a different actio...
[ "It should be easy.\nIf you record the frame number in a variable, you can modulo this with the number of frames you have to get an animation frame number to display.\nframe_count = 0\nanimation_frames = 4\nwhile quit == False:\n # ...\n # snip\n # ...\n area = pygame.Rect(\n image_number * 100,\...
[ 4 ]
[]
[]
[ "2d", "pygame", "python", "sprite" ]
stackoverflow_0000737303_2d_pygame_python_sprite.txt
Q: Returning default members when accessing to objects in python I'm writing an "envirorment" where each variable is composed by a value and a description: class my_var: def __init__(self, value, description): self.value = value self.description = description Variables are created and put inside a dic...
Returning default members when accessing to objects in python
I'm writing an "envirorment" where each variable is composed by a value and a description: class my_var: def __init__(self, value, description): self.value = value self.description = description Variables are created and put inside a dictionary: my_dict["foo"] = my_var(0.5, "A foo var") This is cool bu...
[ "Two general notes.\n\nPlease use Upper Case for Class Names.\nPlease (unless using Python 3.0) subclass object. class My_Var(object):, for example.\n\nNow to your question.\nLet's say you do\nx= My_Var(0.5, \"A foo var\")\n\nHow does python distinguish between x, the composite object and x's value (x.value)?\nDo ...
[ 3, 2, 2, 1 ]
[]
[]
[ "dynamic_data", "python" ]
stackoverflow_0000737512_dynamic_data_python.txt
Q: How can I make a Python extension module packaged as an egg loadable without installing it? I'm in the middle of reworking our build scripts to be based upon the wonderful Waf tool (I did use SCons for ages but its just way too slow). Anyway, I've hit the following situation and I cannot find a resolution to it:...
How can I make a Python extension module packaged as an egg loadable without installing it?
I'm in the middle of reworking our build scripts to be based upon the wonderful Waf tool (I did use SCons for ages but its just way too slow). Anyway, I've hit the following situation and I cannot find a resolution to it: I have a product that depends on a number of previously built egg files. I'm trying to package ...
[ "Heh, I think this was my bad. The issue appear to have been that the zipsafe flag in setup.py for the extension package was set to False, which appears to affect your ability to treat it as such at all.\nNow that I've set that to True I can import the egg files, simply by adding each one to the PYTHONPATH.\nI hop...
[ 3, 1 ]
[]
[]
[ "build_tools", "egg", "python", "setuptools", "waf" ]
stackoverflow_0000737383_build_tools_egg_python_setuptools_waf.txt
Q: How to Modify Choices of ModelMultipleChoiceField Let's say I have some contrived models: class Author(Model): name = CharField() class Book(Model): title = CharField() author = ForeignKey(Author) And let's say I want to use a ModelForm for Book: class BookForm(ModelForm): class Meta: ...
How to Modify Choices of ModelMultipleChoiceField
Let's say I have some contrived models: class Author(Model): name = CharField() class Book(Model): title = CharField() author = ForeignKey(Author) And let's say I want to use a ModelForm for Book: class BookForm(ModelForm): class Meta: model = Book Simple so far. But let's also say that I...
[ "Although Carl is correct about the fields, you're also missing a super class call. This is how I do it:\nclass BookForm(ModelForm):\n author = ModelMultipleChoiceField(queryset=Author.objects.all())\n\n class Meta:\n model = Book\n\n def __init__(self, *args, **kwargs):\n letter = kwargs.pop...
[ 9, 8 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000738301_django_django_forms_python.txt
Q: In Python, how do I reference a class generically in a static way, like PHP's "self" keyword? PHP classes can use the keyword "self" in a static context, like this: <?php class Test { public static $myvar = 'a'; public static function t() { echo self::$myvar; // Generically reference the current class. ...
In Python, how do I reference a class generically in a static way, like PHP's "self" keyword?
PHP classes can use the keyword "self" in a static context, like this: <?php class Test { public static $myvar = 'a'; public static function t() { echo self::$myvar; // Generically reference the current class. echo Test::$myvar; // Same thing, but not generic. } } ?> Obviously I can't use "self" in thi...
[ "This should do the trick:\nclass C(object):\n my_var = 'a'\n\n @classmethod\n def t(cls):\n print cls.my_var\n\nC.t()\n\n", "In all cases, self.__class__ is an object's class.\nhttp://docs.python.org/library/stdtypes.html#special-attributes\nIn the (very) rare case where you are trying to mess wi...
[ 36, 29 ]
[]
[]
[ "class", "python" ]
stackoverflow_0000738467_class_python.txt
Q: How do I detect if my appengine app is being accessed by an iphone/ipod touch? I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax? A: This is the syntax I was looking for, works with iphone and ipod touch...
How do I detect if my appengine app is being accessed by an iphone/ipod touch?
I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax?
[ "This is the syntax I was looking for, works with iphone and ipod touch:\nuastring = self.request.headers.get('user_agent')\nif \"Mobile\" in uastring and \"Safari\" in uastring:\n # do iphone / ipod stuff\n\n", "This article outlines a few ways of detecting an iPhone through by checking the HTTP_USER_AGENT agen...
[ 7, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "google_app_engine", "iphone", "python", "web_applications" ]
stackoverflow_0000617202_google_app_engine_iphone_python_web_applications.txt
Q: Followup: Multiprocessing or Multithreading for Python simulation software this is a follow up to this. (You don't have to read all the answers, just the question) People explained to me the difference between processes and threads. On the one hand, I wanted processes so I could fully exploit all core of the CPU, ...
Followup: Multiprocessing or Multithreading for Python simulation software
this is a follow up to this. (You don't have to read all the answers, just the question) People explained to me the difference between processes and threads. On the one hand, I wanted processes so I could fully exploit all core of the CPU, on the other hand, passing information between processes was less than ideal, an...
[ "Before using processes, make sure that:\n\nYour algorithm can be parallelized between all the processors.\nYou need this parallelism.\n\nIn my opinion a good rule of thumb is:\n\nMake it work.\nMake it right.\nMake it fast.\n\nSo I'd suggest to “simply” use threads first. Maybe you will realize that even with one ...
[ 2, 0 ]
[]
[]
[ "multicore", "multiprocessing", "multithreading", "python", "simulation" ]
stackoverflow_0000737826_multicore_multiprocessing_multithreading_python_simulation.txt
Q: QFileDialog passing directory to python script Im writing a little python program that goes through an XML file and does some replacement of tags. It takes three arguments, a path from whcih it creates a directory tree, the XML file its reading and the xml file its outputting to. It works fine from the command lin...
QFileDialog passing directory to python script
Im writing a little python program that goes through an XML file and does some replacement of tags. It takes three arguments, a path from whcih it creates a directory tree, the XML file its reading and the xml file its outputting to. It works fine from the command line just passing in arguments. As its not just for me,...
[ "Two potential solutions.\nMethod 1:\nIf you must use the displayText() method, I suggest you wrap the call to displayText() with an explicit string cast:\npath = str(self.pathBox.displayText()) \nxmlFile = str(self.xmlFileBox.displayText()) \noutFileName = str(self.outfileNameBox.displayText())\n\nThe reason is th...
[ 1 ]
[]
[]
[ "parsing", "pyqt", "python", "qfile", "qt" ]
stackoverflow_0000739288_parsing_pyqt_python_qfile_qt.txt
Q: Pretty-printing C# from Python Suppose I wrote a compiler in Python or Ruby that translates a language into a C# AST. How do I pretty-print this AST from Python or Ruby to get nicely indented C# code? Thanks, Joel A: In python the pprint module is available. Depending on how your data is structured it may not re...
Pretty-printing C# from Python
Suppose I wrote a compiler in Python or Ruby that translates a language into a C# AST. How do I pretty-print this AST from Python or Ruby to get nicely indented C# code? Thanks, Joel
[ "In python the pprint module is available.\nDepending on how your data is structured it may not return the result your looking for.\n", "Once you have an AST, this should be very easy. When you walk your AST, all you have to do is keep track of what your current indent level is -- you could use a global for this...
[ 1, 1 ]
[ "One way would be to just print it and then invoke a code formatter.\n" ]
[ -2 ]
[ "c#", "parsing", "pretty_print", "python", "ruby" ]
stackoverflow_0000734413_c#_parsing_pretty_print_python_ruby.txt
Q: Apply multiple negative regex to expression in Python This question is similar to "How to concisely cascade through multiple regex statements in Python" except instead of matching one regular expression and doing something I need to make sure I do not match a bunch of regular expressions, and if no matches are fou...
Apply multiple negative regex to expression in Python
This question is similar to "How to concisely cascade through multiple regex statements in Python" except instead of matching one regular expression and doing something I need to make sure I do not match a bunch of regular expressions, and if no matches are found (aka I have valid data) then do something. I have found ...
[ "\"Squoosh\" all the regexes into one line but put each in a named group using (?P<name>...) then use MatchOjbect.lastgroup to find which matched.\n" ]
[ 2 ]
[]
[]
[ "coding_style", "python", "regex" ]
stackoverflow_0000739651_coding_style_python_regex.txt
Q: Iterating over object instances of a given class in Python Given a class that keeps a registry of its Objects: class Person(object): __registry = [] def __init__(self, name): self.__registry.append(self) self.name = name How would I make the following code work (without using Person.__registr...
Iterating over object instances of a given class in Python
Given a class that keeps a registry of its Objects: class Person(object): __registry = [] def __init__(self, name): self.__registry.append(self) self.name = name How would I make the following code work (without using Person.__registry): for personobject in Person: print personobject While re...
[ "You can make your class object iterable with a simple metaclass.\nclass IterRegistry(type):\n def __iter__(cls):\n return iter(cls._registry)\n\nclass Person(object):\n __metaclass__ = IterRegistry\n _registry = []\n\n def __init__(self, name):\n self._registry.append(self)\n self....
[ 33, 15, 4 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0000739882_oop_python.txt
Q: Is it possible to update a Google calendar from App Engine without logging in as the owner? I'd like to be able to use the Google Data API from an AppEngine application to update a calendar while not logged in as the calendar's owner or the a user that the calendar is shared with. This is in contrast to the examp...
Is it possible to update a Google calendar from App Engine without logging in as the owner?
I'd like to be able to use the Google Data API from an AppEngine application to update a calendar while not logged in as the calendar's owner or the a user that the calendar is shared with. This is in contrast to the examples here: http://code.google.com/appengine/articles/more_google_data.html The login and password ...
[ "It should be possible using OAuth, i havent used it myself but my understanding is the user logs in and then gives your app permission to access their private data (e.g. Calendar records). Once they have authorised your app you will be able to access their data without them logging in.\nHere is an article explain...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python", "web_services" ]
stackoverflow_0000723719_google_app_engine_python_web_services.txt
Q: Python: Locks from `threading` and `multiprocessing` interchangable? Are the locks from the threading module interchangeable with those from the multiprocessing module? A: You can typically use the two interchangeably, but you need to cognizant of the differences. For example, multiprocessing.Event is backed by ...
Python: Locks from `threading` and `multiprocessing` interchangable?
Are the locks from the threading module interchangeable with those from the multiprocessing module?
[ "You can typically use the two interchangeably, but you need to cognizant of the differences. For example, multiprocessing.Event is backed by a named semaphore, which is sensitive to the platform under the application. \nMultiprocessing.Lock is backed by Multiprocessing.SemLock - so it needs named semaphores. In es...
[ 8, 1, 1 ]
[]
[]
[ "locking", "multiprocessing", "multithreading", "python" ]
stackoverflow_0000739687_locking_multiprocessing_multithreading_python.txt
Q: Organizing a large Python project that must share an internal state? I'm currently in the middle of porting a fairly large Perl The problem is that it uses little Perl tricks to make its code available for useing. I've done about the same with Python, making the codebase one big module for importing. I've had a fi...
Organizing a large Python project that must share an internal state?
I'm currently in the middle of porting a fairly large Perl The problem is that it uses little Perl tricks to make its code available for useing. I've done about the same with Python, making the codebase one big module for importing. I've had a firm grasp of Python for a long time, but I have no experience with large pr...
[ "It's really hard to tell without actually being able to see the code, but you should probably just consider importing the items that each module uses, in that module. It's not unusual to have a long list of imports - here's an example from my own website:\n# standard\nimport inspect\nimport linecache\nimport neo_c...
[ 1, 0 ]
[]
[]
[ "code_organization", "project_management", "python" ]
stackoverflow_0000739311_code_organization_project_management_python.txt
Q: Insert Command into Bash Shell Is there any way to inject a command into a bash prompt in Linux? I am working on a command history app - like the Ctrl+R lookup but different. I am using python for this. I will show a list of commands from history based on the user's search term - if the user presses enter, the app...
Insert Command into Bash Shell
Is there any way to inject a command into a bash prompt in Linux? I am working on a command history app - like the Ctrl+R lookup but different. I am using python for this. I will show a list of commands from history based on the user's search term - if the user presses enter, the app will execute the command and print ...
[ "You can do this, but only if the shell runs as a subprocess of your Python program; you can't feed content into the stdin of your parent process. (If you could, UNIX would have a host of related security issues when folks run processes with fewer privileges than the calling shell!)\nIf you're familiar with how Exp...
[ 3, 3, 3, 1 ]
[]
[]
[ "bash", "command", "linux", "python", "shell" ]
stackoverflow_0000524068_bash_command_linux_python_shell.txt
Q: Python: Good place to learn about `multiprocessing.Manager`? I want to learn to use multiprocessing.Manager. I looked at the documentation but it's not easy enough for me. Anyone knows of a good tutorial or something like that? A: The documentation of multiprocessing.Manager contains extensive examples for using...
Python: Good place to learn about `multiprocessing.Manager`?
I want to learn to use multiprocessing.Manager. I looked at the documentation but it's not easy enough for me. Anyone knows of a good tutorial or something like that?
[ "The documentation of multiprocessing.Manager contains extensive examples for using a Manager and the various objects associated with the calss:\n\nManagers provide a way to create data\n which can be shared between different\n processes. A manager object controls a\n server process which manages shared\n objec...
[ 6 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0000740848_multiprocessing_python.txt
Q: Can InstantDjango be Used Rather than the Normal Installation Is it possible to do development just using Instant Django? Do I need to have the normal version working or can I just use this instant version? Has anyone used it? A: It is, of course, possible to use InstantDjango for development. InstantDjango us...
Can InstantDjango be Used Rather than the Normal Installation
Is it possible to do development just using Instant Django? Do I need to have the normal version working or can I just use this instant version? Has anyone used it?
[ "It is, of course, possible to use InstantDjango for development. InstantDjango uses SQLite3, which is a perfectly reasonable relational database for embedded or light/sometimes-moderate use. The whole purpose of django is that the ORM layer gives you database portability.\nThat said, I would not use InstantDjango ...
[ 4 ]
[]
[]
[ "django", "instant", "python" ]
stackoverflow_0000740929_django_instant_python.txt
Q: Django: Adding additional properties to Model Class Object This is using Google App Engine. I am not sure if this is applicable to just normal Django development or if Google App Engine will play a part. If it does, would you let me know so I can update the description of this problem. class MessageModel(db.Model)...
Django: Adding additional properties to Model Class Object
This is using Google App Engine. I am not sure if this is applicable to just normal Django development or if Google App Engine will play a part. If it does, would you let me know so I can update the description of this problem. class MessageModel(db.Model): to_user_id = db.IntegerProperty() to_user = db.StringP...
[ "You should still be able to send it messagesSQL to the template after you've added elements to it via the for loop. Python allows that sort of thing.\nSomething else that might make sense in some cases would be to give your MessageModel methods. For instance, if you have a \ndef since_date_created(self):\n ''...
[ 5, 4 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0000741270_django_google_app_engine_python.txt
Q: Parsing specific elements out of a very large HTML file I have a very large HTML file (several megabytes). I know the data I want is under something like <div class=someName>here</div> What is a good library to parse through the HTML page so I can loop through elements and grab each someName? I want to do this in ...
Parsing specific elements out of a very large HTML file
I have a very large HTML file (several megabytes). I know the data I want is under something like <div class=someName>here</div> What is a good library to parse through the HTML page so I can loop through elements and grab each someName? I want to do this in either C#, Python or C++.
[ "I would use Python and BeautifulSoup for the job. It is very solid at handling this kind of stuff.\nFor your case, you can use SoupStrainer to make BeautifulSoup only parse DIVs in the document that have the class you want, so it doesn't have to have the whole thing in memory.\nFor example, say your document looks...
[ 12, 3, 1, 1, 0 ]
[]
[]
[ "c#", "c++", "html", "parsing", "python" ]
stackoverflow_0000739325_c#_c++_html_parsing_python.txt
Q: Encapsulation vs. inheritance, help making a choice I need to write handlers for several different case types (in Python). The interface for all this types are the same, but the handling logic is different. One option would be defining a common class that receives the particular handler type as one of the __init...
Encapsulation vs. inheritance, help making a choice
I need to write handlers for several different case types (in Python). The interface for all this types are the same, but the handling logic is different. One option would be defining a common class that receives the particular handler type as one of the __init__ parameters: class Handler: def __init__ (self, hand...
[ "I might be missing some subtle intricacy in your question, but given your first example, what precludes you from doing something like this:\nclass HandlerCase1(object):\n def handle_stuff(self, *args, **kwargs):\n print \"Handling case 1\"\n\n\nclass HandlerCase2(object):\n def handle_stuff(self, *arg...
[ 4 ]
[]
[]
[ "abstract_class", "design_patterns", "inheritance", "python" ]
stackoverflow_0000742376_abstract_class_design_patterns_inheritance_python.txt
Q: Code works in global scope but not local scope? This function should be returning 36 but it returns 0. If I run through the logic line by line in interactive mode I get 36. Code from math import * line = ((2, 5), (4, -1)) point = (6, 11) def cross(line, point): #reference: http://www.topcoder.com/tc?module=S...
Code works in global scope but not local scope?
This function should be returning 36 but it returns 0. If I run through the logic line by line in interactive mode I get 36. Code from math import * line = ((2, 5), (4, -1)) point = (6, 11) def cross(line, point): #reference: http://www.topcoder.com/tc?module=Static&d1=tutorials&d2=geometry1 ab = ac = [None, ...
[ "You have ab and ac pointing to the same reference. Change this:\nab = ac = [None, None]\n\nto this:\nab = [None, None]\nac = [None, None]\n\n", "In the line ab = ac = [None, None], you assign the same list to the variables ab and ac. When you change one, you change the other at the same time.\nThe reason it wor...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000742496_python.txt
Q: Discrete Event Queuing Simulation I'm stuck trying to implement a single server queue. I've adapted some pseudocode from Norm Matloff's Simpy tutorial to Python and the code is here. Now I am struggling to find some way to calculate the mean waiting time of a job/customer. At this point my brain has tied itself i...
Discrete Event Queuing Simulation
I'm stuck trying to implement a single server queue. I've adapted some pseudocode from Norm Matloff's Simpy tutorial to Python and the code is here. Now I am struggling to find some way to calculate the mean waiting time of a job/customer. At this point my brain has tied itself into a knot! Any pointers, ideas, tips o...
[ "You should know when each customer arrived in the queue. When they arrive at the server you should add one to the number of customers served as well as accumulate the amount of time he waited. At the end of the simulation you simply divide the accumulated time by the number of customers and you have a mean wait ...
[ 5 ]
[]
[]
[ "python", "queue" ]
stackoverflow_0000742776_python_queue.txt
Q: Immutability and thread safety in Python I'm cleaning some of the Python code I wrote when I was...not as knowledgeable. Primarily I am killing some of the complexity that stemmed from an incomplete understanding of threading in Python. I need to make a list of items thread-safe, and I'd like to do it via immutabl...
Immutability and thread safety in Python
I'm cleaning some of the Python code I wrote when I was...not as knowledgeable. Primarily I am killing some of the complexity that stemmed from an incomplete understanding of threading in Python. I need to make a list of items thread-safe, and I'd like to do it via immutable lists, instead of the usual locking approach...
[ "First of all, appending to a list is already thread-safe in the CPython reference implementation of the Python programming language. In other words, while the language specification doesn't require that the list class be thread-safe, it is anyway. So unless you're using Jython or IronPython or some other Python ...
[ 15, 4 ]
[]
[]
[ "immutability", "multithreading", "python" ]
stackoverflow_0000742882_immutability_multithreading_python.txt
Q: Dynamic processes in Python I have a question concerning Python multiprocessing. I am trying to take a dataset, break into chunks, and pass those chunks to concurrently running processes. I need to transform large tables of data using simple calculations (eg. electrical resistance -> temperature for a thermistor)....
Dynamic processes in Python
I have a question concerning Python multiprocessing. I am trying to take a dataset, break into chunks, and pass those chunks to concurrently running processes. I need to transform large tables of data using simple calculations (eg. electrical resistance -> temperature for a thermistor). The code listed below almost wor...
[ "You haven't overridden the run method. There are two ways with processes (or threads) to have it execute code:\n\nCreate a process specifying target\nSubclass the process, overriding the run method.\n\nOverriding __init__ just means your process is all dressed up with nowhere to go. It should be used to give it ...
[ 1, 1, 0 ]
[]
[]
[ "multiprocessing", "multithreading", "python" ]
stackoverflow_0000740717_multiprocessing_multithreading_python.txt
Q: how to convert string representation bytes back to bytes? I am using SUDS to talk with a web service written by C#. The service recieves a url, crawls its web page, then return its content as byte[]. its type in SOAP is: <s:element minOccurs="0" maxOccurs="1" name="rawByte" type="s:base64Binary" /> sample client ...
how to convert string representation bytes back to bytes?
I am using SUDS to talk with a web service written by C#. The service recieves a url, crawls its web page, then return its content as byte[]. its type in SOAP is: <s:element minOccurs="0" maxOccurs="1" name="rawByte" type="s:base64Binary" /> sample client codes: >>> from suds.client import Client >>> url = "http://WSS...
[ "As the SOAP element says, the bytes are base64-encoded.\nTo decode, use the python module \nbase64.\n", "I need to convert it back to string with the binascii module, like:\n>>> btxt = binascii.a2b_base64(page.rawByte)\n\nthen btxt can be treated as a normal string.\n" ]
[ 3, 2 ]
[]
[]
[ "python", "web_services" ]
stackoverflow_0000743374_python_web_services.txt
Q: Something wrong with output from list in Python I want a Python program to import a list of words from a text file and print out the content of the text file as two lists. The data in the text file is on this form: A Alfa B Betta C Charlie I want a Python program to print out one list with A,B,C and one with Alf...
Something wrong with output from list in Python
I want a Python program to import a list of words from a text file and print out the content of the text file as two lists. The data in the text file is on this form: A Alfa B Betta C Charlie I want a Python program to print out one list with A,B,C and one with Alfa, Betta, Charlie. This is what I've written: english...
[ "You want something like this:\nenglish2german = open(\"english2german.txt\")\nenglist = []\ngerlist = []\n\nfor line in english2german:\n (e, g) = line.split()\n englist.append(e)\n gerlist.append(g)\n\nThe problem with your code before is that englist[i:] is actually a slice of a list, not just a single ...
[ 6, 6, 3, 1, 1, 1 ]
[]
[]
[ "list", "python", "text" ]
stackoverflow_0000743248_list_python_text.txt
Q: setattr with kwargs, pythonic or not? I'm using __init__() like this in some SQLAlchemy ORM classes that have many parameters (upto 20). def __init__(self, **kwargs): for k, v in kwargs.iteritems(): setattr(self, k, v) Is it "pythonic" to set attributes like this? A: Yes. Another way to do this is....
setattr with kwargs, pythonic or not?
I'm using __init__() like this in some SQLAlchemy ORM classes that have many parameters (upto 20). def __init__(self, **kwargs): for k, v in kwargs.iteritems(): setattr(self, k, v) Is it "pythonic" to set attributes like this?
[ "Yes. Another way to do this is.\ndef __init__(self, **kwargs):\n self.__dict__.update( kwargs )\n\n", "Yes, if there's not a \"nicer\" way of supplying the arguments.\nFor example, using your ORM classes you mention, perhaps it would be more Python'y to allow..\ncol = Varchar()\ncol.index = True\ncol.length ...
[ 29, 9, 1 ]
[]
[]
[ "initialization", "python" ]
stackoverflow_0000739625_initialization_python.txt
Q: Django RSS Feed Wrong Domain I have an RSS feed that I'm setting up on my new site using Django. Currently I have an RSS feed being served per user, rather than just one big nasty, global RSS feed. The only problem is that the links that are returned by the RSS feed have the completely wrong domain name in the lin...
Django RSS Feed Wrong Domain
I have an RSS feed that I'm setting up on my new site using Django. Currently I have an RSS feed being served per user, rather than just one big nasty, global RSS feed. The only problem is that the links that are returned by the RSS feed have the completely wrong domain name in the links. The end path is perfectly corr...
[ "May be it's coming from environment variables? Try:\nexport | grep your.mistery.domain\n\nsee if that comes up with anything, do that as the same user under which you are running your Django apps.\nYou know you can always implement your item_link() method which would return the URL that you want, see documentation...
[ 3 ]
[]
[]
[ "django", "python", "rss" ]
stackoverflow_0000742974_django_python_rss.txt
Q: Reading Huge File in Python I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python. My current approach is included below. It takes 30 seconds...
Reading Huge File in Python
I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python. My current approach is included below. It takes 30 seconds. There must be more efficient Py...
[ "If you only need 200 of 50 million lines, then reading all of it into memory is a waste. I would sort the list of search keys and then apply binary search to the file using seek() or something similar. This way you would not read the entire file to memory which I think should speed things up.\n", "Slight optimiz...
[ 11, 7, 4, 3, 3, 2, 0, 0 ]
[]
[]
[ "file_io", "large_files", "performance", "python" ]
stackoverflow_0000744256_file_io_large_files_performance_python.txt
Q: Imports in python are static, any solution? foo.py : i = 10 def fi(): global i i = 99 bar.py : import foo from foo import i print i, foo.i foo.fi() print i, foo.i This is problematic. Why does i not change when foo.i changes? A: What Ross is saying is to restucture foo like so: _i = 10 def getI(): ...
Imports in python are static, any solution?
foo.py : i = 10 def fi(): global i i = 99 bar.py : import foo from foo import i print i, foo.i foo.fi() print i, foo.i This is problematic. Why does i not change when foo.i changes?
[ "What Ross is saying is to restucture foo like so:\n_i = 10\n\ndef getI():\n return _i\n\ndef fi():\n global _i\n _i = 99\n\nThen you will see it works the way you want:\n>>> import foo\n>>> print foo.getI()\n10\n>>> foo.fi()\n>>> print foo.getI()\n99\n\nIt is also 'better' in the sense that you avoid expo...
[ 8, 7, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000744325_python.txt
Q: Do Python regular expressions allow embedded options? In particular, I'd like to know if I can specify an embedded option in the pattern string that will enable multiline mode. That is, typically with Python regular expressions multiline mode is enabled like this: pattern = re.compile(r'foo', re.MULTILINE) I'd l...
Do Python regular expressions allow embedded options?
In particular, I'd like to know if I can specify an embedded option in the pattern string that will enable multiline mode. That is, typically with Python regular expressions multiline mode is enabled like this: pattern = re.compile(r'foo', re.MULTILINE) I'd like a way to get multiline matching by specifying it in the...
[ "yes.\nFrom the docs:\n\n(?iLmsux) (One or more letters from the set 'i',\n 'L', 'm', 's', 'u', 'x'.) \nThe group\n matches the empty string; the letters\n set the corresponding flags: re.I\n (ignore case), re.L (locale\n dependent), re.M (multi-line), re.S\n (dot matches all), re.U (Unicode\n dependent), an...
[ 6 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000744885_python_regex.txt
Q: Python/Django Modeling Question What is the best way to have many children records pointing to one parent record in the same model/table in Django? Is this implementation correct?: class TABLE(models.Model): id = models.AutoField(primary_key=True) parent = models.ForeignKey("TABLE", unique=False) A: Djan...
Python/Django Modeling Question
What is the best way to have many children records pointing to one parent record in the same model/table in Django? Is this implementation correct?: class TABLE(models.Model): id = models.AutoField(primary_key=True) parent = models.ForeignKey("TABLE", unique=False)
[ "Django has a special syntax for ForeignKey for self-joins:\nclass TABLE(models.Model):\n id = models.AutoField(primary_key=True)\n parent = models.ForeignKey('self')\n\nSource (second paragraph)\n", "Two things:\nFirst, you need to allow the possibility of a null value for parent, otherwise your TABLE tree...
[ 10, 2 ]
[]
[]
[ "database", "django", "model", "python" ]
stackoverflow_0000744921_database_django_model_python.txt
Q: Adding a user supplied property (at runtime) to an instance of Expando class in Google App Engine? By creating datastore models that inherit from the Expando class I can make my model-entities/instances have dynamic properties. That is great! But what I want is the names of these dynamic properties to be determine...
Adding a user supplied property (at runtime) to an instance of Expando class in Google App Engine?
By creating datastore models that inherit from the Expando class I can make my model-entities/instances have dynamic properties. That is great! But what I want is the names of these dynamic properties to be determined at runtime. Is that possible? For example, class ExpandoTest (db.Expando): prop1 = db.StringProperty(...
[ "Usually, we use the setattr function directly.\nsetattr( entity_two, 'some_variable', some_value )\n\n", "Just found the solution to my own question. It was really simple but as I am a python noob I ended up posting the question that you see above.\nFor the code sample that I had used, this is what needs to be d...
[ 3, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000746942_google_app_engine_python.txt
Q: How to write ampersand in node attribude? I need to have following attribute value in my XML node: CommandLine="copy $(TargetPath) ..\..\&#x0D;&#x0A;echo dummy > dummy.txt" Actually this is part of a .vcproj file generated in VS2008. &#x0D;&#x0A means line break, as there should be 2 separate commands. I'm using ...
How to write ampersand in node attribude?
I need to have following attribute value in my XML node: CommandLine="copy $(TargetPath) ..\..\&#x0D;&#x0A;echo dummy > dummy.txt" Actually this is part of a .vcproj file generated in VS2008. &#x0D;&#x0A means line break, as there should be 2 separate commands. I'm using Python 2.5 with minidom to parse XML - but unfo...
[ "You should try storing the actual characters (ASCII 13 and ASCII 10) in the attribute value, instead of their already-escaped counterparts.\n\nEDIT: It looks like minidom does not handle newlines in attribute values correctly. \nEven though a literal line break in an attribute value is allowed, but it will face no...
[ 1, 1, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0000746602_python_xml.txt
Q: I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters For example, The function could be something like def RandABCD(n, .25, .34, .25, .25): Where n is the length of the string to be generated and the following numbers are the de...
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters
For example, The function could be something like def RandABCD(n, .25, .34, .25, .25): Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D. I would imagine this is quite simple, however i am having trouble creating a working program. Any help would...
[ "Here's the code to select a single weighted value. You should be able to take it from here. It uses bisect and random to accomplish the work.\nfrom bisect import bisect\nfrom random import random\n\ndef WeightedABCD(*weights):\n chars = 'ABCD'\n breakpoints = [sum(weights[:x+1]) for x in range(4)]\n return ch...
[ 4, 2, 2, 0, 0, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0000744127_python_random.txt
Q: Basic python. Quick question regarding calling a function I've got a basic problem in python, and I would be glad for some help :-) I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: (This is the functiondoc.txt) def autoparts(): list_of_pa...
Basic python. Quick question regarding calling a function
I've got a basic problem in python, and I would be glad for some help :-) I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: (This is the functiondoc.txt) def autoparts(): list_of_parts= open('list_of_parts.txt', 'r') for line in list_of_par...
[ "Some quick points:\n\nYou should not name Python source files \".txt\", you should use \".py\".\nYour indents look wrong, but that might just be Stack Overflow.\nYou need to call the autoparts() function to set up the dictionary.\nThe autoparts() function should probably return the dictionary, to make it usable by...
[ 4, 3, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000746774_python.txt
Q: For each function in class within python In python is it possible to run each function inside a class? EDIT: What i am trying to do is call of the functions inside a class, collect their return variables and work with that. A: yes, you can. Quick and dirty: class foo: def one(self): print "here is o...
For each function in class within python
In python is it possible to run each function inside a class? EDIT: What i am trying to do is call of the functions inside a class, collect their return variables and work with that.
[ "yes, you can.\nQuick and dirty: \nclass foo:\n def one(self):\n print \"here is one\"\n def two(self):\n print \"here is two\"\n def three(self):\n print \"here is three\"\n\n\nobj = foo()\nfor entry in dir(obj):\n print entry, callable(getattr(obj,entry))\n if callable(getattr(...
[ 4, 3, 3, 1, 1, 1 ]
[]
[]
[ "oop", "python", "reflection" ]
stackoverflow_0000742708_oop_python_reflection.txt
Q: Calling unknown Python functions This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question. How do I call a function from a string, i.e. functions_to_call = ["func_1", "func_2", "func_3"] for f in functions_to_call: call f A: You can use t...
Calling unknown Python functions
This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question. How do I call a function from a string, i.e. functions_to_call = ["func_1", "func_2", "func_3"] for f in functions_to_call: call f
[ "You can use the python builtin locals() to get local declarations, eg:\ndef f():\n print \"Hello, world\"\n\ndef g():\n print \"Goodbye, world\"\n\nfor fname in [\"f\", \"g\"]:\n fn = locals()[fname]\n print \"Calling %s\" % (fname)\n fn()\n\nYou can use the \"imp\" module to load functions from use...
[ 19, 14, 8, 6, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000744626_python.txt
Q: benchmarking django apps I'm interested in testing the performance of my django apps as I go, what is the best way to get line by line performance data? note: Googling this returns lots of people benchmarking django itself. I'm not looking for a benchmarks of django, I'm trying to test the performance of the djang...
benchmarking django apps
I'm interested in testing the performance of my django apps as I go, what is the best way to get line by line performance data? note: Googling this returns lots of people benchmarking django itself. I'm not looking for a benchmarks of django, I'm trying to test the performance of the django apps that I'm writing :) Tha...
[ "There's two layers to this. We have most of #1 in place for our testing. We're about to start on #2.\n\nDjango in isolation. The ordinary Django unit tests works well here. Create some tests that cycle through a few (less than 6) \"typical\" use cases. Get this, post that, etc. Collect timing data. This isn...
[ 7, 5 ]
[]
[]
[ "django", "profiling", "python" ]
stackoverflow_0000748130_django_profiling_python.txt
Q: Python: Convert those TinyURL (bit.ly, tinyurl, ow.ly) to full URLS I am just learning python and is interested in how this can be accomplished. During the search for the answer, I came across this service: http://www.longurlplease.com For example: http://bit.ly/rgCbf can be converted to: http://webdesignledger....
Python: Convert those TinyURL (bit.ly, tinyurl, ow.ly) to full URLS
I am just learning python and is interested in how this can be accomplished. During the search for the answer, I came across this service: http://www.longurlplease.com For example: http://bit.ly/rgCbf can be converted to: http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place I did some insp...
[ "Enter urllib2, which offers the easiest way of doing this:\n>>> import urllib2\n>>> fp = urllib2.urlopen('http://bit.ly/rgCbf')\n>>> fp.geturl()\n'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'\n\nFor reference's sake, however, note that this is also possible with httplib:\n>>> ...
[ 32 ]
[]
[]
[ "bit.ly", "python", "tinyurl" ]
stackoverflow_0000748324_bit.ly_python_tinyurl.txt
Q: adding comments to pot files automatically I want to pull certain comments from my py files that give context to translations, rather than manually editing the .pot file basically i want to go from this python file: # For Translators: some useful info about the sentence below _("Some string blah blah") to this po...
adding comments to pot files automatically
I want to pull certain comments from my py files that give context to translations, rather than manually editing the .pot file basically i want to go from this python file: # For Translators: some useful info about the sentence below _("Some string blah blah") to this pot file: # For Translators: some useful info abou...
[ "After much pissing about I found the best way to do this:\n#. Translators:\n# Blah blah blah\n_(\"String\")\n\nThen search for comments with a . like so:\nxgettext --language=Python --keyword=_ --add-comments=. --output=test.pot *.py\n\n", "I was going to suggest the compiler module, but it ignores comments:\nf....
[ 2, 1 ]
[]
[]
[ "internationalization", "localization", "python" ]
stackoverflow_0000744894_internationalization_localization_python.txt
Q: How do I get all the entities of a type with a required property in Google App Engine? I have a model which has a required string property like the following: class Jean(db.Model): sex = db.StringProperty(required=True, choices=set(["male", "female"])) When I try calling Jean.all(), python complains about not...
How do I get all the entities of a type with a required property in Google App Engine?
I have a model which has a required string property like the following: class Jean(db.Model): sex = db.StringProperty(required=True, choices=set(["male", "female"])) When I try calling Jean.all(), python complains about not having a required property. Surely there must be a way to get all of them. If Steve is corr...
[ "Maybe you have old data in the datastore with no sex property (added before you specified the required property), then the system complain that there is an entry without sex property.\nTry adding a default value:\nclass Jean(db.Model):\n sex = db.StringProperty(required=True, choices=set([\"male\", \"female\"])...
[ 1 ]
[]
[]
[ "data_modeling", "entity", "google_app_engine", "python" ]
stackoverflow_0000748952_data_modeling_entity_google_app_engine_python.txt
Q: Django: How to use stored model instances as form choices? I have a model which is essentially just a string (django.db.models.CharField). There will only be several instances of this model stored. How could I use those values as choices in a form? To illustrate, the model could be BlogTopic. I'd like to offer use...
Django: How to use stored model instances as form choices?
I have a model which is essentially just a string (django.db.models.CharField). There will only be several instances of this model stored. How could I use those values as choices in a form? To illustrate, the model could be BlogTopic. I'd like to offer users the ability to choose one or several topics to subscribe to. ...
[ "topics = forms.ModelMultipleChoiceField(queryset=BlogTopic.objects.all())\n\n" ]
[ 26 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000749000_django_django_forms_python.txt
Q: Is Python interpreted (like Javascript or PHP)? Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)? A: As the varied responses will tell you, the line between interpreted and compiled is no longer as clear as it was...
Is Python interpreted (like Javascript or PHP)?
Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?
[ "As the varied responses will tell you, the line between interpreted and compiled is no longer as clear as it was when such terms were coined. In fact, it's also something of a mistake to consider languages as being either interpreted or compiled, as different implementations of languages may do different things. ...
[ 94, 53, 25, 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000745743_python.txt
Q: Search a list of strings for any sub-string from another list Given these 3 lists of data and a list of keywords: good_data1 = ['hello, world', 'hey, world'] good_data2 = ['hey, man', 'whats up'] bad_data = ['hi, earth', 'sup, planet'] keywords = ['world', 'he'] I'm trying to write a simple function to check if a...
Search a list of strings for any sub-string from another list
Given these 3 lists of data and a list of keywords: good_data1 = ['hello, world', 'hey, world'] good_data2 = ['hey, man', 'whats up'] bad_data = ['hi, earth', 'sup, planet'] keywords = ['world', 'he'] I'm trying to write a simple function to check if any of the keywords exist as a substring of any word in the data lis...
[ "Are you looking for\nany( k in s for k in keywords )\n\nIt's more compact, but might be less efficient.\n", "In your example, with so few items, it doesn't really matter. But if you have a list of several thousand items, this might help.\nSince you don't care which element in the list contains the keyword, you c...
[ 38, 16, 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000749342_python.txt
Q: Python: How to estimate / calculate memory footprint of data structures? What's a good way to estimate the memory footprint of an object? Conversely, what's a good way to measure the footprint? For example, say I have a dictionary whose values are lists of integer,float tuples: d['key'] = [ (1131, 3.11e18), (9813,...
Python: How to estimate / calculate memory footprint of data structures?
What's a good way to estimate the memory footprint of an object? Conversely, what's a good way to measure the footprint? For example, say I have a dictionary whose values are lists of integer,float tuples: d['key'] = [ (1131, 3.11e18), (9813, 2.48e19), (4991, 9.11e18) ] I have 4G of physical memory and would like to f...
[ "Guppy has a nice memory profiler (Heapy):\n>>> from guppy import hpy\n>>> hp = hpy()\n>>> hp.setrelheap() # ignore all existing objects\n>>> d = {}\n>>> d['key'] = [ (1131, 3.11e18), (9813, 2.48e19), (4991, 9.11e18) ]\n>>> hp.heap()\n Partition of a set of 24 objects. Total size = 1464 bytes.\n Index Count % ...
[ 10, 5 ]
[]
[]
[ "memory_management", "memory_size", "python" ]
stackoverflow_0000749625_memory_management_memory_size_python.txt
Q: Can pysvn 1.6.3 be made to work with Subversion 1.6 under linux? I see no reference on their website for this. I get pysvn to configure and build, but then it fails all the test. Has anyone had any luck getting this to work under linux? A: No, it cannot. Your best bet is to use Subversion 1.5.5. See the site fo...
Can pysvn 1.6.3 be made to work with Subversion 1.6 under linux?
I see no reference on their website for this. I get pysvn to configure and build, but then it fails all the test. Has anyone had any luck getting this to work under linux?
[ "No, it cannot. \nYour best bet is to use Subversion 1.5.5. See the site for more details. \n" ]
[ 1 ]
[]
[]
[ "linux", "pysvn", "python", "svn" ]
stackoverflow_0000683278_linux_pysvn_python_svn.txt
Q: How to visualize IP addresses as they change in python? I've written a little script that collects my external IP address every time I open a new terminal window and appends it, at well as the current time, to a text file. I'm looking for ideas on a way to visualize when/how often my IP address changes. I bounce b...
How to visualize IP addresses as they change in python?
I've written a little script that collects my external IP address every time I open a new terminal window and appends it, at well as the current time, to a text file. I'm looking for ideas on a way to visualize when/how often my IP address changes. I bounce between home and campus and could separate them using the scri...
[ "Plot your IP as a point on the xkcd internet map (or some zoomed in subset of the map, to better show different but closely neighboring IPs). \nPlot each point \"stacked\" proportional to how often you've had that IP, and color the IPs to make more recent points brighter, less recent points proportionally darker. ...
[ 4, 1, 0, 0 ]
[]
[]
[ "ip_address", "matplotlib", "python", "visualization" ]
stackoverflow_0000749937_ip_address_matplotlib_python_visualization.txt
Q: find missing numeric from ALPHANUMERIC - Python How would I write a function in Python to determine if a list of filenames matches a given pattern and which files are missing from that pattern? For example: Input -> KUMAR.3.txt KUMAR.4.txt KUMAR.6.txt KUMAR.7.txt KUMAR.9.txt KUMAR.10.txt KUMAR.11.txt KUMAR.13.txt ...
find missing numeric from ALPHANUMERIC - Python
How would I write a function in Python to determine if a list of filenames matches a given pattern and which files are missing from that pattern? For example: Input -> KUMAR.3.txt KUMAR.4.txt KUMAR.6.txt KUMAR.7.txt KUMAR.9.txt KUMAR.10.txt KUMAR.11.txt KUMAR.13.txt KUMAR.15.txt KUMAR.16.txt Desired Output--> KUMAR.5....
[ "You can approach this as:\n\nConvert the filenames to appropriate integers.\nFind the missing numbers.\nCombine the missing numbers with the filename template as output.\n\nFor (1), if the file structure is predictable, then this is easy.\ndef to_num(s, start=6):\n return int(s[start:s.index('.txt')])\n\nGiven:...
[ 2, 1 ]
[]
[]
[ "alphanumeric", "filenames", "list", "python" ]
stackoverflow_0000750093_alphanumeric_filenames_list_python.txt
Q: Retrieving/Printing execution context EDIT: This question has been solved with help from apphacker and ConcernedOfTunbridgeWells. I have updated the code to reflect the solution I will be using. I am currently writing a swarm intelligence simulator and looking to give the user an easy way to debug their algorithms...
Retrieving/Printing execution context
EDIT: This question has been solved with help from apphacker and ConcernedOfTunbridgeWells. I have updated the code to reflect the solution I will be using. I am currently writing a swarm intelligence simulator and looking to give the user an easy way to debug their algorithms. Among other outputs, I feel it would be b...
[ "try:\nclass TheClass(object):\n def __init__(self,val):\n self.val=val\n def thefunction(self,a,b):\n c=a+b\n print locals()\n\n\nC=TheClass(2)\nC.thefunction(1,2)\n\n", "You can use __locals__ to get the local execution context. See this stackoverflow posting for some discussion that...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000750702_python.txt
Q: Binary array in python How to create big array in python, how efficient creating that in C/C++: byte *data = (byte*)memalloc(10000); or byte *data = new byte[10000]; in python...? A: Have a look at the array module: import array array.array('B', [0] * 10000) Instead of passing a list to initialize it, you can...
Binary array in python
How to create big array in python, how efficient creating that in C/C++: byte *data = (byte*)memalloc(10000); or byte *data = new byte[10000]; in python...?
[ "Have a look at the array module:\nimport array\narray.array('B', [0] * 10000)\n\nInstead of passing a list to initialize it, you can pass a generator, which is more memory efficient.\n", "You can pre-allocate a list with:\nl = [0] * 10000\n\nwhich will be slightly faster than .appending to it (as it avoids inter...
[ 8, 6, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000751055_python.txt
Q: Parse shell file output with Python I have a file with data. The file is the output generated from a shell scripting file: |a |869 | |b |835 | |c |0 | |d |0 | |e |34 | |f...
Parse shell file output with Python
I have a file with data. The file is the output generated from a shell scripting file: |a |869 | |b |835 | |c |0 | |d |0 | |e |34 | |f |3337 How can ...
[ "You could do this:\noutput = {}\nfor line in open(\"myfile\"):\n parts = line.split('|')\n output[parts[1].strip()] = parts[2].strip()\n\nprint output['a'] // prints 869\nprint output['f'] // prints 3337\n\nOr, using the csv module, as suggested by Eugene Morozov:\nimport csv\noutput = {}\nreader = csv.reade...
[ 9, 4, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000751557_python.txt
Q: How to embed a tag within a url templatetag in a django template? How do I embed a tag within a url templatetag in a django template? Django 1.0 , Python 2.5.2 In views.py def home_page_view(request): NUP={"HOMEPAGE": "named-url-pattern-string-for-my-home-page-view"} variables = RequestContext(request,...
How to embed a tag within a url templatetag in a django template?
How do I embed a tag within a url templatetag in a django template? Django 1.0 , Python 2.5.2 In views.py def home_page_view(request): NUP={"HOMEPAGE": "named-url-pattern-string-for-my-home-page-view"} variables = RequestContext(request, {'NUP':NUP}) return render_to_response('home_page.html', variables...
[ "Maybe you could try passing the final URL to the template, instead?\nSomething like this:\nfrom django.core.urlresolvers import reverse\n\ndef home_page_view(request):\n NUP={\"HOMEPAGE\": reverse('named-url-pattern-string-for-my-home-page-view')} \n variables = RequestContext(request, {'NUP':NUP})\n r...
[ 2, 0, 0 ]
[]
[]
[ "django", "python", "templates", "templatetag", "url" ]
stackoverflow_0000254895_django_python_templates_templatetag_url.txt
Q: Can I compile numpy & scipy as eggs for free on Windows32? I've been asked to provide Numpy & Scipy as python egg files. Unfortunately Numpy and Scipy do not make official releases of their product in .egg form for a Win32 platform - that means if I want eggs then I have to compile them myself. At the moment my em...
Can I compile numpy & scipy as eggs for free on Windows32?
I've been asked to provide Numpy & Scipy as python egg files. Unfortunately Numpy and Scipy do not make official releases of their product in .egg form for a Win32 platform - that means if I want eggs then I have to compile them myself. At the moment my employer provides Visual Studio.Net 2003, which will compile no ve...
[ "Try compiling the whole Python stack with MinGW32. This is a GCC-Win32 development environment that can be used to build Python and a wide variety of software. You will probably have to compile the whole Python distribution with it. Here is a guide to compiling Python with MinGW. Note that you will probably ha...
[ 2, 1, 0 ]
[]
[]
[ "numpy", "python", "scipy", "windows" ]
stackoverflow_0000752482_numpy_python_scipy_windows.txt
Q: How can I use Perl libraries from Python? I have written a bunch of Perl libraries (actually Perl classes) and I want to use some of them in my Python application. Is there a natural way to do this without using SWIG or writing Perl API for Python. I am asking for a similar way of PHP's Perl interface. If there is...
How can I use Perl libraries from Python?
I have written a bunch of Perl libraries (actually Perl classes) and I want to use some of them in my Python application. Is there a natural way to do this without using SWIG or writing Perl API for Python. I am asking for a similar way of PHP's Perl interface. If there is no such kind of work for Perl in Python. What ...
[ "Personally, I would expose the Perl libs as services via XML/RPC or some other such mechanism. That way you can call them from your Python application in a very natural manner.\n", "I haven't tried it, but Inline::Python lets you call Python from Perl. \nYou should be able to use a thin bit of perl to load your...
[ 8, 4, 3, 2, 1 ]
[]
[]
[ "api", "perl", "python" ]
stackoverflow_0000750872_api_perl_python.txt
Q: dispatcher python hy all, I have the following "wrong" dispatcher: def _load_methods(self): import os, sys, glob sys.path.insert(0, 'modules\commands') for c in glob.glob('modules\commands\Command*.py'): if os.path.isdir(c): continue c = os.path.splitext(c)[0] parts ...
dispatcher python
hy all, I have the following "wrong" dispatcher: def _load_methods(self): import os, sys, glob sys.path.insert(0, 'modules\commands') for c in glob.glob('modules\commands\Command*.py'): if os.path.isdir(c): continue c = os.path.splitext(c)[0] parts = c.split(os.path.sep )...
[ "\nsys.path.insert(0, 'modules\\commands')\n\nIt's best not to put a relative path into sys.path. If the current directory changes during execution it'll break.\nAlso if you are running from a different directory to the script it won't work. If you want to make it relative to the script's location, use file.\nAlso ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000751455_python.txt
Q: "Slicing" in Python Expressions documentation I don't understand the following part of the Python docs: http://docs.python.org/reference/expressions.html#slicings Is this referring to list slicing ( x=[1,2,3,4]; x[0:2] )..? Particularly the parts referring to ellipsis.. slice_item ::= expression | proper_sl...
"Slicing" in Python Expressions documentation
I don't understand the following part of the Python docs: http://docs.python.org/reference/expressions.html#slicings Is this referring to list slicing ( x=[1,2,3,4]; x[0:2] )..? Particularly the parts referring to ellipsis.. slice_item ::= expression | proper_slice | ellipsis The conversion of a slice item tha...
[ "Ellipsis is used mainly by the numeric python extension, which adds a multidimensional array type. Since there are more than one dimensions, slicing becomes more complex than just a start and stop index; it is useful to be able to slice in multiple dimensions as well. eg, given a 4x4 array, the top left area woul...
[ 32, 26, 9 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0000752602_python_syntax.txt
Q: How do you automate the launching/debugging of large scale projects? Scenario: There is a complex piece of software that is annoying to launch by hand. What I've done is to create a python script to launch the executable and attach gdb for debugging. The process launching script: ensures an environment variable i...
How do you automate the launching/debugging of large scale projects?
Scenario: There is a complex piece of software that is annoying to launch by hand. What I've done is to create a python script to launch the executable and attach gdb for debugging. The process launching script: ensures an environment variable is set. ensures a local build directory gets added to the environment's LD_...
[ "Instead of forwarding the signal to the debuggee from Python, you could try just ignoring it. The following worked for me:\nimport signal\nsignal.signal(signal.SIGINT, signal.SIG_IGN)\n\nimport subprocess\ncat = subprocess.Popen(['cat'])\nsubprocess.call(['gdb', '--pid=%d' % cat.pid])\n\nWith this I was able to ^...
[ 3, 0, 0 ]
[]
[]
[ "debugging", "gdb", "python", "selinux", "subprocess" ]
stackoverflow_0000739090_debugging_gdb_python_selinux_subprocess.txt
Q: Accessing the class that owns a decorated method from the decorator I'm writing a decorator for methods that must inspect the parent methods (the methods of the same name in the parents of the class in which I'm decorating). Example (from the fourth example of PEP 318): def returns(rtype): def check_returns(f)...
Accessing the class that owns a decorated method from the decorator
I'm writing a decorator for methods that must inspect the parent methods (the methods of the same name in the parents of the class in which I'm decorating). Example (from the fourth example of PEP 318): def returns(rtype): def check_returns(f): def new_f(*args, **kwds): result = f(*args, **kwds)...
[ "\nhere I want to reach the class owning the decorated method f\n\nYou can't because at the point of decoration, no class owns the method f.\nclass A(object):\n @returns(int)\n def compute(self, value):\n return value * 3\n\nIs the same as saying:\nclass A(object):\n pass\n\n@returns(int)\ndef compu...
[ 6, 6 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0000753537_decorator_python.txt
Q: Need to build (or otherwise obtain) python-devel 2.3 and add to LD_LIBRARY_PATH I am supporting an application with a hard dependency on python-devel 2.3.7. The application runs the python interpreter embedded, attempting to load libpython2.3.so - but since the local machine has libpython2.4.so under /usr/lib64, t...
Need to build (or otherwise obtain) python-devel 2.3 and add to LD_LIBRARY_PATH
I am supporting an application with a hard dependency on python-devel 2.3.7. The application runs the python interpreter embedded, attempting to load libpython2.3.so - but since the local machine has libpython2.4.so under /usr/lib64, the application is failing. I see that there are RPMs for python-devel (but not versio...
[ "You can use the python RPM's linked to from the python home page ChristopheD mentioned.\nYou can extract the RPM's using cpio, as they are just specialized cpio archives.\nYour method of extracting them to your home directory and setting LD_LIBRARY_PATH and PATH should work; I use this all the time for hand-built ...
[ 2, 0 ]
[]
[]
[ "build", "linux", "python" ]
stackoverflow_0000753749_build_linux_python.txt
Q: How to generate examples of a gettext plural forms expression? In Python? Given a gettext Plural-Forms line, general a few example values for each n. I'd like this feature for the web interface for my site's translators, so that they know which plural form to put where. For example, given: "Plural-Forms: nplurals=...
How to generate examples of a gettext plural forms expression? In Python?
Given a gettext Plural-Forms line, general a few example values for each n. I'd like this feature for the web interface for my site's translators, so that they know which plural form to put where. For example, given: "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%" "10<=4 && (n%100<10 || n%10...
[ "Given that it's late, I'll bite.\nThe following solution is hacky, and relies on converting your plural form to python code that can be evaluated (basically converting the x ? y : z statements to the python x and y or z equivalent, and changing &&/|| to and/or)\nI'm not sure if your plural form rule is a contrived...
[ 1 ]
[]
[]
[ "gettext", "internationalization", "python" ]
stackoverflow_0000749170_gettext_internationalization_python.txt
Q: How to know when to manage resources in Python I hope I framed the question right. I am trying to force myself to be a better programmer. By better I mean efficient. I want to write a program to identify the files in a directory and read each file for further processing. After some shuffling I got to this: for...
How to know when to manage resources in Python
I hope I framed the question right. I am trying to force myself to be a better programmer. By better I mean efficient. I want to write a program to identify the files in a directory and read each file for further processing. After some shuffling I got to this: for file in os.listdir(dir): y=open(dir+'\\'+file,'...
[ "Python will close open files when they get garbage-collected, so generally you can forget about it -- particularly when reading.\nThat said, if you want to close explicitely, you could do this:\nfor file in os.listdir(dir):\n f = open(dir+'\\\\'+file,'r')\n y = f.readlines()\n for line in y:\n pass...
[ 11, 3 ]
[]
[]
[ "garbage_collection", "python" ]
stackoverflow_0000754187_garbage_collection_python.txt
Q: How is this "referenced before assignment"? I have a bit of Python to connect to a database with a switch throw in for local versus live. LOCAL_CONNECTION = {"server": "127.0.0.1", "user": "root", "password": "", "database": "testing"} LIVE_CONNECTION = {"server": "10.1.1.1", "user": "x", "password": "y",...
How is this "referenced before assignment"?
I have a bit of Python to connect to a database with a switch throw in for local versus live. LOCAL_CONNECTION = {"server": "127.0.0.1", "user": "root", "password": "", "database": "testing"} LIVE_CONNECTION = {"server": "10.1.1.1", "user": "x", "password": "y", "database": "nottesting"} if debug_mode: ...
[ "The second assignement is misspelled.\nYou wrote connnection_info = LIVE_CONNECTION with 3 n's.\n", "Typo: connnection_info = LIVE_CONNECTION\n" ]
[ 16, 4 ]
[]
[]
[ "python" ]
stackoverflow_0000754421_python.txt
Q: Python: Read a file (from an external server) Can you tell me how to code a Python script which reads a file from an external server? I look for something similar to PHP's file_get_contents() or file() function. It would be great if someone could post the entire code for such a script. Thanks in advance! A: The ...
Python: Read a file (from an external server)
Can you tell me how to code a Python script which reads a file from an external server? I look for something similar to PHP's file_get_contents() or file() function. It would be great if someone could post the entire code for such a script. Thanks in advance!
[ "The entire script is:\nimport urllib\ncontent = urllib.urlopen('http://www.google.com/').read()\n\n", "better would be the same as Jarret's code, but using urllib2:\nimport urllib2\ncontent = urllib2.urlopen('http://google.com').read()\n\nurllib2 is a bit newer and more modern. Doesn't matter too much in your ca...
[ 12, 5 ]
[]
[]
[ "file", "python" ]
stackoverflow_0000754170_file_python.txt
Q: Some Basic Python Questions I'm a total python noob so please bear with me. I want to have python scan a page of html and replace instances of Microsoft Word entities with something UTF-8 compatible. My question is, how do you do that in Python (I've Googled this but haven't found a clear answer so far)? I want t...
Some Basic Python Questions
I'm a total python noob so please bear with me. I want to have python scan a page of html and replace instances of Microsoft Word entities with something UTF-8 compatible. My question is, how do you do that in Python (I've Googled this but haven't found a clear answer so far)? I want to dip my toe in the Python waters...
[ "First of all, those aren't Microsoft Word entities—they are UTF-8. You're converting them to HTML entities.\nThe Pythonic way to write something like:\nchr(0xe2) . chr(0x80) . chr(0x98)\n\nwould be:\n'\\xe2\\x80\\x98'\n\nBut Python already has built-in functionality for the type of conversion you want to do:\ndef...
[ 20, 3, 2, 1 ]
[]
[]
[ "html_entities", "php", "python", "replace", "unicode" ]
stackoverflow_0000754468_html_entities_php_python_replace_unicode.txt
Q: can a method call be chained to the 'set()' built-in? (and why not?) If I try: mi_list = ['three', 'small', 'words'] mi_set = set(mi_list) mi_set.remove('small') print mi_set I get: set(['three', 'words']) which is what I expect. Whereas If I try: mi_list = ['three', 'small', 'words'] mi_set = set(mi_lis...
can a method call be chained to the 'set()' built-in? (and why not?)
If I try: mi_list = ['three', 'small', 'words'] mi_set = set(mi_list) mi_set.remove('small') print mi_set I get: set(['three', 'words']) which is what I expect. Whereas If I try: mi_list = ['three', 'small', 'words'] mi_set = set(mi_list).remove('small') print mi_set I get: None Why? I suspect there's a cl...
[ "set.remove returns nothing (None).\nYour code assigns the return value of set.remove to the variable mi_set. Therefore, mi_set is None.\n", "There is a general convention in python that methods which cause side-effects return None. Examples include list.sort, list.append, set.add, set.remove, dict.update, etc.\...
[ 19, 8, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000751457_python.txt
Q: How do you Debug/Take Apart/Learn from someone else's Python code (web-based)? A good example of this is: http://github.com/tav/tweetapp/blob/a711404f2935c3689457c61e073105c1756b62af/app/root.py In Visual Studio (ASP.net C#) where I come from, the classes are usually split into separate files + I can set break poi...
How do you Debug/Take Apart/Learn from someone else's Python code (web-based)?
A good example of this is: http://github.com/tav/tweetapp/blob/a711404f2935c3689457c61e073105c1756b62af/app/root.py In Visual Studio (ASP.net C#) where I come from, the classes are usually split into separate files + I can set break points to understand the code level. If I run a program like this, do I just do "system...
[ "You've run into a pretty specific case of code that will be hard to understand. They probably did that for the convenience of having all the code in one file.\nI would recommend letting epydoc have a pass at it. It will create HTML documentation of the program. This will show you the class structure and you can ev...
[ 3, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000754481_google_app_engine_python.txt
Q: Is there a more pythonic way to build this dictionary? What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: values is a list that is not rela...
Is there a more pythonic way to build this dictionary?
What is the "most pythonic" way to build a dictionary where I have the values in a sequence and each key will be a function of its value? I'm currently using the following, but I feel like I'm just missing a cleaner way. NOTE: values is a list that is not related to any dictionary. for value in values: new_dict[key...
[ "At least it's shorter:\ndict((key_from_value(value), value) for value in values)\n\n", ">>> l = [ 1, 2, 3, 4 ]\n>>> dict( ( v, v**2 ) for v in l )\n{1: 1, 2: 4, 3: 9, 4: 16}\n\nIn Python 3.0 you can use a \"dict comprehension\" which is basically a shorthand for the above:\n{ v : v**2 for v in l }\n\n", "Py3K:...
[ 18, 15, 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000753986_python.txt
Q: finditer hangs when matching against long string I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the fir...
finditer hangs when matching against long string
I have a somewhat complex regular expression which I'm trying to match against a long string (65,535 characters). I'm looking for multiple occurrences of the re in the string, and so am using finditer. It works, but for some reason it hangs after identifying the first few occurrences. Does anyone know why this might be...
[ "Could it be that your expression triggers exponential behavior in the Python RE engine?\nThis article deals with the problem. If you have the time, you might want to try running your expression in an RE engine developed using those ideas.\n", "Definitely exponential behaviour. You've got so many d* parts to you...
[ 5, 5, 3, 2, 2, 1 ]
[]
[]
[ "performance", "python", "regex" ]
stackoverflow_0000755332_performance_python_regex.txt
Q: Python/wxPython: Doing work continuously in the background I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes. When the user starts a simulat...
Python/wxPython: Doing work continuously in the background
I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes. When the user starts a simulation, and defines an initial state, I want the program to render ...
[ "I would use a threading.Thread to run the code in the background and wx.CallAfter to post updates to my window thread to render them to the user.\nthread = threading.Thread(target=self.do_work)\nthread.setDaemon(True)\nthread.start()\n\n...\n\ndef do_work(self):\n # processing code here\n while processing:\n...
[ 10, 7, 4, 0 ]
[]
[]
[ "background", "multithreading", "python", "wxpython" ]
stackoverflow_0000730645_background_multithreading_python_wxpython.txt
Q: Can you write a permutation function just as elegantly in C#? I like this 6 line solution a lot and am trying to replicate it in C#. Basically, it permutes the elements of an array: def permute(xs, pre=[]): if len(xs) == 0: yield pre for i, x in enumerate(xs): for y in permute(xs[:i] + xs[i+1:], pre ...
Can you write a permutation function just as elegantly in C#?
I like this 6 line solution a lot and am trying to replicate it in C#. Basically, it permutes the elements of an array: def permute(xs, pre=[]): if len(xs) == 0: yield pre for i, x in enumerate(xs): for y in permute(xs[:i] + xs[i+1:], pre + [x]): yield y
[ "Well, it probably isn't how I'd write it, but:\nstatic IEnumerable<T[]> Permute<T>(this T[] xs, params T[] pre) {\n if (xs.Length == 0) yield return pre;\n for (int i = 0; i < xs.Length; i++) {\n foreach (T[] y in Permute(xs.Take(i).Union(xs.Skip(i+1)).ToArray(), pre.Union(new[] { xs[i] }).ToArray()))...
[ 12, 1, 0 ]
[ "Not entirely to the point I must admit after some comments, but the code below can be used to generate a random permutation of a finite sequence. It's a variation of the Fisher-Yates shuffle algorithm. The example uses a sequence of int's but you can use any Enumerable<T> of course.\nvar ints = Enumerable.Range(0,...
[ -6 ]
[ "algorithm", "c#", "python" ]
stackoverflow_0000756223_algorithm_c#_python.txt
Q: How to select at the same time from two Listbox? from Tkinter import * master = Tk() listbox = Listbox(master) listbox.pack() listbox.insert(END, "a list entry") for item in ["one", "two", "three", "four"]: listbox.insert(END, item) listbox2 = Listbox(master) listbox2.pack() listbox2.insert(END, "a list en...
How to select at the same time from two Listbox?
from Tkinter import * master = Tk() listbox = Listbox(master) listbox.pack() listbox.insert(END, "a list entry") for item in ["one", "two", "three", "four"]: listbox.insert(END, item) listbox2 = Listbox(master) listbox2.pack() listbox2.insert(END, "a list entry") for item in ["one", "two", "three", "four"]: ...
[ "Short answer: set the value of the exportselection attribute of all listbox widgets to False or zero.\nFrom a pythonware overview of the listbox widget:\n\nBy default, the selection is exported\n to the X selection mechanism. If you\n have more than one listbox on the\n screen, this really messes things up\n f...
[ 46, 8 ]
[]
[]
[ "listbox", "python", "tkinter" ]
stackoverflow_0000756662_listbox_python_tkinter.txt
Q: Matching a pair of comments in HTML using regular expressions I have a mako template that looks something like this: % if staff: <!-- begin staff --> ... <!-- end staff --> % endif That way if I pass the staff variable as being True, those comments should appear. I'm trying to test this by using a re...
Matching a pair of comments in HTML using regular expressions
I have a mako template that looks something like this: % if staff: <!-- begin staff --> ... <!-- end staff --> % endif That way if I pass the staff variable as being True, those comments should appear. I'm trying to test this by using a regular expression that looks like this: re.search('<!-- begin staff ...
[ "By default . doesn't match newlines - you need to add the re.DOTALL option.\nre.search('<!-- begin staff -->.*<!-- end staff -->', text, re.DOTALL)\n\nIf you have more than one staff section, you might also want to make the match ungreedy:\nre.search('<!-- begin staff -->.*?<!-- end staff -->', text, re.DOTALL)\n\...
[ 9, 2 ]
[]
[]
[ "mako", "python", "regex", "unit_testing" ]
stackoverflow_0000756898_mako_python_regex_unit_testing.txt
Q: Difference in regex behavior between Perl and Python? I have a couple email addresses, 'support@company.com' and '1234567@tickets.company.com'. In perl, I could take the To: line of a raw email and find either of the above addresses with /\w+@(tickets\.)?company\.com/i In python, I simply wrote the above regex as...
Difference in regex behavior between Perl and Python?
I have a couple email addresses, 'support@company.com' and '1234567@tickets.company.com'. In perl, I could take the To: line of a raw email and find either of the above addresses with /\w+@(tickets\.)?company\.com/i In python, I simply wrote the above regex as'\w+@(tickets\.)?company\.com' expecting the same result. H...
[ "The documentation for re.findall:\n\nfindall(pattern, string, flags=0)\n Return a list of all non-overlapping matches in the string.\n\n If one or more groups are present in the pattern, return a\n list of groups; this will be a list of tuples if the pattern\n has more than one group.\n\n Empty matc...
[ 7, 4, 2, 1 ]
[]
[]
[ "perl", "python", "regex" ]
stackoverflow_0000757476_perl_python_regex.txt
Q: How do I send large amounts of data from a forked process? I have a ctypes wrapper for a library. Unfortunately, this library is not 100% reliable (occasional segfaults, etc.). Because of how it's used, I want the wrapper to be reasonably resilient to the library crashing. The best way to do this seems to be forki...
How do I send large amounts of data from a forked process?
I have a ctypes wrapper for a library. Unfortunately, this library is not 100% reliable (occasional segfaults, etc.). Because of how it's used, I want the wrapper to be reasonably resilient to the library crashing. The best way to do this seems to be forking a process and sending the results back from the child. I'd li...
[ "Probably you are trying to write more data than can fit into the pipe, so it is blocking until someone comes along and reads some of that info out of there. That will never happen, because the only reader is the parent process, which you appear to have written to wait until the child terminates before it reads any...
[ 4, 2, 0 ]
[]
[]
[ "fork", "pipe", "python" ]
stackoverflow_0000757020_fork_pipe_python.txt
Q: "ImportError: No module named dummy" on fresh Django project I've got the following installed through MacPorts on MacOS X 10.5.6: py25-sqlite3 @2.5.4_0 (active) python25 @2.5.4_1+darwin_9+macosx (active) sqlite3 @3.6.12_0 (active) python25 is correctly set as my system's default Python. I downloaded a fresh copy ...
"ImportError: No module named dummy" on fresh Django project
I've got the following installed through MacPorts on MacOS X 10.5.6: py25-sqlite3 @2.5.4_0 (active) python25 @2.5.4_1+darwin_9+macosx (active) sqlite3 @3.6.12_0 (active) python25 is correctly set as my system's default Python. I downloaded a fresh copy of Django 1.1 beta (I have the same problem with 1.0 and trunk, th...
[ "I found this thread on the Django Users group:\nThey suggest that it has something to do with the way MacPorts installs Python. I wish I had more details to help you with, but as a workaround, I recommend you use MacPorts to uninstall this copy of Python and try to use alternate method of install it. If you're loo...
[ 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "database", "django", "python", "sqlite" ]
stackoverflow_0000739191_database_django_python_sqlite.txt
Q: Why doesn't the regex match when I add groups? I have this regex code in python : if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text): print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups()) text is {\fad(200,200)}Épisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03 and read from a file (don't know...
Why doesn't the regex match when I add groups?
I have this regex code in python : if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text): print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups()) text is {\fad(200,200)}Épisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03 and read from a file (don't know if that helps). This returns the following: (None, ...
[ "Put extra parens around the choice: re.search(r\"{(?:\\\\fad|fade)\\((\\d{1,4}),(\\d{1,4})\\)}\", text).groups()\nAlso, escaping {} braces isn't necessary, it just needlessly clutters your regexp.\n", "The bracket is part of the or branch starting with fade, so it's looking for either \"{fad\" or \"fade(...\". ...
[ 6, 4, 2, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000757949_python_regex.txt
Q: Whats the easiest and fastest way to measure HD performance using Python? I need to measure the performance of a hard disk using python. What is the best/fastest/shortest/easiest approach to do it? It doesn't have to be overly accurate, just a ballpark value. My actual goal is to write a small utility which will a...
Whats the easiest and fastest way to measure HD performance using Python?
I need to measure the performance of a hard disk using python. What is the best/fastest/shortest/easiest approach to do it? It doesn't have to be overly accurate, just a ballpark value. My actual goal is to write a small utility which will adjust the postgres settings to the best configuration for the given hardware. M...
[ "I would think your best bet would be using an external tool, Bonnie++ for example, and parse the program output. Even if you're not that concerned with precision there's no reason to reinvent the wheel. Why rewrite what's already there?\n", "Start here: http://www.acnc.com/benchmarks.html\nGet the source for one...
[ 2, 1 ]
[]
[]
[ "performance", "postgresql", "python" ]
stackoverflow_0000757816_performance_postgresql_python.txt
Q: Problem with Python modules I'm uploading my first Django app to my Dreamhost server. My app uses xlwt package and since I can't install it in the default location ( /usr/lib/python2.3/site-packages/xlwt ), I installed it on another location by: python setup.py install --home=$HOME Then xlwt is installed here: /h...
Problem with Python modules
I'm uploading my first Django app to my Dreamhost server. My app uses xlwt package and since I can't install it in the default location ( /usr/lib/python2.3/site-packages/xlwt ), I installed it on another location by: python setup.py install --home=$HOME Then xlwt is installed here: /home/myuser/lib/python/xlwt/ Afte...
[ "PYTHONPATH may only be set when you run from the shell, you can set path programatically from python using\nimport sys\nsys.path.append('/home/myuser/lib/python')\n\n" ]
[ 5 ]
[]
[]
[ "django", "dreamhost", "python" ]
stackoverflow_0000758187_django_dreamhost_python.txt
Q: How do you order lists in the same way QuerySets are ordered in Django? I have a model that has an ordering field under its Meta class. When I perform a query and get back a QuerySet for the model it is in the order specified. However if I have instances of this model that are in a list and execute the sort met...
How do you order lists in the same way QuerySets are ordered in Django?
I have a model that has an ordering field under its Meta class. When I perform a query and get back a QuerySet for the model it is in the order specified. However if I have instances of this model that are in a list and execute the sort method on the list the order is different from the one I want. Is there a way t...
[ "Not automatically, but with a bit of work, yes. You need to define a comparator function (or cmp method on the model class) that can compare two model instances according to the relevant attribute. For instance:\nclass Dated(models.Model):\n ...\n created = models.DateTimeField(default=datetime.now)\n\n class...
[ 5, 3, 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000753687_django_django_models_python.txt
Q: how to use pycurl if requested data is sometimes gzipped, sometimes not? I'm doing this to fetch some data: c = pycurl.Curl() c.setopt(pycurl.ENCODING, 'gzip') c.setopt(pycurl.URL, url) c.setopt(pycurl.TIMEOUT, 10) c.setopt(pycurl.FOLLOWLOCATION, True) xml = StringIO() c.setopt(pycurl.WRITEFUNCTION, xml.writ...
how to use pycurl if requested data is sometimes gzipped, sometimes not?
I'm doing this to fetch some data: c = pycurl.Curl() c.setopt(pycurl.ENCODING, 'gzip') c.setopt(pycurl.URL, url) c.setopt(pycurl.TIMEOUT, 10) c.setopt(pycurl.FOLLOWLOCATION, True) xml = StringIO() c.setopt(pycurl.WRITEFUNCTION, xml.write ) c.perform() c.close() My urls are typically of this sort: http://host/pa...
[ "If worst comes to worst, you could omit the ENCODING 'gzip', set HTTPHEADER to {'Accept-Encoding' : 'gzip'}, check the response headers for \"Content-Encoding: gzip\" and if it's present, gunzip the response yourself.\n" ]
[ 5 ]
[]
[]
[ "gzip", "http", "libcurl", "pycurl", "python" ]
stackoverflow_0000758243_gzip_http_libcurl_pycurl_python.txt
Q: Python Sort Collections.DefaultDict in Descending order I have this bit of code: visits = defaultdict(int) for t in tweetsSQL: visits[t.user.from_user] += 1 I looked at some examples online that used the sorted method like so: sorted(visits.iteritems, key=operator.itemgetter(1), reverse=True) but...
Python Sort Collections.DefaultDict in Descending order
I have this bit of code: visits = defaultdict(int) for t in tweetsSQL: visits[t.user.from_user] += 1 I looked at some examples online that used the sorted method like so: sorted(visits.iteritems, key=operator.itemgetter(1), reverse=True) but it is giving me: "TypeError: 'builtin_function_or_method' ob...
[ "iteritems is a method. You need parenthesis to call it: visits.iteritems().\nAs it stands now, you are passing the iteritems method itself to sorted which is why it is complaining that it can't iterate over a function or method. \n", "Personally I think one of these forms is a little more succinct as the first a...
[ 12, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000758792_python.txt
Q: Matplotlib suddenly crashes after reinstalling Xcode? I was happy in my world of python and matplotlib with a good level of familiarity. I notied Xcode on my Mac wasn't working so I installed the latest version from Apple and it somehow broke my install of matplotlib (or numpy?)! I'm now getting ... /sw/lib/pytho...
Matplotlib suddenly crashes after reinstalling Xcode?
I was happy in my world of python and matplotlib with a good level of familiarity. I notied Xcode on my Mac wasn't working so I installed the latest version from Apple and it somehow broke my install of matplotlib (or numpy?)! I'm now getting ... /sw/lib/python2.5/site-packages/matplotlib-0.91.1-py2.5-macosx- 10.5-i38...
[ "You're using Python from Fink, so Xcode doesn't have anything to do with it. from numpy.core.ma import * works fine with Apple's bundled Python and NumPy too.\n" ]
[ 3 ]
[]
[]
[ "matplotlib", "numpy", "python", "xcode" ]
stackoverflow_0000758980_matplotlib_numpy_python_xcode.txt
Q: How can I remove a temporary file (image) that is being displayed by CGI? I've written a python CGI script that converts files into .jpgs and displays them in a simple HTML page. I don't want to clutter up the folders with these .jpg files, so I used tempfile.NamedTemporaryFile to create a file to store the conve...
How can I remove a temporary file (image) that is being displayed by CGI?
I've written a python CGI script that converts files into .jpgs and displays them in a simple HTML page. I don't want to clutter up the folders with these .jpg files, so I used tempfile.NamedTemporaryFile to create a file to store the converted .jpg output. Everything works great, but i want to remove this file after...
[ "You can't remove the file from your cgi script. Because the html page is send to the user only after your script finishes to run. And then the users browser parse the html and fetch the jpg file.\nThe simplest option is to write the temporary files to a sub directory and periodically clean that directory (living i...
[ 3 ]
[]
[]
[ "cgi", "image", "python" ]
stackoverflow_0000759271_cgi_image_python.txt
Q: Unexpected result from sys.getrefcount When I typed: >>> astrd = 123 >>> import sys >>> sys.getrefcount(astrd) 3 >>> I am not getting where is astrd used 3 times ? A: It's not astrd that is referenced three times, but the value 123. astrd is simply a name for the (immutable) number 123, which can be referenced...
Unexpected result from sys.getrefcount
When I typed: >>> astrd = 123 >>> import sys >>> sys.getrefcount(astrd) 3 >>> I am not getting where is astrd used 3 times ?
[ "It's not astrd that is referenced three times, but the value 123. astrd is simply a name for the (immutable) number 123, which can be referenced however many times. Additionally to that, small integers are usually shared:\n>>> astrd = 123\n>>> sys.getrefcount(astrd)\n4\n>>> j = 123\n>>> sys.getrefcount(astrd)\n5\n...
[ 10, 7, 6, 5 ]
[]
[]
[ "garbage_collection", "python" ]
stackoverflow_0000759740_garbage_collection_python.txt
Q: Elixir Event Handler I want to use the @after_insert decorator of Elixir, but i can't access the Session within the model. Since i have autocommit set to False, i can't commit any changes in the event handler. Is there any best practice how to deal with that? The Code I used to build model, database connection etc...
Elixir Event Handler
I want to use the @after_insert decorator of Elixir, but i can't access the Session within the model. Since i have autocommit set to False, i can't commit any changes in the event handler. Is there any best practice how to deal with that? The Code I used to build model, database connection etc. are mostly taken off the...
[ "Have you imported Session?\nfrom packagename import Session\nat the top of your model file should do the trick. Packagename is the directory name.\n" ]
[ 0 ]
[]
[]
[ "pylons", "python", "python_elixir" ]
stackoverflow_0000756529_pylons_python_python_elixir.txt
Q: Shell: insert a blank/new line two lines above pattern To add a blank line above every line that matches your regexp, you can use: sed '/regexp/{x;p;x;}' But I want to add a blank line, not one line above, but two lines above the line which matches my regexp. The pattern I'll be matching is a postal code in the a...
Shell: insert a blank/new line two lines above pattern
To add a blank line above every line that matches your regexp, you can use: sed '/regexp/{x;p;x;}' But I want to add a blank line, not one line above, but two lines above the line which matches my regexp. The pattern I'll be matching is a postal code in the address line. Here is a snippet of the text's formatting: ra...
[ "More readable Perl, and handles multiple files sanely.\n#!/usr/bin/env perl\nuse constant LINES => 2;\nmy @buffer = ();\nwhile (<>) {\n /pattern/ and unshift @buffer, \"\\n\";\n push @buffer, $_;\n print splice @buffer, 0, -LINES;\n}\ncontinue {\n if (eof(ARGV)) {\n print @buffer;\n @buff...
[ 7, 5, 3, 2, 1, 0 ]
[]
[]
[ "awk", "perl", "python", "sed", "text" ]
stackoverflow_0000757532_awk_perl_python_sed_text.txt
Q: Performance Considerations Using Multiple Layers of Generators in Python? Are there any performance considerations for using a lot of generators chained together, as opposed to just a single generator. For example: def A(self, items): for item in self.AB(items): if object.A(): yield item d...
Performance Considerations Using Multiple Layers of Generators in Python?
Are there any performance considerations for using a lot of generators chained together, as opposed to just a single generator. For example: def A(self, items): for item in self.AB(items): if object.A(): yield item def AB(self, items): for object in self.ABC(objects): if object.A() ...
[ "There is nothing wrong with chaining generators, but in this example there is no reason for A to call self.AB, it can just loop over items to get the same result.\nYou should write your code as clearly as you can and if it's slow then use a profiler to determine where the bottleneck is. Contrived examples such as ...
[ 2 ]
[]
[]
[ "generator", "performance", "python" ]
stackoverflow_0000759729_generator_performance_python.txt
Q: add request to django model method? I'm keeping track of a user status on a model. For the model 'Lesson' I have the status 'Finished', 'Learning', 'Viewed'. In a view for a list of models I want to add the user status. What is the best way to do this? One idea: Adding the request to a models method would do the t...
add request to django model method?
I'm keeping track of a user status on a model. For the model 'Lesson' I have the status 'Finished', 'Learning', 'Viewed'. In a view for a list of models I want to add the user status. What is the best way to do this? One idea: Adding the request to a models method would do the trick. Is that possible? Edit: I meant in ...
[ "If your status is a value that changes, you have to break this into two separate parts.\n\nUpdating the status. This must be called in a view function. The real work, however, belongs in the model. The view function calls the model method and does the save.\nDisplaying the status. This is just some string repr...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000759850_django_django_models_python.txt
Q: django-paypal setup Has anyone setup django-paypal? Here is the link to it here? I have "myproject" setup, and my folder sturecture looks like this: myproject > paypal > (stdandard and pro folders) to my settins.py file I added INSTALLED_APPS = ( 'myproject.paypal.standard', 'myproject.paypal.pro', ) in ...
django-paypal setup
Has anyone setup django-paypal? Here is the link to it here? I have "myproject" setup, and my folder sturecture looks like this: myproject > paypal > (stdandard and pro folders) to my settins.py file I added INSTALLED_APPS = ( 'myproject.paypal.standard', 'myproject.paypal.pro', ) in my url's file for my acco...
[ "In your code...\n 'payment_form_cls': 'payment_form_cls', # form class to use for payment\n\nThis must be a Form object that's used for validation.\n 'payment_form_cls': MyValidationForm, # form class to use for payment\n\n\nEdit\nhttp://github.com/johnboxall/django-paypal/tree/master\nYour request is suppose...
[ 5, 0 ]
[]
[]
[ "django", "paypal", "python" ]
stackoverflow_0000757809_django_paypal_python.txt
Q: Map raw SQL to multiple related Django models Due to performance reasons I can't use the ORM query methods of Django and I have to use raw SQL for some complex questions. I want to find a way to map the results of a SQL query to several models. I know I can use the following statement to map the query results to o...
Map raw SQL to multiple related Django models
Due to performance reasons I can't use the ORM query methods of Django and I have to use raw SQL for some complex questions. I want to find a way to map the results of a SQL query to several models. I know I can use the following statement to map the query results to one model, but I can't figure how to use it to be ab...
[ "First, can you prove the ORM is stopping your performance? Sometimes performance problems are simply poor database design, or improper indexes. Usually this comes from trying to force-fit Django's ORM onto a legacy database design. Stored procedures and triggers can have adverse impact on performance -- especia...
[ 1 ]
[]
[]
[ "django", "django_models", "mysql", "python", "sql" ]
stackoverflow_0000759797_django_django_models_mysql_python_sql.txt
Q: python ctypes and sysctl I have following code import sys from ctypes import * from ctypes.util import find_library libc = cdll.LoadLibrary(find_library("c")) CTL_KERN = 1 KERN_SHMMAX = 34 sysctl_names = { 'memory_shared_buffers' : (CTL_KERN, KERN_SHMMAX), } def posix_sysctl_long(name): _mem = c_uint...
python ctypes and sysctl
I have following code import sys from ctypes import * from ctypes.util import find_library libc = cdll.LoadLibrary(find_library("c")) CTL_KERN = 1 KERN_SHMMAX = 34 sysctl_names = { 'memory_shared_buffers' : (CTL_KERN, KERN_SHMMAX), } def posix_sysctl_long(name): _mem = c_uint64(0) _arr = c_int * 2 ...
[ "You are not providing the correct values to the sysctl function. Detailed information on the arguments of sysctl() can be found here.\nHere are your errors:\n\nYou have forgotten the nlen argument (second argument)\nThe oldlenp argument is a pointer to the size, not directly the size\n\nHere is the correct functio...
[ 7 ]
[]
[]
[ "c", "ctypes", "linux", "python" ]
stackoverflow_0000759892_c_ctypes_linux_python.txt
Q: Generator function getting executed twice? I'm using a python generator function to provide me with a list of images in the current directory. However I see the function is giving out the entire list twice instead of one time and I have no idea why. I'm using the Python PIL library to create batch thumbnails. Can ...
Generator function getting executed twice?
I'm using a python generator function to provide me with a list of images in the current directory. However I see the function is giving out the entire list twice instead of one time and I have no idea why. I'm using the Python PIL library to create batch thumbnails. Can anyone point me in the right direction? Script: ...
[ "In your debugging, print the full path. I think you're walking the thumbs subdirectory after you walk the . directory.\nAlso. \nclass ThumbnailGenerator( object ):\n\nUsually works out better in the long run.\nPlease do NOT use __ in front of your method names (generate_image_list and create_thumbnail_dir).\nDo n...
[ 3, 0 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0000760647_generator_python.txt
Q: How to access Yahoo Enterprise Web Services using Python SOAPpy? I have a PHP script which works and i need to write the same in Python but SOAPpy generates a slightly different request and i'm not sure how to fix it so the server likes it. The request generated by php script looks like this: <?xml version="1.0" e...
How to access Yahoo Enterprise Web Services using Python SOAPpy?
I have a PHP script which works and i need to write the same in Python but SOAPpy generates a slightly different request and i'm not sure how to fix it so the server likes it. The request generated by php script looks like this: <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xm...
[ "The problem was not about SOAP headers format but just about the parameter order. Here's the full explanation and code: http://pea.somemilk.org/2009/04/05/yahoo-search-marketing-python-soap-binding/\n", "accountID should be of type xsd:string rather than xsd:integer. (maybe you're passing a string instead of an ...
[ 2, 0 ]
[]
[]
[ "python", "soap", "soappy" ]
stackoverflow_0000657473_python_soap_soappy.txt
Q: How to mark a device in a way that can be retrived by HAL but does not require mounting or changing the label I'm trying to find a way to mark a USB flash device in a way that I can programmaticly test for without mounting it or changing the label. Are there any properties I can modify about a device that will no...
How to mark a device in a way that can be retrived by HAL but does not require mounting or changing the label
I'm trying to find a way to mark a USB flash device in a way that I can programmaticly test for without mounting it or changing the label. Are there any properties I can modify about a device that will not cause it to behave/look differently to the user? Running Ubuntu Jaunty.
[ "You cannot modify this property, but the tuple (vendor_id, product_id, serial_number) is unique to each device, so you can use this as mark that is already there. \nYou can enumerate the devices on the USB bus using lsusb or usblib.\n", "Changing the VID/PID might make your device non-usable without custom drive...
[ 1, 0 ]
[]
[]
[ "dbus", "hal", "hardware", "mount", "python" ]
stackoverflow_0000760310_dbus_hal_hardware_mount_python.txt