content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python: Stopping miniDOM from expanding escape sequences When xml.dom.minidom parses a piece of xml, it automagically converts escape characters for greater than and less than into their visual representation. For example: >>> import xml.dom.minidom >>> s = "<example>4 &lt; 5</example>" >>> x = xml.dom.mini...
Python: Stopping miniDOM from expanding escape sequences
When xml.dom.minidom parses a piece of xml, it automagically converts escape characters for greater than and less than into their visual representation. For example: >>> import xml.dom.minidom >>> s = "<example>4 &lt; 5</example>" >>> x = xml.dom.minidom.parseString(s) >>> x.firstChild.firstChild.data u'4 < 5' ...
[ ">>> import xml.dom.minidom\n>>> s = \"<example>4 &lt; 5</example>\"\n>>> x = xml.dom.minidom.parseString(s)\n>>> x.firstChild.firstChild.toxml()\nu'4 &lt; 5'\n\n" ]
[ 3 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0000893930_minidom_python_xml.txt
Q: How does setuptools decide which files to keep for sdist/bdist? I'm working on a Python package that uses namespace_packages and find_packages() like so in setup.py: from setuptools import setup, find_packages setup(name="package", version="1.3.3.7", package=find_packages(), namespace_packages=['packag...
How does setuptools decide which files to keep for sdist/bdist?
I'm working on a Python package that uses namespace_packages and find_packages() like so in setup.py: from setuptools import setup, find_packages setup(name="package", version="1.3.3.7", package=find_packages(), namespace_packages=['package'], ...) It isn't in source control because it is a bundle of upstr...
[ "You need to add a package_data directive. For example, if you want to include files with .txt or .rst extensions:\nfrom setuptools import setup, find_packages\nsetup(name=\"package\",\n version=\"1.3.3.7\",\n package=find_packages(),\n include_package_data=True,\n namespace_packages=['package'], \n ...
[ 4 ]
[]
[]
[ "distutils", "python", "setuptools" ]
stackoverflow_0000894323_distutils_python_setuptools.txt
Q: Multi-server monitor/auto restarter in python I have 2 server programs that must be started with the use of GNU Screen. I'd like to harden these servers against crashes with a Python based program that kicks off each screen session then monitors the server process. If the server process crashes, I need the python ...
Multi-server monitor/auto restarter in python
I have 2 server programs that must be started with the use of GNU Screen. I'd like to harden these servers against crashes with a Python based program that kicks off each screen session then monitors the server process. If the server process crashes, I need the python code to kill the extraneous screen session and rest...
[ "\"need to be multi-threaded to handle the restarting of two separate programs\" \nDon't see why.\nimport subprocess\n\ncommands = [ [\"p1\"], [\"p2\"] ]\nprograms = [ subprocess.Popen(c) for c in commands ]\nwhile True:\n for i in range(len(programs)):\n if programs[i].returncode is None:\n c...
[ 6, 3 ]
[]
[]
[ "bash", "linux", "python", "restart" ]
stackoverflow_0000894474_bash_linux_python_restart.txt
Q: Has Python changed to more object oriented? I remember that at one point, it was said that Python is less object oriented than Ruby, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version? A: Jian Lin — the answer is "Yes...
Has Python changed to more object oriented?
I remember that at one point, it was said that Python is less object oriented than Ruby, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previous version?
[ "Jian Lin — the answer is \"Yes\", Python is more object-oriented than when Matz decided he wanted to create Ruby, and both languages now feature \"everything is an object\". Back when Python was younger, \"types\" like strings and numbers lacked methods, whereas \"objects\" were built with the \"class\" statement...
[ 40, 12, 7, 2, 2, 1 ]
[]
[]
[ "oop", "python", "ruby" ]
stackoverflow_0000894502_oop_python_ruby.txt
Q: More Pythonic conversion to binary? Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves. def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('<I', [2])) ...
More Pythonic conversion to binary?
Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves. def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('<I', [2])) # Image size. data.append(struct....
[ "You can try to implement some sort of declarative syntax for your data.\nWhich may result in something like:\nclass Image(SomeClassWithMetamagic):\n type = PackedValue(2)\n attribute = PackedValue('attributes') # accessed via self.__dict__\n\n#or using decorators\n @pack(\"<II\")\n def get_size():\n ...
[ 4, 4, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000894157_python.txt
Q: Compiled Python CGI Assuming the webserver is configured to handle .exe, Can i compile a python CGI file into an exe for speed. What would some pros and cons be to such a desession? A: There is py2exe (and a tutorial on how to use it), but there is no guarentee that it will make your script any faster. Really ...
Compiled Python CGI
Assuming the webserver is configured to handle .exe, Can i compile a python CGI file into an exe for speed. What would some pros and cons be to such a desession?
[ "There is py2exe (and a tutorial on how to use it), but there is no guarentee that it will make your script any faster. Really its more of an executable interpreter that wraps the bytecode. There are other exe compilers that do varying degrees of things to the python code, so you might want to do a general Google...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000895163_python.txt
Q: How do I get the current file, current class, and current method with Python? Name of the file from where code is running Name of the class from where code is running Name of the method (attribute of the class) where code is running A: Here is an example of each: from inspect import stack class Foo: def __i...
How do I get the current file, current class, and current method with Python?
Name of the file from where code is running Name of the class from where code is running Name of the method (attribute of the class) where code is running
[ "Here is an example of each:\nfrom inspect import stack\n\nclass Foo:\n def __init__(self):\n print __file__\n print self.__class__.__name__\n print stack()[0][3]\n\nf = Foo()\n\n", "import sys\n\nclass A:\n def __init__(self):\n print __file__\n print self.__class__.__nam...
[ 33, 11, 5, 3 ]
[]
[]
[ "filenames", "python" ]
stackoverflow_0000894088_filenames_python.txt
Q: Miminal Linux For a Pylons Web App? I am going to be building a Pylons-based web application. For this purpose, I'd like to build a minimal Linux platform, upon which I would then install the necessary packages such as Python and Pylons, and other necessary dependencies. The other reason to keep it minimal is beca...
Miminal Linux For a Pylons Web App?
I am going to be building a Pylons-based web application. For this purpose, I'd like to build a minimal Linux platform, upon which I would then install the necessary packages such as Python and Pylons, and other necessary dependencies. The other reason to keep it minimal is because this machine will be virtual, probabl...
[ "I really like JeOS \"Just enough OS\" which is a minimal distribution of the Ubuntu Server Edition.\n", "If you want to be able to remove all the cruft but still be using a ‘mainstream’ distro rather than one cut down to aim at tiny devices, look at Slackware. You can happily remove stuff as low-level as sysvini...
[ 8, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "linux", "pylons", "python" ]
stackoverflow_0000589115_linux_pylons_python.txt
Q: Can anyone recommend a Python PDF generator with OpenType (.OTF) support? After asking this question back in November, I've been very happy with ReportLab for all of my python pdf-generation needs. However, it turns out that while ReportLab will use regular TrueType (TTF) fonts, it does not support OpenType (OTF) ...
Can anyone recommend a Python PDF generator with OpenType (.OTF) support?
After asking this question back in November, I've been very happy with ReportLab for all of my python pdf-generation needs. However, it turns out that while ReportLab will use regular TrueType (TTF) fonts, it does not support OpenType (OTF) fonts. One of the current widgets I'm working on is going to need to use some O...
[ "That sort of depends... OpenType was intended to extend TrueType (and uses the general structure of TrueType internally) - so much so that some folks have reported success using OpenType fonts in reportlab; I suppose it all depends on whether or not there are any special OTF characteristics that your use of the fo...
[ 4, 4 ]
[]
[]
[ "opentype", "pdf_generation", "python" ]
stackoverflow_0000895596_opentype_pdf_generation_python.txt
Q: Using virtualenv on Mac OS X I've been using virtualenv on Ubuntu and it rocks, so I'm trying to use it on my Mac and I'm having trouble. The virtualenv command successfully creates the directory, and easy_install gladly installs packages in it, but I can't import anything I install. It seems like sys.path isn't b...
Using virtualenv on Mac OS X
I've been using virtualenv on Ubuntu and it rocks, so I'm trying to use it on my Mac and I'm having trouble. The virtualenv command successfully creates the directory, and easy_install gladly installs packages in it, but I can't import anything I install. It seems like sys.path isn't being set correctly: it doesn't inc...
[ "I've not had any problems with the same OS X/Python/virtualenv version (OS X 10.5.6, Python 2.5.1, virtualenv 1.3.1)\n$ virtualenv test\nNew python executable in test/bin/python\nInstalling setuptools............done.\n$ source test/bin/activate\n(test)$ which python\n/Users/dbr/test/bin/python\n$ echo $PATH\n/Use...
[ 5, 2 ]
[]
[]
[ "macos", "python", "virtualenv" ]
stackoverflow_0000843531_macos_python_virtualenv.txt
Q: How can I launch a python script on windows? I have run a few using batch jobs, but, I am wondering what would be the most appropriate? Maybe using time.strftime? A: If you're looking to do recurring scheduled tasks, then the Task Scheduler (Vista) or Scheduled Tasks (XP and, I think, earlier) is the appropriate...
How can I launch a python script on windows?
I have run a few using batch jobs, but, I am wondering what would be the most appropriate? Maybe using time.strftime?
[ "If you're looking to do recurring scheduled tasks, then the Task Scheduler (Vista) or Scheduled Tasks (XP and, I think, earlier) is the appropriate method on Windows.\n", "I'd second using the Task Scheduler. \nI have also read about a 'cron-like' python based application PyCron - http://www.bigbluehost.com/arti...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000894845_python.txt
Q: How can I start an interactive program(like gdb) from python? I am going to start up gdb from python. For example: prog.shell.py: #do lots of things # # p.subprocess.Popen("gdb --args myprog", shell=True, stdin=sys.stdin, stdout=sys.stdout) But the gdb is not invoked as I expected, the interaction...
How can I start an interactive program(like gdb) from python?
I am going to start up gdb from python. For example: prog.shell.py: #do lots of things # # p.subprocess.Popen("gdb --args myprog", shell=True, stdin=sys.stdin, stdout=sys.stdout) But the gdb is not invoked as I expected, the interaction with gdb is broken. I have also tried os.system(), but it still do...
[ "I think you meant\np = subprocess.Popen(...)\n\nYou probably need to wait for p to finish:\np.wait()\n\n" ]
[ 3 ]
[]
[]
[ "gdb", "python" ]
stackoverflow_0000896031_gdb_python.txt
Q: Can reading a list from a disk be better than loading a dictionary? I am building an application where I am trying to allow users to submit a list of company and date pairs and find out whether or not there was a news event on that date. The news events are stored in a dictionary with a company identifier and a ...
Can reading a list from a disk be better than loading a dictionary?
I am building an application where I am trying to allow users to submit a list of company and date pairs and find out whether or not there was a news event on that date. The news events are stored in a dictionary with a company identifier and a date as a key. newsDict('identifier','MM/DD/YYYY')=[list of news events...
[ "With such a large amount of data, you should be using a database. This would be far better than looking at a list, and would be the most appropriate way of storing your data anyway. If you're using Python, it has SQLite built in I believe.\n", "The dictionary will take more memory because it is effectively a has...
[ 5, 1 ]
[]
[]
[ "dictionary", "list", "performance", "python" ]
stackoverflow_0000895500_dictionary_list_performance_python.txt
Q: How to convert a Pyglet image to a PIL image? i want to convert a Pyglet.AbstractImage object to an PIL image for further manipulation here are my codes from pyglet import image from PIL import Image pic = image.load('pic.jpg') data = pic.get_data('RGB', pic.pitch) im = Image.fromstring('RGB', (pic.width, pic.heig...
How to convert a Pyglet image to a PIL image?
i want to convert a Pyglet.AbstractImage object to an PIL image for further manipulation here are my codes from pyglet import image from PIL import Image pic = image.load('pic.jpg') data = pic.get_data('RGB', pic.pitch) im = Image.fromstring('RGB', (pic.width, pic.height), data) im.show() but the image shown went wron...
[ "I think I find the solution\nthe pitch in Pyglet.AbstractImage instance is not compatible with PIL\nI found in pyglet 1.1 there is a codec function to encode the Pyglet image to PIL\nhere is the link to the source\nso the code above should be modified to this\nfrom pyglet import image\nfrom PIL import Image\npic =...
[ 2, 0 ]
[]
[]
[ "image", "pyglet", "python", "python_imaging_library" ]
stackoverflow_0000896548_image_pyglet_python_python_imaging_library.txt
Q: Display all file names from a specific folder Like there is a folder say XYZ , whcih contain files with diffrent diffrent format let say .txt file, excel file, .py file etc. i want to display in the output all file name using Python programming A: import glob glob.glob('XYZ/*') See the documentation for more A...
Display all file names from a specific folder
Like there is a folder say XYZ , whcih contain files with diffrent diffrent format let say .txt file, excel file, .py file etc. i want to display in the output all file name using Python programming
[ "import glob\nglob.glob('XYZ/*')\n\nSee the documentation for more\n", "Here is an example that might also help show some of the handy basics of python -- dicts {} , lists [] , little string techniques (split), a module like os, etc.:\nbvm@bvm:~/example$ ls\ndeal.xls five.xls france.py guido.py make.py ...
[ 3, 2, 1 ]
[]
[]
[ "directory", "ls", "python" ]
stackoverflow_0000896595_directory_ls_python.txt
Q: Properly importing modules in Python How do I set up module imports so that each module can access the objects of all the others? I have a medium size Python application with modules files in various subdirectories. I have created modules that append these subdirectories to sys.path and imports a group of modules...
Properly importing modules in Python
How do I set up module imports so that each module can access the objects of all the others? I have a medium size Python application with modules files in various subdirectories. I have created modules that append these subdirectories to sys.path and imports a group of modules, using import thisModule as tm. Module o...
[ "\"I have a medium size Python application with modules files in various subdirectories.\"\nGood. Make absolutely sure that each directory include a __init__.py file, so that it's a package.\n\"I have created modules that append these subdirectories to sys.path\"\nBad. Use PYTHONPATH or install the whole structur...
[ 25, 6, 4, 3 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0000896112_python_python_import.txt
Q: Running multiple processes and capturing the output in python with pygtk I'd like to write a simple application that runs multiple programs and displays their output in multiple terminal (style) windows. In addition, I want to be able to read the stdout/stderr of these processes and search for keywords in the out...
Running multiple processes and capturing the output in python with pygtk
I'd like to write a simple application that runs multiple programs and displays their output in multiple terminal (style) windows. In addition, I want to be able to read the stdout/stderr of these processes and search for keywords in the output. I've tried implementing this two ways in python, the first using subproce...
[ "I did something similar to this using the subprocess.Popen. For each process I actually ended up redirecting the stdout and stderr to a temporary file, then periodically checking the file for updates and dumping the output into a TextView. \nThe reason for not using a pipe to the process was that the processes the...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000896874_python.txt
Q: Python cgi FieldStorage slow, alternatives? I have a python cgi script that receives files uploaded via a http post. The files can be large (300+ Mb). The thing is, cgi.FieldStorage() is incredibly slow for getting the file (a 300Mb file took 6 minutes to be "received"). Doing the same by just reading the stdin to...
Python cgi FieldStorage slow, alternatives?
I have a python cgi script that receives files uploaded via a http post. The files can be large (300+ Mb). The thing is, cgi.FieldStorage() is incredibly slow for getting the file (a 300Mb file took 6 minutes to be "received"). Doing the same by just reading the stdin took around 15 seconds. The problem with the latter...
[ "\"[I] would have to parse the data myself\"\nWhy? CGI has a parser you can call explicitly.\nRead the uploaded stream and save it in a local disk file. \nFor blazing speed, use a StringIO in-memory file. Just be aware of the amount of memory the upload will take.\nUse cgi.parse(mylocalfile).\n" ]
[ 2 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0000897206_cgi_python.txt
Q: CreateDatabase often fails on the google data api The following test program is suppossed to create a new spreadsheet: #!/usr/bin/python import gdata.spreadsheet.text_db import getpass import atom import gdata.contacts import gdata.contacts.service import smtplib import time password = getpass.getpass() client =...
CreateDatabase often fails on the google data api
The following test program is suppossed to create a new spreadsheet: #!/usr/bin/python import gdata.spreadsheet.text_db import getpass import atom import gdata.contacts import gdata.contacts.service import smtplib import time password = getpass.getpass() client = gdata.spreadsheet.text_db.DatabaseClient(username='jmv...
[ "Someone clued me in that this is a known bug in gdata.\n" ]
[ 1 ]
[]
[]
[ "gdata_api", "python" ]
stackoverflow_0000894881_gdata_api_python.txt
Q: Checking folder/file ntfs permissions using python As the question title might suggest, I would very much like to know of the way to check the ntfs permissions of the given file or folder (hint: those are the ones you see in the "security" tab). Basically, what I need is to take a path to a file or directory (on a...
Checking folder/file ntfs permissions using python
As the question title might suggest, I would very much like to know of the way to check the ntfs permissions of the given file or folder (hint: those are the ones you see in the "security" tab). Basically, what I need is to take a path to a file or directory (on a local machine, or, preferrably, on a share on a remote ...
[ "Unless you fancy rolling your own, win32security is the way to go. There's the beginnings of an example here:\nhttp://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html\nIf you want to live slightly dangerously (!) my in-progress winsys package is designed to do exactly what you're after. You can g...
[ 17 ]
[]
[]
[ "acl", "ntfs", "permissions", "python", "winapi" ]
stackoverflow_0000896638_acl_ntfs_permissions_python_winapi.txt
Q: Convert list of lists to delimited string How do I do the following using built-in modules only? I have a list of lists like this: [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]] And from it, I'd like to produce a string representation of a table like this where the columns are delimited by tabs and th...
Convert list of lists to delimited string
How do I do the following using built-in modules only? I have a list of lists like this: [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]] And from it, I'd like to produce a string representation of a table like this where the columns are delimited by tabs and the rows by newlines. dog 1 cat 2 a rat 3 4...
[ "Like this, perhaps:\nlists = [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]]\nresult = \"\\n\".join(\"\\t\".join(map(str,l)) for l in lists)\n\nThis joins all the inner lists using tabs, and concatenates the resulting list of strings using newlines.\nIt uses a feature called list comprehension to process ...
[ 19, 4 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0000898391_list_python_string.txt
Q: Priority issue in Sitemaps I am trying to use Django sitemaps. class BlogSiteMap(Sitemap): """A simple class to get sitemaps for blog""" changefreq = 'hourly' priority = 0.5 def items(self): return Blog.objects.order_by('-pubDate') def lastmod(self, obj): return obj.pubDate ...
Priority issue in Sitemaps
I am trying to use Django sitemaps. class BlogSiteMap(Sitemap): """A simple class to get sitemaps for blog""" changefreq = 'hourly' priority = 0.5 def items(self): return Blog.objects.order_by('-pubDate') def lastmod(self, obj): return obj.pubDate My problem is..I wanted to set ...
[ "I think you can alter each object with its priority. Like that for example:\ndef items(self):\n for i, obj in enumerate(Blog.objects.order_by('-pubDate')):\n obj.priority = i < 3 and 1 or 0.5\n yield obj\n\ndef priority(self, obj):\n return obj.priority\n\n", "Something like that might work:\nd...
[ 1, 0 ]
[]
[]
[ "django", "python", "sitemap" ]
stackoverflow_0000763485_django_python_sitemap.txt
Q: How do I refer to a class method outside a function body in Python? I want to do a one time callback registration within Observer. I don't want to do the registration inside init or other function. I don't know if there is a class level equivalent for init class Observer: @classmethod def on_n...
How do I refer to a class method outside a function body in Python?
I want to do a one time callback registration within Observer. I don't want to do the registration inside init or other function. I don't know if there is a class level equivalent for init class Observer: @classmethod def on_new_user_registration(new_user): #body of handler... ...
[ "I suggest to cut down on the number of classes -- remember that Python isn't Java. Every time you use @classmethod or @staticmethod you should stop and think about it since these keywords are quite rare in Python.\nDoing it like this works:\nclass BaseEvent(object):\n def __init__(self, event_info=None):\n ...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000897739_python.txt
Q: In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically? Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, but if I have something like this: [{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':...
In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically?
Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, but if I have something like this: [{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}] And I want it sorted alphabetically (by Name) + include the condition that the ...
[ "The best approach here is to decorate the sort key... Python will sort a tuple by the tuple components in order, so build a tuple key with your sorting criteria:\nsorted(list_of_dicts, key=lambda d: (d['Name'] == 'TOTAL', d['Name'].lower()))\n\nThis results in a sort key of:\n\n(True, 'total') for {'Name': 'TOTAL'...
[ 10, 1, 0 ]
[ "Well, I would sort it in multiple passes, using list's sort method.\nlist = [{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}]\n\nlist.sort(key = lambda x: x['Name']) # Sorted by Name, alphabetically\n\nlist.sort(key = lambda x: 'b' if x['Name'] == 'TOTAL' else 'a'...
[ -1 ]
[ "dictionary", "list", "python", "sorting" ]
stackoverflow_0000898773_dictionary_list_python_sorting.txt
Q: Django shopping cart/basket solution (or should I DIM)? I'm about to build a site that has about half a dozen fairly similar products. They're all DVDs so they fit into a very "fixed" database very well. I was going to make a DVD model. Tag them up. All very simple. All very easy. But we need to be able to sell th...
Django shopping cart/basket solution (or should I DIM)?
I'm about to build a site that has about half a dozen fairly similar products. They're all DVDs so they fit into a very "fixed" database very well. I was going to make a DVD model. Tag them up. All very simple. All very easy. But we need to be able to sell them. The current site outsources the whole purchasing system b...
[ "Since you asked: if your needs are that limited, it does sound like a DIY situation to me. I don't see what's so fiddly about it; what complexity there is is all in the pricing formula, and you're planning to supply that either way. Add in Django's built-in session support and you're most of the way there.\n", ...
[ 3, 2 ]
[]
[]
[ "django", "e_commerce", "python", "shopping_cart" ]
stackoverflow_0000898426_django_e_commerce_python_shopping_cart.txt
Q: How do you store an app engine Image object in the db? I'm a bit stuck with my code: def setVenueImage(img): img = images.Image(img.read()) x, y = photo_utils.getIdealResolution(img.width, img.height) img.resize(x, y) img.execute_transforms() venue_obj = getVenueSingletonObject() if venue_obj is None: ...
How do you store an app engine Image object in the db?
I'm a bit stuck with my code: def setVenueImage(img): img = images.Image(img.read()) x, y = photo_utils.getIdealResolution(img.width, img.height) img.resize(x, y) img.execute_transforms() venue_obj = getVenueSingletonObject() if venue_obj is None: venue_obj = Venue(images = [img]) else: venue_...
[ "I'm not happy with this solution as it doesn't convert an Image object to a blob, but it will do for the time being:\ndef setVenueImage(img):\n original = img.read()\n img = images.Image(original)\n x, y = photo_utils.getIdealResolution(img.width, img.height)\n img = images.resize(original, x, y)\n venue_obj ...
[ 2, 2, 0 ]
[]
[]
[ "google_app_engine", "image", "python" ]
stackoverflow_0000762764_google_app_engine_image_python.txt
Q: Pad an integer using a regular expression I'm using regular expressions with a python framework to pad a specific number in a version number: 10.2.11 I want to transform the second element to be padded with a zero, so it looks like this: 10.02.11 My regular expression looks like this: ^(\d{2}\.)(\d{1})([\.].*) I...
Pad an integer using a regular expression
I'm using regular expressions with a python framework to pad a specific number in a version number: 10.2.11 I want to transform the second element to be padded with a zero, so it looks like this: 10.02.11 My regular expression looks like this: ^(\d{2}\.)(\d{1})([\.].*) If I just regurgitate back the matching groups, ...
[ "How about a completely different approach?\nnums = version_string.split('.')\nprint \".\".join(\"%02d\" % int(n) for n in nums)\n\n", "Try this:\n(^\\d(?=\\.)|(?<=\\.)\\d(?=\\.)|(?<=\\.)\\d$)\n\nAnd replace the match by 0\\1. This will make any number at least two digits long.\n", "What about removing the . fr...
[ 3, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000899804_python_regex.txt
Q: Producing documentation for Python classes I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general. Is there a good (free) system that I can use to p...
Producing documentation for Python classes
I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general. Is there a good (free) system that I can use to provide documentation for classes and functions b...
[ "I have used epydoc to generate documentation for Python modules from embedded docstrings. It's pretty easy to use and generates nice looking output in multiple formats.\n", "python.org is now using sphinx for it's documentation.\nI personally like the output of sphinx over epydoc. I also feel the restructured te...
[ 12, 11, 4, 3, 2 ]
[]
[]
[ "data_structures", "documentation", "python" ]
stackoverflow_0000389688_data_structures_documentation_python.txt
Q: pywikipedia name wikiquote is not defined? I'm writing a bot for Wikipedia but have a problem. When I want to get stuff from another Wikimedia site I get the error - error-name 'wikiquote' is not defined. This is when I start the code off like this- import wikipedia site = wikiquote.getSite() Yet if I was to st...
pywikipedia name wikiquote is not defined?
I'm writing a bot for Wikipedia but have a problem. When I want to get stuff from another Wikimedia site I get the error - error-name 'wikiquote' is not defined. This is when I start the code off like this- import wikipedia site = wikiquote.getSite() Yet if I was to start it with wikipedia written instead of wikiquo...
[ "wikiquote is not defined or imported anywhere in your script. So it is understandable that your code does not work.\nAccording to documentation of pywikipedia, you need to use this instead:\nimport wikipedia\nsite = wikipedia.getSite('en', 'wikiquote')\n\n", "If you're only running this for yourself, it doesn't ...
[ 2, 0 ]
[]
[]
[ "python", "python_2.6", "pywikibot" ]
stackoverflow_0000900306_python_python_2.6_pywikibot.txt
Q: Is there a high-level way to read in lines from an output file and have the types recognized by the structure of the contents? Suppose I have an output file that I want to read and each line was created by joining several types together, prepending and appending the list braces, [('tupleValueA','tupleValueB'), 's...
Is there a high-level way to read in lines from an output file and have the types recognized by the structure of the contents?
Suppose I have an output file that I want to read and each line was created by joining several types together, prepending and appending the list braces, [('tupleValueA','tupleValueB'), 'someString', ('anotherTupleA','anotherTupleB')] I want to read the lines in. Now I can read them in, and operate on the string to a...
[ "What you are looking for is eval. But please keep in mind that this function will evaluate and execute the lines. So don't run it on untrusted input ever!\n>>> print eval(\"[('tupleValueA', 1), 'someString']\")\n[('tupleValueA', 1), 'someString']\n\nIf you have control over the script that generate the output file...
[ 2, 0, 0 ]
[]
[]
[ "python", "string", "tuples" ]
stackoverflow_0000900396_python_string_tuples.txt
Q: Passing Variables to Django Comment Views Alright, I know I've asked similar questions, but I feel this is hopefully a bit different. I'm integrating django.comments into my application, and the more I play with it, the more I realize it may not even be worth my while at the end of the day. That aside, I've manage...
Passing Variables to Django Comment Views
Alright, I know I've asked similar questions, but I feel this is hopefully a bit different. I'm integrating django.comments into my application, and the more I play with it, the more I realize it may not even be worth my while at the end of the day. That aside, I've managed to add Captcha to my comments, and I've learn...
[ "Dynamic data in sidebars is what template tags are for.\nThere's absolutely no need to muck around with the built-in views - just define the tags add them to your templates.\n", "I user template tags as well. Templates in Django are truly for displaying data only.\nI think Django believes in separation between t...
[ 3, 0 ]
[]
[]
[ "django", "django_comments", "python" ]
stackoverflow_0000896532_django_django_comments_python.txt
Q: Understanding python imports In the process of learning Django and Python. I can't make sense of this. (Example Notes:'helloworld' is the name of my project. It has 1 app called 'app'.) from helloworld.views import * # <<-- this works from helloworld import views # <<-- this doesn't work from...
Understanding python imports
In the process of learning Django and Python. I can't make sense of this. (Example Notes:'helloworld' is the name of my project. It has 1 app called 'app'.) from helloworld.views import * # <<-- this works from helloworld import views # <<-- this doesn't work from helloworld.app import views ...
[ "Python imports can import two different kinds of things: modules and objects.\nimport x\n\nImports an entire module named x.\nimport x.y\n\nImports a module named y and it's container x. You refer to x.y. \nWhen you created it, however, you created this directory structure\nx\n __init__.py\n y.py\n\nWhen y...
[ 11, 4, 1 ]
[]
[]
[ "django", "import", "python" ]
stackoverflow_0000900591_django_import_python.txt
Q: Creating a python win32 service I am currently trying to create a win32 service using pywin32. My main point of reference has been this tutorial: http://code.activestate.com/recipes/551780/ What i don't understand is the initialization process, since the Daemon is never initialized directly by Daemon(), instead fr...
Creating a python win32 service
I am currently trying to create a win32 service using pywin32. My main point of reference has been this tutorial: http://code.activestate.com/recipes/551780/ What i don't understand is the initialization process, since the Daemon is never initialized directly by Daemon(), instead from my understanding its initialized b...
[ "I just create a simple \"how to\" where the program is in one module and the service is in another place, it uses py2exe to create the win32 service, which I believe is the best you can do for your users that don't want to mess with the python interpreter or other dependencies.\nYou can check my tutorial here: Cre...
[ 10, 6 ]
[]
[]
[ "python", "pywin32", "winapi" ]
stackoverflow_0000263296_python_pywin32_winapi.txt
Q: How to work with threads in pygtk I have a problem with threads in pygtk. My application consist of a program that downloads pictures off the internet and then displays it with pygtk. The problem is that in order to do this and keep the GUI responsive, I need to use threads. So I got into a callback after the use...
How to work with threads in pygtk
I have a problem with threads in pygtk. My application consist of a program that downloads pictures off the internet and then displays it with pygtk. The problem is that in order to do this and keep the GUI responsive, I need to use threads. So I got into a callback after the user clicked on the button "Download pictu...
[ "Your question is a bit vague, and without a reference to your actual code it's hard to speculate what you're doing wrong.\nSo I'll give you some pointers to read, then speculate wildly based on experience.\nFirst of all, you seem to think that you can only keep the GUI responsive by using threads. This is not tru...
[ 12, 1 ]
[]
[]
[ "multithreading", "pygtk", "python" ]
stackoverflow_0000809818_multithreading_pygtk_python.txt
Q: drawing a pixbuf onto a drawing area using pygtk and glade i'm trying to make a GTK application in python where I can just draw a loaded image onto the screen where I click on it. The way I am trying to do this is by loading the image into a pixbuf file, and then drawing that pixbuf onto a drawing area. the main l...
drawing a pixbuf onto a drawing area using pygtk and glade
i'm trying to make a GTK application in python where I can just draw a loaded image onto the screen where I click on it. The way I am trying to do this is by loading the image into a pixbuf file, and then drawing that pixbuf onto a drawing area. the main line of code is here: def drawing_refresh(self, widget, event): ...
[ "I found out I just need to get the function to call another expose event with widget.queue_draw() at the end of the function. The function was only being called once at the start, and there were no nodes available at this point so nothing was being drawn.\n", "You can make use of cairo to do this. First, create ...
[ 3, 3 ]
[]
[]
[ "drawing", "glade", "pygtk", "python" ]
stackoverflow_0000775528_drawing_glade_pygtk_python.txt
Q: File I/O in the Python 3 C API The C API in Python 3.0 has changed (deprecated) many of the functions for File Objects. Before, in 2.X, you could use PyObject* PyFile_FromString(char *filename, char *mode) to create a Python file object, e.g: PyObject *myFile = PyFile_FromString("test.txt", "r"); ...but such fun...
File I/O in the Python 3 C API
The C API in Python 3.0 has changed (deprecated) many of the functions for File Objects. Before, in 2.X, you could use PyObject* PyFile_FromString(char *filename, char *mode) to create a Python file object, e.g: PyObject *myFile = PyFile_FromString("test.txt", "r"); ...but such function no longer exists in Python 3.0...
[ "You can do it the old(new?)-fashioned way, by just calling the io module.\nThis code works, but it does no error checking. See the docs for explanation.\nPyObject *ioMod, *openedFile;\n\nPyGILState_STATE gilState = PyGILState_Ensure();\n\nioMod = PyImport_ImportModule(\"io\");\n\nopenedFile = PyObject_CallMethod(...
[ 10, 4 ]
[]
[]
[ "python", "python_3.x", "python_c_api" ]
stackoverflow_0000898136_python_python_3.x_python_c_api.txt
Q: Satchmo donations Can anyone share some pointers on building a Donations module for Satchmo? I'm comfortable customizing Satchmo's product models etc but unable to find anything related to Donations I realize it's possible to create a Donations virtual product but as far as I can tell this still requires setting t...
Satchmo donations
Can anyone share some pointers on building a Donations module for Satchmo? I'm comfortable customizing Satchmo's product models etc but unable to find anything related to Donations I realize it's possible to create a Donations virtual product but as far as I can tell this still requires setting the amount beforehand ($...
[ "It looks like the satchmo_cart_details_query signal is the way to go about doing this. It allows you to add a price change value (in my case, donation amount) to a cart item\nI'll post the full solution if anyone is interested\n" ]
[ 3 ]
[]
[]
[ "django", "e_commerce", "python", "satchmo" ]
stackoverflow_0000891934_django_e_commerce_python_satchmo.txt
Q: Replace in Python-* equivalent? If I am finding & replacing some text how can I get it to replace some text that will change each day so ie anything between (( & )) whatever it is? Cheers! A: Use regular expressions (http://docs.python.org/library/re.html)? Could you please be more specific, I don't think I full...
Replace in Python-* equivalent?
If I am finding & replacing some text how can I get it to replace some text that will change each day so ie anything between (( & )) whatever it is? Cheers!
[ "Use regular expressions (http://docs.python.org/library/re.html)?\nCould you please be more specific, I don't think I fully understand what you are trying to accomplish.\nEDIT:\nOk, now I see. This may be done even easier, but here goes:\n>>> import re\n\n>>> s = \"foo(bar)whatever\"\n>>> r = re.compile(r\"(\\()(....
[ 4 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0000901074_python_replace.txt
Q: Need help with the class and instance concept in Python I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet. Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance...
Need help with the class and instance concept in Python
I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet. Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat trough the in...
[ "Your question is really rather broad as classes and instances/objects are vital parts of object-oriented programming, so this is not really Python specific. I recommend you buy some books on this as, while initially basic, it can get pretty in-depth. In essense, however:\n\nThe most popular and developed model of ...
[ 7, 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000900929_python.txt
Q: Dynamic function calls in Python using XMLRPC I'm writing a class which I intend to use to create subroutines, constructor as following: def __init__(self,menuText,RPC_params,RPC_call): #Treat the params #Call the given RPC_call with the treated params The problem is that I want to call the function on the ...
Dynamic function calls in Python using XMLRPC
I'm writing a class which I intend to use to create subroutines, constructor as following: def __init__(self,menuText,RPC_params,RPC_call): #Treat the params #Call the given RPC_call with the treated params The problem is that I want to call the function on the pattern "rpc.serve.(function name here)(params)", w...
[ "You can use getattr to get the function name from the server proxy, so calling the function like this will work:\ngetattr(rpc, function_name)(*params)\n\n" ]
[ 2 ]
[]
[]
[ "function", "python", "rpc", "xml_rpc" ]
stackoverflow_0000901391_function_python_rpc_xml_rpc.txt
Q: finding substring Thanks in advance.I want to find all the substring that occurs between K and N,eventhough K and N occurs in between any number of times. for example a='KANNKAAN' OUTPUT; [KANNKAAN, KANN , KAN ,KAAN] A: import re def occurences(ch_searched, str_input): return [i.start...
finding substring
Thanks in advance.I want to find all the substring that occurs between K and N,eventhough K and N occurs in between any number of times. for example a='KANNKAAN' OUTPUT; [KANNKAAN, KANN , KAN ,KAAN]
[ "import re\n\ndef occurences(ch_searched, str_input):\n return [i.start() for i in re.finditer(ch_searched, str_input)]\n\ndef betweeners(str_input, ch_from, ch_to):\n starts = occurences(ch_from, str_input)\n ends = occurences(ch_to, str_input)\n result = []\n for start in starts:\n for end i...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000901070_python.txt
Q: Python: Joining Multiple Lists to one single Sentence Howdy, I've got multiple lists. For example: [u'This/ABC'] [u'is/ABC'] [u'not/ABC'] [u'even/ABC'] [u'close/ABC'] [u'to/ABC'] [u'funny/ABC'] [u'./ABC'] [u'O/ABC'] [u'noez/ABC'] [u'!/ABC'] I need to join this List to This/ABC is/ABC not/ABC even/ABC close/ABC t...
Python: Joining Multiple Lists to one single Sentence
Howdy, I've got multiple lists. For example: [u'This/ABC'] [u'is/ABC'] [u'not/ABC'] [u'even/ABC'] [u'close/ABC'] [u'to/ABC'] [u'funny/ABC'] [u'./ABC'] [u'O/ABC'] [u'noez/ABC'] [u'!/ABC'] I need to join this List to This/ABC is/ABC not/ABC even/ABC close/ABC to/ABC funny/ABC ./ABC O/ABC noez/ABC !/ABC How do I do th...
[ "If you put them all in a list, for example like this:\na = [\n [u'This/ABC'],\n [u'is/ABC'],\n ...\n]\n\nYou can get your result by adding all the lists and using a regular join on the result:\nresult = ' '.join(sum(a, []))\n\n\nAfter re-reading the question a couple of times, I suppose you also want that...
[ 6, 3, 1, 0 ]
[]
[]
[ "join", "list", "python" ]
stackoverflow_0000901412_join_list_python.txt
Q: Executing *nix binaries in Python I need to run the following command: screen -dmS RealmD top Essentially invoking GNU screen in the background with the session title 'RealmD' with the top command being run inside screen. The command MUST be invoked this way so there can't be a substitute for screen at this time ...
Executing *nix binaries in Python
I need to run the following command: screen -dmS RealmD top Essentially invoking GNU screen in the background with the session title 'RealmD' with the top command being run inside screen. The command MUST be invoked this way so there can't be a substitute for screen at this time until the server is re-tooled. (Another...
[ "os.system is the simplest way, but, for many more possibilities and degrees of freedom, also look at the standard library subprocess module (unless Stephan202's wonderfully simple use of os.system meets all your needs, of course;-).\nEdit Here's the standard replacement for os.system()\np = Popen(\"screen -dmS Rea...
[ 11, 7 ]
[]
[]
[ "gnu_screen", "python" ]
stackoverflow_0000901829_gnu_screen_python.txt
Q: Give Wxwidget Grid rows an ID I posted this in the mailing list, but the reply I got wasn't too clear, so maybe I'll have better luck here. I currently have a grid with data in it. I would like to know if there is a way to give each generated row an ID, or at least, associate each row with an object. It may make i...
Give Wxwidget Grid rows an ID
I posted this in the mailing list, but the reply I got wasn't too clear, so maybe I'll have better luck here. I currently have a grid with data in it. I would like to know if there is a way to give each generated row an ID, or at least, associate each row with an object. It may make it more clear if I clarify what i'm ...
[ "What I did when I encountered such a case was to create a column for IDs and set its width to 0.\n", "You could make your own GridTableBase that implements this, for a simple example to get you started see my answer to this question.\n" ]
[ 3, 2 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0000901704_python_wxpython_wxwidgets.txt
Q: Django not picking up changes to INSTALLED_APPS in settings.py I'm trying to get South to work - it worked fine on my PC, but I'm struggling to deploy it on my webhost. Right now it seems that any changes I make to add/remove items from INSTALLED_APPS aren't being picked up by syncdb or diffsettings. I've added so...
Django not picking up changes to INSTALLED_APPS in settings.py
I'm trying to get South to work - it worked fine on my PC, but I'm struggling to deploy it on my webhost. Right now it seems that any changes I make to add/remove items from INSTALLED_APPS aren't being picked up by syncdb or diffsettings. I've added south to my list of INSTALLED_APPS, but the tables it needs aren't bei...
[ "If you write a migration for an application, syncdb wont work.\nYou have to use \nmanage.py migrate\n\nsyncdb wont work for applications which are hooked under migration using south. Those applications model change will be noticed only depending on south migration history.\nSouth Migration Docs\n", "The answer, ...
[ 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000901061_django_python.txt
Q: Issue with adding new properties to existing Google AppEngine data models / entities In GAE, I have a model called Foo, with existing entities, and attempt to add a new property called memcached to Foo that takes datetime values for the last time this value was set to memcache. If I try to query and sort on this ...
Issue with adding new properties to existing Google AppEngine data models / entities
In GAE, I have a model called Foo, with existing entities, and attempt to add a new property called memcached to Foo that takes datetime values for the last time this value was set to memcache. If I try to query and sort on this property, or even filter for entities that do not have a value for memcached, entities tha...
[ "There's nothing for it but to go through each of your existing entities and add the property, here is the official documentation which walks you through the process.\n" ]
[ 8 ]
[]
[]
[ "bigtable", "google_app_engine", "properties", "python" ]
stackoverflow_0000902633_bigtable_google_app_engine_properties_python.txt
Q: python factory functions compared to class Simple example of a nested function: def maker(N): def action(X): return X * N return action Do factory functions have advantages over creating a class? Performance, memory, clean up? A: What I like most about nested functions is that it is less verbose...
python factory functions compared to class
Simple example of a nested function: def maker(N): def action(X): return X * N return action Do factory functions have advantages over creating a class? Performance, memory, clean up?
[ "What I like most about nested functions is that it is less verbose than classes. The equivalent class definition to your maker function is:\nclass clsmaker(object):\n def __init__(self, N):\n self.N = N\n def __call__(self, X):\n return X * self.N\n\nThat doesn't seem so bad until you start add...
[ 29, 18, 6 ]
[]
[]
[ "function", "python" ]
stackoverflow_0000901892_function_python.txt
Q: Django, custom template filters - regex problems I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input....
Django, custom template filters - regex problems
I'm trying to implement a WikiLink template filter in Django that queries the database model to give different responses depending on Page existence, identical to Wikipedia's red links. The filter does not raise an Error but instead doesn't do anything to the input. WikiLink is defined as: [[ThisIsAWikiLink | This is t...
[ "If your string contains other text in addition to the wiki-link, your filter won't work because you are using re.match instead of re.search. re.match matches at the beginning of the string. re.search matches anywhere in the string. See matching vs. searching.\nAlso, your regex uses the greedy *, so it won't work i...
[ 4, 3, 1, 0 ]
[]
[]
[ "django", "django_templates", "python", "regex" ]
stackoverflow_0000902184_django_django_templates_python_regex.txt
Q: How does the win32com python.Interpreter work? Ok, so I'm trying to google the win32com python package and the python.Interpreter COM server. Unfortunately, python.Interpreter ends up as "python Interpreter" and not giving me any COM server results. I'm trying to make a pluggable program that has a plugin to allo...
How does the win32com python.Interpreter work?
Ok, so I'm trying to google the win32com python package and the python.Interpreter COM server. Unfortunately, python.Interpreter ends up as "python Interpreter" and not giving me any COM server results. I'm trying to make a pluggable program that has a plugin to allow python code to run, and it seems like the python.I...
[ "See http://books.google.com/books?id=ns1WMyLVnRMC&pg=PA232&lpg=PA232&dq=win32com+%22python.interpreter%22&source=bl&ots=NVpe-E8eGg&sig=imGi73WQyOmP4rJC6-jpz4stb9M&hl=en&ei=xrAYSsTHBZH0tAORqeCSDw&sa=X&oi=book_result&ct=result&resnum=6#PPA232,M1 for excellent docs on python.interpreter -- as for your second question...
[ 1 ]
[]
[]
[ "com", "python" ]
stackoverflow_0000902895_com_python.txt
Q: Data storage to ease data interpolation in Python I have 20+ tables similar to table 1. Where all letters represent actual values. Table 1: $ / cars |<1 | 2 | 3 | 4+ <10,000 | a | b | c | d 20,000 | e | f | g | h 30,000 | i | j | k | l 40,000+ | m | n | o | p A user input could be for example, (2.4, 24594) ...
Data storage to ease data interpolation in Python
I have 20+ tables similar to table 1. Where all letters represent actual values. Table 1: $ / cars |<1 | 2 | 3 | 4+ <10,000 | a | b | c | d 20,000 | e | f | g | h 30,000 | i | j | k | l 40,000+ | m | n | o | p A user input could be for example, (2.4, 24594) which is a value between f, g, j, and k. My Python func...
[ "If you want the most computationally efficient solution I can think of and are not restricted to the standard library, then I would recommend scipy/numpy. First, store the a..p array as a 2D numpy array and then both the $4k-10k and 1-4 arrays as 1D numpy arrays. Use scipy's interpolate.interp1d if both 1D array...
[ 7, 3, 0 ]
[]
[]
[ "interpolation", "python" ]
stackoverflow_0000902910_interpolation_python.txt
Q: How to embed a Poll in a Web Page I want to create a simple online poll application. I have created a backend in python that handles vote tracking, poll display, results display and admin setup. However, if I wanted a third party to be able to embed the poll in their website, what would be the recommended way of...
How to embed a Poll in a Web Page
I want to create a simple online poll application. I have created a backend in python that handles vote tracking, poll display, results display and admin setup. However, if I wanted a third party to be able to embed the poll in their website, what would be the recommended way of doing so? I would love to be able to ...
[ "Make your app into a Google Gadget, Open Social gadget, or other kind of gadgets -- these are all designed to be embeddable into third-party pages with as little fuss as possible.\n", "IFrame is the easiest no muss no fuss solution if you want to allow postbacks.\nOr, this is a bit left field and oldschool, but ...
[ 1, 1 ]
[]
[]
[ "cross_domain", "javascript", "python" ]
stackoverflow_0000903104_cross_domain_javascript_python.txt
Q: How to implement hotlinking prevention in Google App Engine My application is on GAE and I'm trying to figure out how to prevent hotlinking of images dynamically served (e.g. /image?id=E23432E) in Python. Please advise. A: In Google webapp framework, you can extract the referer from the Request class: def get(se...
How to implement hotlinking prevention in Google App Engine
My application is on GAE and I'm trying to figure out how to prevent hotlinking of images dynamically served (e.g. /image?id=E23432E) in Python. Please advise.
[ "In Google webapp framework, you can extract the referer from the Request class:\ndef get(self):\n referer = self.request.headers.get(\"Referer\")\n # Will be None if no referer given in header.\n\nNote that's referer, not referrer (see this dictionary entry).\n" ]
[ 11 ]
[]
[]
[ "google_app_engine", "hotlinking", "python" ]
stackoverflow_0000903144_google_app_engine_hotlinking_python.txt
Q: Why is the PyObjC documentation so bad? For example, http://developer.apple.com/cocoa/pyobjc.html is still for OS X 10.4 Tiger, not 10.5 Leopard.. And that's the official Apple documentation for it.. The official PyObjC page is equally bad, http://pyobjc.sourceforge.net/ It's so bad it's baffling.. I'm considering...
Why is the PyObjC documentation so bad?
For example, http://developer.apple.com/cocoa/pyobjc.html is still for OS X 10.4 Tiger, not 10.5 Leopard.. And that's the official Apple documentation for it.. The official PyObjC page is equally bad, http://pyobjc.sourceforge.net/ It's so bad it's baffling.. I'm considering learning Ruby primarily because the RubyCoco...
[ "The main reason for the lack of documentation for PyObjC is that there is one developer (me), and as most developers I don't particularly like writing documentation. Because PyObjC is a side project for me I tend to focus on working on features and bugfixes, because that's more interesting for me.\nThe best way to...
[ 31, 21, 21, 7, 7, 5, 5, 3, 3 ]
[]
[]
[ "cocoa", "macos", "pyobjc", "python" ]
stackoverflow_0000014422_cocoa_macos_pyobjc_python.txt
Q: How do I represent a void pointer in a PyObjC selector? I'm wanting to use an NSOpenPanel for an application I'm designing. Here's what I have so far: @objc.IBAction def ShowOpenPanel_(self, sender): self.panel = NSOpenPanel.openPanel() self.panel.setCanChooseFiles_(False) self.panel.setCanChooseDirec...
How do I represent a void pointer in a PyObjC selector?
I'm wanting to use an NSOpenPanel for an application I'm designing. Here's what I have so far: @objc.IBAction def ShowOpenPanel_(self, sender): self.panel = NSOpenPanel.openPanel() self.panel.setCanChooseFiles_(False) self.panel.setCanChooseDirectories_(True) NSLog(u'Starting OpenPanel') self.panel...
[ "I think you don't need to use objc.selector at all; try this instead:\n@objc.IBAction\ndef ShowOpenPanel_(self, sender):\n self.panel = NSOpenPanel.openPanel()\n self.panel.setCanChooseFiles_(False)\n self.panel.setCanChooseDirectories_(True)\n NSLog(u'Starting OpenPanel')\n self.panel.beginForDirec...
[ 1, 1 ]
[]
[]
[ "macos", "objective_c", "pyobjc", "python", "void_pointers" ]
stackoverflow_0000845970_macos_objective_c_pyobjc_python_void_pointers.txt
Q: Why can I not view my Google App Engine cron admin page? When I go to http://localhost:8080/_ah/admin/cron, as stated in Google's docs, I get the following: Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 501, in __call__ handler.get(...
Why can I not view my Google App Engine cron admin page?
When I go to http://localhost:8080/_ah/admin/cron, as stated in Google's docs, I get the following: Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 501, in __call__ handler.get(*groups) File "C:\Program Files\Google\google_appengine\google...
[ "This is definitely a bug in Google App Engine. If you check groctimespecification.py, you'll see that IntervalTimeSpecification inherits from TimeSpecification, which in turn inherits directly from object and doesn't override its __init__ method.\nSo the __init__ of IntervalTimeSpecification is incorrect:\nclass I...
[ 4, 3 ]
[]
[]
[ "cron", "google_app_engine", "python", "stack_trace" ]
stackoverflow_0000902039_cron_google_app_engine_python_stack_trace.txt
Q: python, regular expressions, named groups and "logical or" operator In python regular expression, named and unnamed groups are both defined with '(' and ')'. This leads to a weird behavior. Regexp "(?P<a>1)=(?P<b>2)" used with text "1=2" will find named group "a" with value "1" and named group "b" with value "2"....
python, regular expressions, named groups and "logical or" operator
In python regular expression, named and unnamed groups are both defined with '(' and ')'. This leads to a weird behavior. Regexp "(?P<a>1)=(?P<b>2)" used with text "1=2" will find named group "a" with value "1" and named group "b" with value "2". But if i want to use "logical or" operator and concatenate multiple rule...
[ "Use (?:) to get rid of the unnamed group:\nr\"(?:(?P<a>1)=(?P<b>2))|(?P<c>3)\"\n\nFrom the documentation of re:\n\n(?:...) A non-grouping version of\n regular parentheses. Matches whatever\n regular expression is inside the\n parentheses, but the substring matched\n by the group cannot be retrieved after\n pe...
[ 15 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000903562_python_regex.txt
Q: Python - get static information i have to get static information from one 'module' to another. I'm trying to write logger with information about code place from where we're logging. For example, in some file: LogObject.Log('Describe error', STATIC_INFORMATION) Static information is class name, file name and funct...
Python - get static information
i have to get static information from one 'module' to another. I'm trying to write logger with information about code place from where we're logging. For example, in some file: LogObject.Log('Describe error', STATIC_INFORMATION) Static information is class name, file name and function name. I get it from this: __file_...
[ "I don't think \"static\" is the world you're looking for. If I understand you correctly, you want to write a function that will return the filename, class name and method name of the caller.\nBasically, you should use sys._getframe(1) to access the previous frame, and work from there.\nExample:\ndef codeinfo():\n ...
[ 3, 2 ]
[]
[]
[ "python", "static", "variables" ]
stackoverflow_0000903497_python_static_variables.txt
Q: is it possible to call python methods from a C program? I remember seeing somewhere that you could call python methods from inside C using #include "python.h" But I can't seem to find the source for this or any examples. How can I call python methods from inside a C program? A: Here's a doc item from the python...
is it possible to call python methods from a C program?
I remember seeing somewhere that you could call python methods from inside C using #include "python.h" But I can't seem to find the source for this or any examples. How can I call python methods from inside a C program?
[ "Here's a doc item from the python site about extending C with python functionality\nHere's the start of the documentation (where it refers to python.h) where you can extend Python with C functionality.\n", "Check out http://docs.python.org/c-api\n" ]
[ 5, 2 ]
[]
[]
[ "c", "embedding", "python" ]
stackoverflow_0000903596_c_embedding_python.txt
Q: Prevent splitting Window when using pythoncomplete in Vim I'm using VIM with pythoncomplete. When I'm making a completion, the current window is splitted and calltips are shown in the upper pane. I hate that! Is there a way to prevent that behavior or at least limit the size of the upper pane automaticly? A: You...
Prevent splitting Window when using pythoncomplete in Vim
I'm using VIM with pythoncomplete. When I'm making a completion, the current window is splitted and calltips are shown in the upper pane. I hate that! Is there a way to prevent that behavior or at least limit the size of the upper pane automaticly?
[ "You need to do something like:\nset completeopt-=preview\n\nThis will prevent the opening of the preview window. \n" ]
[ 5 ]
[]
[]
[ "autocomplete", "python", "vim" ]
stackoverflow_0000903847_autocomplete_python_vim.txt
Q: Cannot access Python server running as Windows service I have written a Python TCP/IP server for internal use, using win32serviceutil/py2exe to create a Windows service. I installed it on a computer running Windows XP Pro SP3. However, I can't connect to it when it's running as a service. I can confirm that it's b...
Cannot access Python server running as Windows service
I have written a Python TCP/IP server for internal use, using win32serviceutil/py2exe to create a Windows service. I installed it on a computer running Windows XP Pro SP3. However, I can't connect to it when it's running as a service. I can confirm that it's binding to the address/port, because I get a conflict when I ...
[ "Possibly the program may be terminated just after initialization. Please check whether it is continuously listening to the requests.\nnetstat -an |find /i \"listening\"\n\nAnd analyze the command line parsed to the programs. You may use procexp to do that.\n", "First of all, whenever you implement a Windows serv...
[ 1, 1, 0 ]
[]
[]
[ "python", "tcp", "windows_services" ]
stackoverflow_0000833062_python_tcp_windows_services.txt
Q: Python: Sending a large dictionary to a server I have an application that should communicate status information to a server. This information is effectively a large dictionary with string keys. The server will run a web application based on Turbogears, so the server-side method called accepts an arbitrary number o...
Python: Sending a large dictionary to a server
I have an application that should communicate status information to a server. This information is effectively a large dictionary with string keys. The server will run a web application based on Turbogears, so the server-side method called accepts an arbitrary number of keyword arguments. In addition to the actual data,...
[ "I agree with all the answers about avoiding pickle, if safety is a concern (it might not be if the sender gets authenticated before the data's unpickled -- but, when security's at issue, two levels of defense may be better than one); JSON is often of help in such cases (or, XML, if nothing else will do...!-).\nAut...
[ 4, 3, 2, 2, 2, 1 ]
[]
[]
[ "python", "turbogears" ]
stackoverflow_0000903885_python_turbogears.txt
Q: How to tell when a function in another class has been called I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechani...
How to tell when a function in another class has been called
I have two Python classes, call them "C1" and "C2". Inside C1 is a function named "F1" and inside C2 is a function named "F2". Is there a way to execute F2 each time F1 is run without making a direct call to F2 from within F1? Is there some other mechanism by which to know when a function from inside another class has ...
[ "You can write a little helper decorator that will make the call for you. The advantage is that it's easy to tell who is going to call what by looking at the code. And you can add as many function calls as you want. It works like registering a callback function:\nfrom functools import wraps\n\ndef oncall(call):\n ...
[ 3, 2, 2, 2, 1, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0000903818_class_python.txt
Q: Unit testing with nose: tests at compile time? Is it possible for the nose unit testing framework to perform tests during the compilation phase of a module? In fact, I'd like to test something with the following structure: x = 123 # [x is used here...] def test_x(): assert (x == 123) del x # Deleted because I d...
Unit testing with nose: tests at compile time?
Is it possible for the nose unit testing framework to perform tests during the compilation phase of a module? In fact, I'd like to test something with the following structure: x = 123 # [x is used here...] def test_x(): assert (x == 123) del x # Deleted because I don't want to clutter the module with unnecessary att...
[ "A simple way to handle this would be to have a TESTING flag, and write:\nif not TESTING:\n del x\n\nHowever, you won't really be properly testing your modules as the tests will be running under different circumstances to your code.\nThe proper answer is that you shouldn't really be bothering with manually clean...
[ 2, 2 ]
[]
[]
[ "nose", "python", "unit_testing" ]
stackoverflow_0000892297_nose_python_unit_testing.txt
Q: Python's 'with' statement versus 'with .. as' Having just pulled my hair off because of a difference, I'd like to know what the difference really is in Python 2.5. I had two blocks of code (dbao.getConnection() returns a MySQLdb connection). conn = dbao.getConnection() with conn: # Do stuff And with dbao.getC...
Python's 'with' statement versus 'with .. as'
Having just pulled my hair off because of a difference, I'd like to know what the difference really is in Python 2.5. I had two blocks of code (dbao.getConnection() returns a MySQLdb connection). conn = dbao.getConnection() with conn: # Do stuff And with dbao.getConnection() as conn: # Do stuff I thought thes...
[ "It may be a little confusing at first glance, but \nwith babby() as b:\n ...\n\nis not equivalent to\nb = babby()\nwith b:\n ...\n\nTo see why, here's how the context manager would be implemented:\nclass babby(object):\n def __enter__(self):\n return 'frigth'\n\n def __exit__(self, type, value, ...
[ 36, 21, 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0000903557_python_syntax.txt
Q: How to parse malformed HTML in python I need to browse the DOM tree of a parsed HTML document. I'm using uTidyLib before parsing the string with lxml a = tidy.parseString(html_code, options) dom = etree.fromstring(str(a)) sometimes I get an error, it seems that tidylib is not able to repair malformed html. how can...
How to parse malformed HTML in python
I need to browse the DOM tree of a parsed HTML document. I'm using uTidyLib before parsing the string with lxml a = tidy.parseString(html_code, options) dom = etree.fromstring(str(a)) sometimes I get an error, it seems that tidylib is not able to repair malformed html. how can I parse every HTML file without getting an...
[ "Beautiful Soup does a good job with invalid/broken HTML\n>>> from BeautifulSoup import BeautifulSoup\n>>> soup = BeautifulSoup(\"<htm@)($*><body><table <tr><td>hi</tr></td></body><html\")\n>>> print soup.prettify()\n<htm>\n <body>\n <table>\n <tr>\n <td>\n hi\n </td>\n </tr>\n </table>\n </body>\n<...
[ 27, 13 ]
[]
[]
[ "html", "lxml", "python" ]
stackoverflow_0000904644_html_lxml_python.txt
Q: Problem with datetime module-Python How come this works: import datetime now = datetime.datetime.now() month = '%d' % now.month print month But this doesn't? import datetime now = datetime.datetime.now() month = '%m' % now.month print month Thanks! A: %m is not a supported format character for the % operator...
Problem with datetime module-Python
How come this works: import datetime now = datetime.datetime.now() month = '%d' % now.month print month But this doesn't? import datetime now = datetime.datetime.now() month = '%m' % now.month print month Thanks!
[ "%m is not a supported format character for the % operator. Here is the list of supported formating characters for this operator\n%m is valid when your are using strftime function to build a date string\n", "'%d' is a format character that insert a \"signed integer decimal\", '%m' has no such meaning. The possibl...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000904852_python.txt
Q: How to do this with datetime & getpage in Python? Currently having some problems- now = datetime.datetime.now() month = now.strftime("%B") site = wikipedia.getSite('en', 'wikiquote') page = wikipedia.Page(site, u"Wikiquote:Quote_of_the_day:abc") I need to get abc to change into the name of the month before it th...
How to do this with datetime & getpage in Python?
Currently having some problems- now = datetime.datetime.now() month = now.strftime("%B") site = wikipedia.getSite('en', 'wikiquote') page = wikipedia.Page(site, u"Wikiquote:Quote_of_the_day:abc") I need to get abc to change into the name of the month before it then tries to get the page, yet everything I try it give...
[ "The page URL format is actually Wikiquote:Quote_of_the_day/Month. Try this:\npage = wikipedia.Page(site, u\"Wikiquote:Quote_of_the_day/%s\" % month)\n\n", "Would this work?\npage = wikipedia.Page(site, u\"Wikiquote:Quote_of_the_day:\" + month)\n\n", "Did you try this:\npage = wikipedia.Page(site, u\"Wikiquote:...
[ 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000904894_python.txt
Q: Python - how to implement Bridge (or Adapter) design pattern? I'm struggling with implementing the Bridge design pattern (or an alternative such as Adapter) in Python I want to be able to write code like this to dump database schemas based on a supplied URL: urls = ['sqlite://c:\\temp\\test.db', 'oracle://user:pas...
Python - how to implement Bridge (or Adapter) design pattern?
I'm struggling with implementing the Bridge design pattern (or an alternative such as Adapter) in Python I want to be able to write code like this to dump database schemas based on a supplied URL: urls = ['sqlite://c:\\temp\\test.db', 'oracle://user:password@tns_name']; for url in urls: db = Database(url); sche...
[ "Use a Factory pattern instead:\nclass Oracle(object):\n ...\n\nclass SQLite(object):\n ...\n\ndbkind = dict(sqlite=SQLite, oracle=Oracle)\n\ndef Database(url):\n db_type, rest = string.split(self.url, \"://\", 1)\n return dbkind[db_type](rest)\n\n" ]
[ 26 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0000905289_design_patterns_python.txt
Q: How can I draw automatic graphs using dot in Python on a Mac? I am producing graphs in a Python program, and now I need to visualize them. I am using Tkinter as GUI to visualize all the other data, and I would like to have a small subwindow inside with the graph of the data. At the moment I have the data being rep...
How can I draw automatic graphs using dot in Python on a Mac?
I am producing graphs in a Python program, and now I need to visualize them. I am using Tkinter as GUI to visualize all the other data, and I would like to have a small subwindow inside with the graph of the data. At the moment I have the data being represented in a .dot file. And then I keep graphviz open, which shows...
[ "I do not have a mac to test it on, but the NetworkX package includes methods to read .dot files and draw graphs using matplotlib. You can embed a matplotlib figure in Tk (example 1, example 2).\n", "Quick Google pulls up http://code.google.com/p/pydot/. I haven't tried it but it looks promising.\n" ]
[ 2, 1 ]
[]
[]
[ "dot", "dyld", "graphviz", "macos", "python" ]
stackoverflow_0000903582_dot_dyld_graphviz_macos_python.txt
Q: Is there any library to find out urls of embedded flvs in a webpage? I'm trying to write a script which can automatically download gameplay videos. The webpages look like dota.sgamer.com/Video/Detail/402 and www.wfbrood.com/movie/spl2009/movie_38214.html, they have flv player embedded in the flash plugin. Is there...
Is there any library to find out urls of embedded flvs in a webpage?
I'm trying to write a script which can automatically download gameplay videos. The webpages look like dota.sgamer.com/Video/Detail/402 and www.wfbrood.com/movie/spl2009/movie_38214.html, they have flv player embedded in the flash plugin. Is there any library to help me find out the exact flv urls? or any other ideas to...
[ "It looks like Flashticle (4th result on searching the cheese shop for \"flash\"), might be able to get the information you want, if it is there.\nAs to getting the file, you want to look at a html parser. I've heard good things about Beautiful Soup. Between that and urllib2 (part of the standard library), you sh...
[ 1, 0 ]
[]
[]
[ "download", "flv", "python" ]
stackoverflow_0000905403_download_flv_python.txt
Q: Storing Python scripts on a webserver Following on my previous question, if I have some hosting how can I put a python script on their that I can then run from there? Do I need to do something special to run it/install something? EDIT-Clarification-I would like to be able to upload the script which does stuff on ...
Storing Python scripts on a webserver
Following on my previous question, if I have some hosting how can I put a python script on their that I can then run from there? Do I need to do something special to run it/install something? EDIT-Clarification-I would like to be able to upload the script which does stuff on the internet-no data is stored on my comput...
[ "You have to ensure your hoster system supports Python.\nYou can ask them about that.\nTo run the script once it is there, you can act in several ways, depending on what you want to do.\nYou can have your server side language to invoke it (i.e. from the backend of a web page), or if you have a shell access to the m...
[ 1, 0 ]
[]
[]
[ "hosting", "python" ]
stackoverflow_0000905902_hosting_python.txt
Q: Why such import is not allowed? FILE: b.py class B: def __init__(self): print "B" import a a = A() FILE: a.py class A(B): ###=> B is not defined def __init__(self): print "A" When I try to execute b.py, it's said that B is not defined. Am I misunderstanding "import"? Thank...
Why such import is not allowed?
FILE: b.py class B: def __init__(self): print "B" import a a = A() FILE: a.py class A(B): ###=> B is not defined def __init__(self): print "A" When I try to execute b.py, it's said that B is not defined. Am I misunderstanding "import"? Thanks a lot if you can pointer out the pr...
[ "Because python initializes class A in its own file. It is not like a C or PHP include where every imported module is essentially pasted into the original file.\nYou should put class B in the same file as class A to fix this problem. Or you can put class B in c.py and import it with \"from c import B\".\n", "The ...
[ 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0000905848_python.txt
Q: HttpResponseRedirect django + facebook I have a form with 2 buttons. depending on the button click user is taken to different url. view function is : friend_id = request.POST.get('selected_friend_id_list') history = request.POST.get('statushistory') if history: print "dfgdfgdf" return HttpResponseRedirec...
HttpResponseRedirect django + facebook
I have a form with 2 buttons. depending on the button click user is taken to different url. view function is : friend_id = request.POST.get('selected_friend_id_list') history = request.POST.get('statushistory') if history: print "dfgdfgdf" return HttpResponseRedirect('../status/') else: return direct_to_...
[ "\"so my problem is page is not redirecting to the url . If I make HttpResponseRedirect('../') it gives me the correct page but url is not changing.\"\nBy \"URL\" I'm guessing you mean \"The URL shown in the browser\". It helps if your question is very precise.\nFirst, you must provide an absolute URL. http://doc...
[ 2, 0 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0000905803_django_facebook_python.txt
Q: Alternative to innerhtml that includes header? I'm trying to extract data from the following page: http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&param2=&param3=&param4=&param5=2009-04-22&param6=37# Which, conveniently and inefficiently enough, includes all the data embedded as a csv...
Alternative to innerhtml that includes header?
I'm trying to extract data from the following page: http://www.bmreports.com/servlet/com.logica.neta.bwp_PanBMDataServlet?param1=&param2=&param3=&param4=&param5=2009-04-22&param6=37# Which, conveniently and inefficiently enough, includes all the data embedded as a csv file in the header, set as a variable called gs_csv...
[ "Untested: Did you try looking at what Document.scripts contains?\nUPDATE:\nFor some reason, I am having immense difficulty getting this to work using the Windows Scripting Host (but then, I don't use it very often, apologies). Anyway, here is the Perl source that works:\nuse strict;\nuse warnings;\n\nuse Win32::OL...
[ 1, 0, 0, 0 ]
[]
[]
[ "com", "css", "dom", "html", "python" ]
stackoverflow_0000906660_com_css_dom_html_python.txt
Q: Python Twisted protocol unregistering? I've came up with problem regarding unregistering protocols from reactor in twisted while application is running. I use hardware modems connected to PC by USB and that's why this scenario is so important for my solution. Has anyone an idea how to do it? Greets, Chris A: Wh...
Python Twisted protocol unregistering?
I've came up with problem regarding unregistering protocols from reactor in twisted while application is running. I use hardware modems connected to PC by USB and that's why this scenario is so important for my solution. Has anyone an idea how to do it? Greets, Chris
[ "When you first call reactor.listen on your protocol factory, it returns an object that implements IListeningPort, see http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.interfaces.IListeningPort.html -- just save that object somewhere and when you want to stop listening on that protocol factori, call th...
[ 6 ]
[]
[]
[ "protocols", "python", "twisted" ]
stackoverflow_0000906496_protocols_python_twisted.txt
Q: Making a Python script executable chmod755? My hosting provider says my python script must be made to be executable(chmod755). What does this mean & how do I do it? Cheers! A: Unix-like systems have "file modes" that say who can read/write/execute a file. The mode 755 means owner can read/write/execute, and eve...
Making a Python script executable chmod755?
My hosting provider says my python script must be made to be executable(chmod755). What does this mean & how do I do it? Cheers!
[ "Unix-like systems have \"file modes\" that say who can read/write/execute a file. The mode 755 means owner can read/write/execute, and everyone else can read/execute but not write. To make your Python script have this mode, you type\nchmod 0755 script.py\n\nYou also need a shebang like\n#!/usr/bin/python\n\non the...
[ 5, 5, 1, 0, 0 ]
[]
[]
[ "hosting", "python" ]
stackoverflow_0000907579_hosting_python.txt
Q: Gather all Python modules used into one folder? I don't think this has been asked before-I have a folder that has lots of different .py files. The script I've made only uses some-but some call others & I don't know all the ones being used. Is there a program that will get everything needed to make that script ru...
Gather all Python modules used into one folder?
I don't think this has been asked before-I have a folder that has lots of different .py files. The script I've made only uses some-but some call others & I don't know all the ones being used. Is there a program that will get everything needed to make that script run into one folder? Cheers!
[ "# zipmod.py - make a zip archive consisting of Python modules and their dependencies as reported by modulefinder\n# To use: cd to the directory containing your Python module tree and type\n# $ python zipmod.py archive.zip mod1.py mod2.py ...\n# Only modules in the current working directory and its subdirectories w...
[ 6, 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000907660_python.txt
Q: python-mysql : How to get interpolated query string? In diagnosing SQL query problems, it would sometimes be useful to be able to see the query string after parameters are interpolated into it, using MySQLdb's safe interpolation. Is there a way to get that information from either a MySQL exception object or from t...
python-mysql : How to get interpolated query string?
In diagnosing SQL query problems, it would sometimes be useful to be able to see the query string after parameters are interpolated into it, using MySQLdb's safe interpolation. Is there a way to get that information from either a MySQL exception object or from the connection object itself?
[ "Use mysql's own ability to log the queries and watch for them.\n", "Perhaps You could use the slow_query_log?\nIf You cannot turn on the mysql's internal ability to log all queries, You need to write down all the queries before You execute them... You can store them in an own log-file, or in a table (or in some ...
[ 2, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0000904042_mysql_python.txt
Q: exec statement with/without prior compile These weekend I've been tearing down to pieces Michele Simionato's decorator module, that builds signature-preserving decorators. At the heart of it all there is a dynamically generated function, which works something similar to this... src = """def function(a,b,c) :\n ...
exec statement with/without prior compile
These weekend I've been tearing down to pieces Michele Simionato's decorator module, that builds signature-preserving decorators. At the heart of it all there is a dynamically generated function, which works something similar to this... src = """def function(a,b,c) :\n return _caller_(a,b,c)\n""" evaldict = {'_calle...
[ "There are a few differences that I see. Firstly, compile has slightly better semantics in the face of syntax errors than exec. I suspect that the real reason is that the definition of compile is very explicit with respect to the handling of new line characters where exec is a little less precise.\nI was curious as...
[ 2, 2 ]
[]
[]
[ "compilation", "eval", "exec", "python" ]
stackoverflow_0000906920_compilation_eval_exec_python.txt
Q: A problem with downloading a file with Python I try to automatically download a file by clicking on a link on the webpage. After clicking on the link, I get the 'File Download' Window dialog with 'Open', 'Save' and 'Cancel' buttons. I would like to click the Save button. I use watsup library in the following way: ...
A problem with downloading a file with Python
I try to automatically download a file by clicking on a link on the webpage. After clicking on the link, I get the 'File Download' Window dialog with 'Open', 'Save' and 'Cancel' buttons. I would like to click the Save button. I use watsup library in the following way: from watsup.winGuiAuto import * optDialog = findTo...
[ "Sasha,\nIt is highly likely that the file dialog you refer to (the Security Warning file download dialog) will NOT respond to windows messages in this manner, for security reasons. The dialog is specifically designed to respond only to a user physically clicking on the OK button with his mouse. I think you will ...
[ 1, 0, 0, 0 ]
[]
[]
[ "download", "file", "python", "user_interface" ]
stackoverflow_0000904555_download_file_python_user_interface.txt
Q: Gather all Python modules used into one folder? Possible Duplicate: Gather all Python modules used into one folder? I don't think this has been asked before-I have a folder that has lots of different .py files. The script I've made only uses some-but some call others & I don't know all the ones being used. Is ...
Gather all Python modules used into one folder?
Possible Duplicate: Gather all Python modules used into one folder? I don't think this has been asked before-I have a folder that has lots of different .py files. The script I've made only uses some-but some call others & I don't know all the ones being used. Is there a program that will get everything needed to m...
[ "Since Python is not statically linked language, this task would be rather a challenging one. Especially if some of your code uses eval(...) or exec(...).\nIf your script is not very big, I would just move it out, make sure that your python.exe does not load modules from that directory and would run the script and ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000907972_python.txt
Q: Using python to develop web application I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development? Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web deve...
Using python to develop web application
I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development? Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web development using python?
[ "Now that everyone has said Django, I can add my two cents: I would argue that you might learn more by looking at the different components first, before using Django. For web development with Python, you often want 3 components:\n\nSomething that takes care\nof the HTTP stuff (e.g.\nCherryPy)\nA templating language...
[ 21, 4, 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000895420_python.txt
Q: Secure plugin system for python application I have an application written in python. I created a plugin system for the application that uses egg files. Egg files contain compiled python files and can be easily decompiled and used to hack the application. Is there a way to secure this system? I'd like to use digita...
Secure plugin system for python application
I have an application written in python. I created a plugin system for the application that uses egg files. Egg files contain compiled python files and can be easily decompiled and used to hack the application. Is there a way to secure this system? I'd like to use digital signature for this - sign these egg files and c...
[ "\nIs there a way to secure this system?\n\nThe answer is \"that depends\".\nThe two questions you should ask is \"what are people supposed to be able to do\" and \"what are people able to do (for a given implementation)\". If there exists an implementation where the latter is a subset of the former, the system ca...
[ 3, 1 ]
[]
[]
[ "plugins", "python", "signing" ]
stackoverflow_0000908285_plugins_python_signing.txt
Q: Regex Substitution in Python I have a CSV file with several entries, and each entry has 2 unix timestamp formatted dates. I have a method called convert(), which takes in the timestamp and converts it to YYYYMMDD. Now, since I have 2 timestamps in each line, how would I replace each one with the new value? EDIT: J...
Regex Substitution in Python
I have a CSV file with several entries, and each entry has 2 unix timestamp formatted dates. I have a method called convert(), which takes in the timestamp and converts it to YYYYMMDD. Now, since I have 2 timestamps in each line, how would I replace each one with the new value? EDIT: Just to clarify, I would like to co...
[ "If you know the replacement:\np = re.compile( r',\\d{8},')\np.sub( ','+someval+',', csvstring )\n\nif it's a format change:\np = re.compile( r',(\\d{4})(\\d\\d)(\\d\\d),')\np.sub( r',\\3-\\2-\\1,', csvstring )\n\nEDIT: sorry, just realised you said python, modified above\n", "I assume that by \"unix timestamp fo...
[ 3, 1, 1, 0 ]
[]
[]
[ "python", "regex", "timestamp" ]
stackoverflow_0000908739_python_regex_timestamp.txt
Q: Windows Authentication with Python and urllib2 I want to grab some data off a webpage that requires my windows username and password. So far, I've got: opener = build_opener() try: page = opener.open("http://somepagewhichneedsmywindowsusernameandpassword/") print page except URLError: print "Oh noes." ...
Windows Authentication with Python and urllib2
I want to grab some data off a webpage that requires my windows username and password. So far, I've got: opener = build_opener() try: page = opener.open("http://somepagewhichneedsmywindowsusernameandpassword/") print page except URLError: print "Oh noes." Is this supported by urllib2? I've found Python NTL...
[ "Assuming you are writing your client code on Windows and need seamless NTLM authentication then you should read Mark Hammond's Hooking in NTLM post from the python-win32 mailing list which essentially answers the same question. This points at the sspi example code included with the Python Win32 extensions (which a...
[ 16 ]
[ "There are several forms of authentication that web sites can use.\n\nHTTP Authentication. This where the browser pops up a window for you to enter your username and password. There are two mechanisms: basic and digest. There is an \"Authorization\" Header that comes along with the page that tells a browser (or...
[ -2 ]
[ "python", "urllib2" ]
stackoverflow_0000909658_python_urllib2.txt
Q: Changing a get request to a post in python? I have this- en.wikipedia.org/w/api.php?action=login&lgname=user&lgpassword=password But it doesn't work because it is a get request. What would the the post request version of this? Cheers! A: The variables for a POST request are in the HTTP headers, not in the URL...
Changing a get request to a post in python?
I have this- en.wikipedia.org/w/api.php?action=login&lgname=user&lgpassword=password But it doesn't work because it is a get request. What would the the post request version of this? Cheers!
[ "The variables for a POST request are in the HTTP headers, not in the URL.\nCheck urllib.\nedit:\nTry this (i got it from here):\nimport urllib\nimport urllib2\n\nurl = 'en.wikipedia.org/w/api.php'\nvalues = {'action' : 'login',\n 'lgname' : 'user',\n 'password' : 'password' }\n\ndata = urllib.url...
[ 3, 2, 0 ]
[]
[]
[ "forms", "get", "post", "python" ]
stackoverflow_0000909929_forms_get_post_python.txt
Q: Reading "raw" Unicode-strings in Python I am quite new to Python so my question might be silly, but even though reading through a lot of threads I didn't find an answer to my question. I have a mixed source document which contains html, xml, latex and other textformats and which I try to get into a latex-only form...
Reading "raw" Unicode-strings in Python
I am quite new to Python so my question might be silly, but even though reading through a lot of threads I didn't find an answer to my question. I have a mixed source document which contains html, xml, latex and other textformats and which I try to get into a latex-only format. Therefore, I have used python to recogni...
[ "You talk of ``raw'' Unicode strings. What does that mean? Unicode itself is not an encoding, but there are different encodings to store Unicode characters (read this post by Joel).\nThe open function in Python 3.0 takes an optional encoding argument that lets you specify the encoding, e.g. UTF-8 (a very common way...
[ 4, 1, 0 ]
[]
[]
[ "python", "readability", "string", "unicode" ]
stackoverflow_0000909886_python_readability_string_unicode.txt
Q: Python MemoryError - how can I force object deletion I have a program that process several files, and for each file a report is generated. The report generating part is a separate function that takes a filename, then returns. During report generation, intermediate parts are cached in memory, as they may be used fo...
Python MemoryError - how can I force object deletion
I have a program that process several files, and for each file a report is generated. The report generating part is a separate function that takes a filename, then returns. During report generation, intermediate parts are cached in memory, as they may be used for several parts of the report, to avoid recalculating. Whe...
[ "You should check out the gc module: http://docs.python.org/library/gc.html#module-gc. \n" ]
[ 3 ]
[]
[]
[ "garbage_collection", "memory", "python", "resources" ]
stackoverflow_0000910153_garbage_collection_memory_python_resources.txt
Q: Problems with python script on web hosting I have written a script for Wikipedia & it works fine on my computer, yet when I upload it to my web host(Dreamhost) it doesn't work & says that the user I am trying to log in as is blocked-this is not true, it works on my computer & I#m not blocked. This is the exact err...
Problems with python script on web hosting
I have written a script for Wikipedia & it works fine on my computer, yet when I upload it to my web host(Dreamhost) it doesn't work & says that the user I am trying to log in as is blocked-this is not true, it works on my computer & I#m not blocked. This is the exact error message I get- A problem occurred in a Python...
[ "It could be that your host (Dreamhost) is blocked, and not your user.\n", "I'd start by adding in some debug. Can you capture the output you're sending to wikipedia and the results it resturns? There's probably some more information lodged in there which you can extract to see why it's failing.\n[Edit] r.e. debu...
[ 1, 0 ]
[]
[]
[ "hosting", "python", "pywikibot" ]
stackoverflow_0000910219_hosting_python_pywikibot.txt
Q: Possible: Program executing Qt3 and Qt4 code? Maybe its a very dumb question but I hope you can give me some answers. I have a commercial application which uses Qt3 for its GUI and an embedded Python interpreter (command line) for scripting. I want to write a custom plugin for this application which uses Qt4. The ...
Possible: Program executing Qt3 and Qt4 code?
Maybe its a very dumb question but I hope you can give me some answers. I have a commercial application which uses Qt3 for its GUI and an embedded Python interpreter (command line) for scripting. I want to write a custom plugin for this application which uses Qt4. The plugin is mainly a subclassed QMainWindow-class tha...
[ "See this thread on a Trolltech forum.\n(Well actually that's about Qt3 plugins in a Qt4 app but I suspect the answer is much the same). \nUpdate: link now a dud, but the wayback machine has it.\n", "This might be possible by namespacing Qt. From configure --help;\n-qtnamespace <name> Wraps all Qt library code i...
[ 3, 3 ]
[]
[]
[ "boost", "c++", "python", "qt", "windows" ]
stackoverflow_0000910230_boost_c++_python_qt_windows.txt
Q: Recommended way to run another program from within a Python script Possible Duplicate: How to call external command in Python I'm writing a Python script on a windows machine. I need to launch another application "OtherApp.exe". What is the most suitable way to do so? Till now I've been looking at os.system() o...
Recommended way to run another program from within a Python script
Possible Duplicate: How to call external command in Python I'm writing a Python script on a windows machine. I need to launch another application "OtherApp.exe". What is the most suitable way to do so? Till now I've been looking at os.system() or os.execl() and they don't quite look appropriate (I don't even know i...
[ "The recommended way is to use the subprocess module. All other ways (like os.system() or exec) are brittle, unsecure and have subtle side effects that you should not need to care about. subprocess replaces all of them.\n" ]
[ 5 ]
[ "Note that this answer is specific to python versions 2.x which I am locked to due to an embedded system. I am only leaving it for historical reasons just in case. \nOne of the things the subprocess offers is a method to catch the output of a command, for example using [popen] on a windows machine\nimport os\nos.p...
[ -1 ]
[ "python", "windows" ]
stackoverflow_0000910733_python_windows.txt
Q: Factory for Callback methods - Python TKinter Writing a test app to emulate PIO lines, I have a very simple Python/Tk GUI app. Using the numeric Keys 1 to 8 to simulate PIO pins 1 to 8. Press the key down = PIO High, release the Key = PIO goes low. What I need it for is not the problem. I kind of went down a rabbi...
Factory for Callback methods - Python TKinter
Writing a test app to emulate PIO lines, I have a very simple Python/Tk GUI app. Using the numeric Keys 1 to 8 to simulate PIO pins 1 to 8. Press the key down = PIO High, release the Key = PIO goes low. What I need it for is not the problem. I kind of went down a rabbit hole trying to use a factory to create the key pr...
[ "cb expects 'self' and 'event'. Maybe it only gets event from the bind?\n", "In answer to your followup question.\nI'm not sure which part you don't understand but I'm guessing you don't quite have a handle on how event callbacks work? If so it's pretty easy. Tk runs in a loop looking for events (keypresses, mous...
[ 1, 1, 0 ]
[]
[]
[ "factory", "methods", "python" ]
stackoverflow_0000909551_factory_methods_python.txt
Q: How to show characters non ascii in python? I'm using the Python Shell in this way: >>> s = 'Ã' >>> s '\xc3' How can I print s variable to show the character Ã??? This is the first and easiest question. Really, I'm getting the content from a web page that has non ascii characters like the previous and others with...
How to show characters non ascii in python?
I'm using the Python Shell in this way: >>> s = 'Ã' >>> s '\xc3' How can I print s variable to show the character Ã??? This is the first and easiest question. Really, I'm getting the content from a web page that has non ascii characters like the previous and others with tilde like á, é, í, ñ, etc. Also, I'm trying to ...
[ "How can I print s variable to show the character Ã???\nuse print:\n>>> s = 'Ã'\n>>> s\n'\\xc3'\n>>> print s\nÃ\n\n", "Suppose you want to print it as utf-8. Before python 3, the best is to specifically encode it\nprint u'Ã'.encode('utf-8')\n\nif you get the text externally then you have to specifically decode('u...
[ 2, 2, 1 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0000910809_python_urllib2.txt
Q: Python and Qt (PyQt) - calling method before resize event i have a question. There is application class in my program. It is inherited from QtGui.QMainWindow. In ini I call my own method which works with graphic. And it should be called before resize event. How can i do that? Thanks. EDIT: As you can se here the v...
Python and Qt (PyQt) - calling method before resize event
i have a question. There is application class in my program. It is inherited from QtGui.QMainWindow. In ini I call my own method which works with graphic. And it should be called before resize event. How can i do that? Thanks. EDIT: As you can se here the value of resize event is 14, and show event is 17. So i should f...
[ "You could override in your class the resizeEvent method (which QMainWindows inherits from QWidget), see http://doc.trolltech.com/4.4/qwidget.html#resizeEvent -- in your override, call your other code, then delegate the rest of the work to the parent's version of the method.\n" ]
[ 1 ]
[]
[]
[ "constructor", "pyqt", "python" ]
stackoverflow_0000911167_constructor_pyqt_python.txt
Q: Python: Inheriting from Built-In Types I have a question concerning subtypes of built-in types and their constructors. I want a class to inherit both from tuple and from a custom class. Let me give you the concrete example. I work a lot with graphs, meaning nodes connected with edges. I am starting to do some work...
Python: Inheriting from Built-In Types
I have a question concerning subtypes of built-in types and their constructors. I want a class to inherit both from tuple and from a custom class. Let me give you the concrete example. I work a lot with graphs, meaning nodes connected with edges. I am starting to do some work on my own graph framework. There is a class...
[ "Since tuples are immutable, you need to override the __new__ method as well. See http://www.python.org/download/releases/2.2.3/descrintro/#__new__\nclass GraphElement:\n def __init__(self, graph):\n pass\n\nclass Edge(GraphElement, tuple):\n def __new__(cls, graph, (source, target)):\n return t...
[ 10, 6, 3 ]
[]
[]
[ "graph", "oop", "python" ]
stackoverflow_0000911375_graph_oop_python.txt
Q: Python MS Word Possible Duplicate: Reading/Writing MS Word files in Python I'm looking into a requirements management system (like requiste pro - Rational Rose) - and will need to read through a MS Word doc searching for specific tags - on either a windows or Apple OS environment. Are there any known frameworks...
Python MS Word
Possible Duplicate: Reading/Writing MS Word files in Python I'm looking into a requirements management system (like requiste pro - Rational Rose) - and will need to read through a MS Word doc searching for specific tags - on either a windows or Apple OS environment. Are there any known frameworks for this (I couldn...
[ "First, get it out of native Word (.doc) format.\n\nDo a \"Save As XML\" and insist your users work with that file instead of the .doc file. They'll hardly notice the difference -- except that the file is bigger.\nUse lxml or element tree to parse the XML and find the headings, sections, paragraphs and lists.\n\nY...
[ 4, 2, 2, 2, 0, 0 ]
[]
[]
[ "ms_word", "python" ]
stackoverflow_0000910730_ms_word_python.txt
Q: Django/Python UserWarning Error I keep getting this error/warning, which is annoying, and wanted to see if I can fix it, but I'm not sure where to start (I'm a newbie): /home/simi/workspace/hssn_svn/hssn/../hssn/log/loggers.py:28: UserWarning: ERROR: Could not configure logging warnings.warn('ERROR: Could not co...
Django/Python UserWarning Error
I keep getting this error/warning, which is annoying, and wanted to see if I can fix it, but I'm not sure where to start (I'm a newbie): /home/simi/workspace/hssn_svn/hssn/../hssn/log/loggers.py:28: UserWarning: ERROR: Could not configure logging warnings.warn('ERROR: Could not configure logging', UserWarning) I'm g...
[ "Do you have write permissions to all the files within the application you are working with. Also make sure you have everything in settings.py setup correctly, make sure specified paths exist and you have permissions.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000911273_django_python.txt
Q: Storing information on points in a 3d space I'm writing some code (just for fun so far) in Python that will store some data on every point in a 3d space. I'm basically after a 3d matrix object that stores arbitary objects that will allow me to do some advanced selections, like: Get the point where x=1,y=2,z=3. Ge...
Storing information on points in a 3d space
I'm writing some code (just for fun so far) in Python that will store some data on every point in a 3d space. I'm basically after a 3d matrix object that stores arbitary objects that will allow me to do some advanced selections, like: Get the point where x=1,y=2,z=3. Getting all points where y=2. Getting all points wi...
[ "Here's another common approach\nclass Point( object ):\n def __init__( self, x, y, z, data ):\n self.x, self.y, self.z = x, y, z\n self.data = data\n def distFrom( self, x, y, z )\n return math.sqrt( (self.x-x)**2 + (self.y-y)**2 + (self.z-z)**2 )\n\ndatabase = [ Point(x,y,z,data), Point...
[ 6, 3, 1, 0, 0, 0, 0 ]
[ "It depends upon the precise configuration of your system, but from the example you give you are using integers and discrete points, so it would probably be appropriate to consider Sparse Matrix data structures. \n" ]
[ -1 ]
[ "3d", "data_structures", "matrix", "numpy", "python" ]
stackoverflow_0000910930_3d_data_structures_matrix_numpy_python.txt
Q: Django -- how to use templatetags filter with multiple arguments I have a few values that I would like to pass into a filter and get a URL out of it. In my template I have: {% if names %} {% for name in names %} <a href='{{name|slugify|add_args:"custid=name.id, sortid=2"}}'>{{name}}</a> {%if not forloop....
Django -- how to use templatetags filter with multiple arguments
I have a few values that I would like to pass into a filter and get a URL out of it. In my template I have: {% if names %} {% for name in names %} <a href='{{name|slugify|add_args:"custid=name.id, sortid=2"}}'>{{name}}</a> {%if not forloop.last %} | {% endif %} {% endfor %} {% endif %} In my templatetags I...
[ "This \"smart\" stuff logic should not be in the template.\nBuild your end-of-urls in your view and then pass them to template:\ndef the_view(request):\n url_stuff = \"custid=%s, sortid, ....\" % (name.id, 2 ...)\n\n return render_to_response('template.html',\n {'url_stuff':url_stuff,},\n context_instance =...
[ 6, 4, 3 ]
[]
[]
[ "django", "django_templates", "filter", "python", "tags" ]
stackoverflow_0000896166_django_django_templates_filter_python_tags.txt
Q: Django objects change model field This doesn't work: >>> pa = Person.objects.all() >>> pa[2].nickname u'arst' >>> pa[2].nickname = 'something else' >>> pa[2].save() >>> pa[2].nickname u'arst' But it works if you take p = Person.objects.get(pk=2) and change the nick. Why so. A: >>> type(Person.objects.all...
Django objects change model field
This doesn't work: >>> pa = Person.objects.all() >>> pa[2].nickname u'arst' >>> pa[2].nickname = 'something else' >>> pa[2].save() >>> pa[2].nickname u'arst' But it works if you take p = Person.objects.get(pk=2) and change the nick. Why so.
[ ">>> type(Person.objects.all())\n<class 'django.db.models.query.QuerySet'>\n\n>>> pa = Person.objects.all() # Not evaluated yet - lazy\n>>> type(pa)\n<class 'django.db.models.query.QuerySet'>\n\nDB queried to give you a Person object\n>>> pa[2]\n\nDB queried again to give you yet another Person object. \n>>> pa[2]....
[ 10, 4, 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000910287_django_django_models_python.txt