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: How can I extract x, y and z coordinates from geographical data by Python? I have geographical data which has 14 variables. The data is in the following format: QUADNAME: rockport_colony_SD RESOLUTION: 10 ULLAT: 43.625 ULLON: -97.87527466 LRLAT: 43.5 LRLON: -97.75027466 HDATUM: 27 ZMIN: ...
How can I extract x, y and z coordinates from geographical data by Python?
I have geographical data which has 14 variables. The data is in the following format: QUADNAME: rockport_colony_SD RESOLUTION: 10 ULLAT: 43.625 ULLON: -97.87527466 LRLAT: 43.5 LRLON: -97.75027466 HDATUM: 27 ZMIN: 361.58401489 ZMAX: 413.38400269 ZMEAN: 396.1293335 ZSIGMA: 12.3...
[ "Something like this might work if the data is all in a big flat text file:\nimport re\n\ndata = \"\"\"\nQUADNAME: rockport_colony_SD RESOLUTION: 10 ULLAT: 43.625\nULLON: -97.87527466 LRLAT: 43.5\nLRLON: -97.75027466 HDATUM: 27\nZMIN: 361.58401489 ZMAX: 413.38400269 ZMEAN: 396.1293335 ZSIGMA: 12.36359215 PMETHOD: 5...
[ 4, 2 ]
[]
[]
[ "extraction", "geography", "python" ]
stackoverflow_0000489901_extraction_geography_python.txt
Q: Given an rpm package name, query the yum database for updates I was imagining a 3-line Python script to do this but the yum Python API is impenetrable. Is this even possible? Is writing a wrapper for 'yum list package-name' the only way to do this? A: http://fpaste.org/paste/2453 and there are many examples of ...
Given an rpm package name, query the yum database for updates
I was imagining a 3-line Python script to do this but the yum Python API is impenetrable. Is this even possible? Is writing a wrapper for 'yum list package-name' the only way to do this?
[ "http://fpaste.org/paste/2453\nand there are many examples of the yum api and some guides to getting started with it here:\nhttp://yum.baseurl.org/#DeveloperDocumentationExamples\n", "As Seth points out, you can use the updates APIs to ask if something is available as an update. For something that's close to what...
[ 7, 4 ]
[]
[]
[ "python", "rpm", "yum" ]
stackoverflow_0000489113_python_rpm_yum.txt
Q: What is the most pythonic way to make a bound method act like a function? I'm using a Python API that expects me to pass it a function. However, for various reasons, I want to pass it a method, because I want the function to behave different depending on the instance it belongs to. If I pass it a method, the API ...
What is the most pythonic way to make a bound method act like a function?
I'm using a Python API that expects me to pass it a function. However, for various reasons, I want to pass it a method, because I want the function to behave different depending on the instance it belongs to. If I pass it a method, the API will not call it with the correct 'self' argument, so I'm wondering how to turn...
[ "Will passing in the method bound to a instance work? If so, you don't have to do anything special.\nIn [2]: class C(object):\n ...: def method(self, a, b, c):\n ...: print a, b, c\n ...:\n ...:\n\nIn [3]: def api_function(a_func):\n ...: a_func(\"One Fish\", \"Two Fish\", \"Blue Fish\")\n...
[ 9, 0 ]
[]
[]
[ "closures", "function", "methods", "python" ]
stackoverflow_0000490429_closures_function_methods_python.txt
Q: How can I pass a filename as a parameter into my module? I have the following code in .py file: import re regex = re.compile( r"""ULLAT:\ (?P<ullat>-?[\d.]+).*? ULLON:\ (?P<ullon>-?[\d.]+).*? LRLAT:\ (?P<lrlat>-?[\d.]+)""", re.DOTALL|re.VERBOSE) I have the data in .txt file as a sequence: QUADNAME: r...
How can I pass a filename as a parameter into my module?
I have the following code in .py file: import re regex = re.compile( r"""ULLAT:\ (?P<ullat>-?[\d.]+).*? ULLON:\ (?P<ullon>-?[\d.]+).*? LRLAT:\ (?P<lrlat>-?[\d.]+)""", re.DOTALL|re.VERBOSE) I have the data in .txt file as a sequence: QUADNAME: rockport_colony_SD RESOLUTION: 10 ULLAT: 43.625 ULLON: -97.8752...
[ "You need to read the file in and then search the contents using the regular expression. The sys module contains a list, argv, which contains all the command line parameters. We pull out the second one (the first is the file name used to run the script), open the file, and then read in the contents.\n\nimport re\ni...
[ 22 ]
[]
[]
[ "command_line", "module", "parameters", "python" ]
stackoverflow_0000491085_command_line_module_parameters_python.txt
Q: MS Outlook CDO/MAPI Blocking Python File Output? Here is an example of the problem I am running into. I am using the Python Win32 extensions to access an Outlook mailbox and retrieve messages. Below is a script that should write "hello world" to a text file. I need to grab some messages from an Outlook mailbox a...
MS Outlook CDO/MAPI Blocking Python File Output?
Here is an example of the problem I am running into. I am using the Python Win32 extensions to access an Outlook mailbox and retrieve messages. Below is a script that should write "hello world" to a text file. I need to grab some messages from an Outlook mailbox and I noticed something weird. After I attach to the m...
[ "answering my own question. it looks like your working directory gets changed when you read the email. If you set it back, your file i/o works fine.\nthe correct script would look like this:\n#!/usr/bin/env python\n\nimport os\nfrom win32com.client import Dispatch\n\nfh = open('foo.txt', 'w')\nfh.write('hello ')\...
[ 1, 1 ]
[]
[]
[ "mapi", "outlook", "python", "winapi" ]
stackoverflow_0000488504_mapi_outlook_python_winapi.txt
Q: regex: Matching parts of a string when the string contains part of a regex pattern I want to reduce the number of patterns I have to write by using a regex that picks up any or all of the pattern when it appears in a string. Is this possible with Regex? E.g. Pattern is: "the cat sat on the mat" I would like patte...
regex: Matching parts of a string when the string contains part of a regex pattern
I want to reduce the number of patterns I have to write by using a regex that picks up any or all of the pattern when it appears in a string. Is this possible with Regex? E.g. Pattern is: "the cat sat on the mat" I would like pattern to match on following strings: "the" "the cat" "the cat sat" ... "the cat sat on the ...
[ "This:\nthe( cat( sat( on( the( mat)?)?)?)?)?\n\nwould answer your question. Remove \"optional group\" parens \"(...)?\" for parts that are not optional, add additional groups for things that must match together.\nthe // complete match\nthe cat // complete match\nthe cat sat ...
[ 7, 2, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000490762_python_regex.txt
Q: Python: Problem with local modules shadowing global modules I've got a package set up like so: packagename/ __init__.py numbers.py tools.py ...other stuff Now inside tools.py, I'm trying to import the standard library module fractions. However, the fractions module itself imports the numbers modul...
Python: Problem with local modules shadowing global modules
I've got a package set up like so: packagename/ __init__.py numbers.py tools.py ...other stuff Now inside tools.py, I'm trying to import the standard library module fractions. However, the fractions module itself imports the numbers module, which is supposed to be the one in the standard library. The p...
[ "absolute and relative imports can be used since python2.5 (with __future__ import) and seem to be what you're looking for.\n", "I try to avoid shadowing the standard library. How about renaming your module to \"_numbers.py\" ?\nAnd of course, you could still do:\nimport _numbers as numbers\n\n" ]
[ 9, 7 ]
[]
[]
[ "python" ]
stackoverflow_0000491705_python.txt
Q: Emacs 23 and iPython Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend? A: I got it working qui...
Emacs 23 and iPython
Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?
[ "I got it working quite well with emacs 23. The only open issue is the focus not returning to the python buffer after sending the buffer to the iPython interpreter.\nhttp://www.emacswiki.org/emacs/PythonMode#toc10\n(setq load-path\n (append (list nil\n \"~/.emacs.d/python-mode-1.0/\"\n ...
[ 8, 2, 0 ]
[]
[]
[ "emacs", "emacs23", "ipython", "python" ]
stackoverflow_0000304049_emacs_emacs23_ipython_python.txt
Q: How do I make IPython organize tab completion possibilities by class? When an object has hundreds of methods, tab completion is hard to use. More often than not the interesting methods are the ones defined or overridden by the inspected object's class and not its base classes. How can I get IPython to group its ta...
How do I make IPython organize tab completion possibilities by class?
When an object has hundreds of methods, tab completion is hard to use. More often than not the interesting methods are the ones defined or overridden by the inspected object's class and not its base classes. How can I get IPython to group its tab completion possibilities so the methods and properties defined in the ins...
[ "Since I am not using Python 2.6 or 3.0 yet and don't have readline.set_completion_display_matches_hook(), I can use ctypes to set completion_display_func like so:\nfrom ctypes import *\n\nrl = cdll.LoadLibrary('libreadline.so')\n\ndef completion_display_func(matches, num_matches, max_length):\n print \"Hello fr...
[ 5, 1, 1 ]
[]
[]
[ "ipython", "python", "readline" ]
stackoverflow_0000465605_ipython_python_readline.txt
Q: Using Python split to splice a variable together I have this list ["camilla_farnestam@hotmail.com : martin00", ""], How do I split so it only be left with: camilla_farnestam@hotmail.com:martin00 A: Do you want to have: aList[0] ? EDIT:: Oh, you have a tuple with the list in it! Now I see: al = ["camilla_farn...
Using Python split to splice a variable together
I have this list ["camilla_farnestam@hotmail.com : martin00", ""], How do I split so it only be left with: camilla_farnestam@hotmail.com:martin00
[ "Do you want to have: aList[0] ? \nEDIT::\nOh, you have a tuple with the list in it!\nNow I see:\nal = [\"camilla_farnestam@hotmail.com : martin00\", \"\"],\n#type(al) == tuple\n#len(al) == 1\naList = al[0]\n#type(aList) == list\n#len(aList) == 2\n#Now you can type:\naList[0]\n#and you get:\n\"camilla_farnestam@ho...
[ 3, 3, 2, 1, 0, 0 ]
[]
[]
[ "python", "split" ]
stackoverflow_0000492452_python_split.txt
Q: How do I use ctypes to set a library's extern function pointer to a Python callback function? Some C libraries export function pointers such that the user of the library sets that function pointer to the address of their own function to implement a hook or callback. In this example library liblibrary.so, how do I ...
How do I use ctypes to set a library's extern function pointer to a Python callback function?
Some C libraries export function pointers such that the user of the library sets that function pointer to the address of their own function to implement a hook or callback. In this example library liblibrary.so, how do I set library_hook to a Python function using ctypes? library.h: typedef int exported_function_t(char...
[ "This is tricky in ctypes because ctypes function pointers do not implement the .value property used to set other pointers. Instead, cast your callback function and the extern function pointer to void * with the c_void_p function. After setting the function pointer as void * as shown, C can call your Python functio...
[ 9 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0000492377_ctypes_python.txt
Q: One-to-many relationship in Datastore and de-referencing in Google App Engine I have a one to many relationship between two entities: the first one is a satellite and the second one is channel. The satellite form returns a satellite name which I want to appear in another HTML page, with the channel data where you ...
One-to-many relationship in Datastore and de-referencing in Google App Engine
I have a one to many relationship between two entities: the first one is a satellite and the second one is channel. The satellite form returns a satellite name which I want to appear in another HTML page, with the channel data where you can say that this channel is related to that satellite. How can I do this?
[ "This sounds like a good case for using the ReferenceProperty that is part of the Datastore API of App Engine. Here's an idea to get you started:\nclass Satellite(db.Model):\n name = db.StringProperty()\n\nclass Channel(db.Model):\n satellite = db.ReferenceProperty(Satellite, collection_name='channels')\n freq ...
[ 6 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000488498_google_app_engine_python.txt
Q: In Django, how do you retrieve data from extra fields on many-to-many relationships without an explicit query for it? Given a situation in Django 1.0 where you have extra data on a Many-to-Many relationship: class Player(models.Model): name = models.CharField(max_length=80) class Team(models.Model): name = mo...
In Django, how do you retrieve data from extra fields on many-to-many relationships without an explicit query for it?
Given a situation in Django 1.0 where you have extra data on a Many-to-Many relationship: class Player(models.Model): name = models.CharField(max_length=80) class Team(models.Model): name = models.CharField(max_length=40) players = models.ManyToManyField(Player, through='TeamPlayer', related_name='teams') class...
[ "So, 15 minutes after asking the question, and I found my own answer. \nUsing dir(Team), I can see another generated attribute named teamplayer_set (it also exists on Player). \nt = Team.objects.get(pk=168)\nfor x in t.teamplayer_set.all():\n if x.captain:\n print \"%s (Captain)\" % (x.player.name)\n else:\n ...
[ 10 ]
[]
[]
[ "django", "manytomanyfield", "python" ]
stackoverflow_0000493304_django_manytomanyfield_python.txt
Q: Adding a SOAP header to a SOAPpy request Does anyone know how to do this? I need to add a header of the form: value1 value2 A: As the question is phrased, it's hard to guess what the intention (or even the intended semantics) is. For setting headers, try the following: import SOAPpy headers = SOAP...
Adding a SOAP header to a SOAPpy request
Does anyone know how to do this? I need to add a header of the form: value1 value2
[ "As the question is phrased, it's hard to guess what the intention (or even the intended semantics) is. For setting headers, try the following:\nimport SOAPpy\nheaders = SOAPpy.Types.headerType()\nheaders.value1 = value2\n\nor\n[...]\nheaders.foo = value1\nheaders.bar = value2\n\n" ]
[ 4 ]
[]
[]
[ "python", "soappy" ]
stackoverflow_0000354370_python_soappy.txt
Q: Is a PHP, Python, PostgreSQL design suitable for a business application? I'm looking for some quick thoughts about a business application I am looking to build. I'd like to separate the three layers of presentation, domain logic, and data using PHP, Python, and PostgreSQL, respectively. I would like to hear, poss...
Is a PHP, Python, PostgreSQL design suitable for a business application?
I'm looking for some quick thoughts about a business application I am looking to build. I'd like to separate the three layers of presentation, domain logic, and data using PHP, Python, and PostgreSQL, respectively. I would like to hear, possibly from other folks who have gone down this path before, if there are proble...
[ "Look at Django.\nPython code. A template language that permits some of the same features as PHP -- slightly different syntax.\nModel is divorced from view functions (\"business rules\") and divorced from presentation. This is enforced throughout Django. \nOne of the common questions is \"why can't I do -- some ...
[ 11, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "php", "postgresql", "python" ]
stackoverflow_0000439759_php_postgresql_python.txt
Q: Form (or Formset?) to handle multiple table rows in Django I'm working on my first Django application. In short, what it needs to do is to display a list of film titles, and allow users to give a rating (out of 10) to each film. I've been able to use the {{ form }} and {{ formset }} syntax in a template to produce...
Form (or Formset?) to handle multiple table rows in Django
I'm working on my first Django application. In short, what it needs to do is to display a list of film titles, and allow users to give a rating (out of 10) to each film. I've been able to use the {{ form }} and {{ formset }} syntax in a template to produce a form which lets you rate one film at a time, which correspond...
[ "\"At first, I thought this was what formsets were for, but I can't see any way to automatically iterate over the contents of a database table to produce items to go in the form, if you see what I mean.\"\nYou need to get a queryset. And you need to provide that queryset to your form as initial data. See using in...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000298779_django_python.txt
Q: File and space in Python I have a file like: <space> <space> line1 <space> column 1 column 2 column 3 ... . . . <space> <space> How to remove this extra spaces? I need to extract the heading which will be on line1. Also, I need to extract column 1, column 2, column 3 etc. At the end of last column conte...
File and space in Python
I have a file like: <space> <space> line1 <space> column 1 column 2 column 3 ... . . . <space> <space> How to remove this extra spaces? I need to extract the heading which will be on line1. Also, I need to extract column 1, column 2, column 3 etc. At the end of last column content there is '\n'.How to get r...
[ "Start by opening the file and reading all the lines:\nf = open('filename string');\nlines = f.readlines()\n\nThen...\n# remove empty lines\nlines = [l for l in lines if len(l.strip()) > 0]\nheader = lines[0]\nline = lines[1].split(' ')\ncolumn1 = line[0]\ncolumn2 = line[1]\n...\n\nAlso:\ntotal_lines = len(lines)\n...
[ 4, 1, 0 ]
[]
[]
[ "file", "parsing", "python", "spaces" ]
stackoverflow_0000494919_file_parsing_python_spaces.txt
Q: Which Python module is suitable for data manipulation in a list? I have a sequence of x, y and z -coordinates, which I need to manipulate. They are in one list of three tuples, like {(x1, y1, z1), (x2, y2, z2), ...}. I need addition, multiplication and logarithm to manipulate my data. I would like to study a modul...
Which Python module is suitable for data manipulation in a list?
I have a sequence of x, y and z -coordinates, which I need to manipulate. They are in one list of three tuples, like {(x1, y1, z1), (x2, y2, z2), ...}. I need addition, multiplication and logarithm to manipulate my data. I would like to study a module, which is as powerful as Awk -language.
[ "I'm not sure exactly what you're after. You can do a lot with list comprehensions. For example, if you want to turn a list:\ncoords = [(x1, y1, z1), (x2, y2, z2), (x3, y3, z3)] # etc\n\ninto a tuple (x1+x2+x3, y1+y2+y3, z1+z2+z3), then you can do:\nsums = (sum(a[0] for a in coords), sum(a[1] for a in coords), s...
[ 8, 7, 2, 1 ]
[]
[]
[ "module", "python" ]
stackoverflow_0000493853_module_python.txt
Q: refactor this dictionary-to-xml converter in python It's a small thing, really: I have this function that converts dict objects to xml. Here's the function: def dictToXml(d): from xml.sax.saxutils import escape def unicodify(o): if o is None: return u''; return unicode(o) ...
refactor this dictionary-to-xml converter in python
It's a small thing, really: I have this function that converts dict objects to xml. Here's the function: def dictToXml(d): from xml.sax.saxutils import escape def unicodify(o): if o is None: return u''; return unicode(o) lines = [] def addDict(node, offset): for nam...
[ ">>> from pyfo import pyfo\n>>> d = ('site', { 'name': 'stackoverflow', 'blogger': [ 'Jeff', 'Joel' ] } )\n>>> result = pyfo(d, pretty=True, prolog=True, encoding='ascii')\n>>> print result.encode('ascii', 'xmlcharrefreplace')\n<?xml version=\"1.0\" encoding=\"ascii\"?>\n<site>\n <blogger>\n Jeff\n Joel\n <...
[ 9, 4, 1, 1, 0, 0 ]
[]
[]
[ "dry", "python", "xml" ]
stackoverflow_0000494881_dry_python_xml.txt
Q: Confusion about global variables in python I'm new to python, so please excuse what is probably a pretty dumb question. Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different ...
Confusion about global variables in python
I'm new to python, so please excuse what is probably a pretty dumb question. Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses it. I have ...
[ "There are more problems than just the leading underscore I'm afraid.\nWhen you call my_function(), it still won't have your debug variable in its namespace, unless you import it from two.py.\nOf course, doing that means you'll end up with cyclic dependencies (one.py -> two.py -> one.py), and you'll get NameErrors ...
[ 16, 5, 4, 1 ]
[]
[]
[ "global_variables", "python", "python_import" ]
stackoverflow_0000495422_global_variables_python_python_import.txt
Q: python setup.py develop not updating easy_install.pth According to setuptools documentation, setup.py develop is supposed to create the egg-link file and update easy_install.pth when installing into site-packages folder. However, in my case it's only creating the egg-link file. How does setuptools decide if it n...
python setup.py develop not updating easy_install.pth
According to setuptools documentation, setup.py develop is supposed to create the egg-link file and update easy_install.pth when installing into site-packages folder. However, in my case it's only creating the egg-link file. How does setuptools decide if it needs to update easy_install.pth? Some more info: It works w...
[ "Reinstall setuptools with the command easy_install --always-unzip --upgrade setuptools. If that fixes it then the zipping was the problem.\n", "I'd try to debug it with pdb. The issue is most likely with the easy install's method check_site_dir, which seeks for easy-install.pth. \n" ]
[ 4, 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0000421050_python_setuptools.txt
Q: How to send clip names using LiveAPI (of Ableton Live) When an audio or midi clip is played (triggered), its name needs to be sent using OSC to another application. LiveAPI is an interface which allows one to explore and automate Ableton Live using python scripts. The code to do this must be written in a python sc...
How to send clip names using LiveAPI (of Ableton Live)
When an audio or midi clip is played (triggered), its name needs to be sent using OSC to another application. LiveAPI is an interface which allows one to explore and automate Ableton Live using python scripts. The code to do this must be written in a python script, which must be placed in a specific folder where Ableto...
[ "According to the LiveAPI documentation, the Clip object has a \"name\" attribute which holds the clip name. Presumably that's what you want to send in your OSC packets.\nAlso, it's worth mentioning that the Max/MSP support in Live8 will probably be a lot more comfortable to work with than LiveAPI, which is pretty...
[ 2, 0 ]
[]
[]
[ "ableton_live", "api", "osc", "python" ]
stackoverflow_0000375052_ableton_live_api_osc_python.txt
Q: StaticText items disappear in wx.StaticBox I'm creating a staticbox and a staticboxsizer in a vertical sizer. Everything works fine for me, but not on the customer's environment. Everything in the staticbox is displayed, but labels. snippet below shows how i construct the staticboxsizer. sbox2 = wx.StaticBox...
StaticText items disappear in wx.StaticBox
I'm creating a staticbox and a staticboxsizer in a vertical sizer. Everything works fine for me, but not on the customer's environment. Everything in the staticbox is displayed, but labels. snippet below shows how i construct the staticboxsizer. sbox2 = wx.StaticBox(self, wx.ID_ANY, 'CH1 Only') sboxsizer2 = w...
[ "The source code of wxStaticBox does different things in painting code, depending on whether XP themes are enabled. In the screen shot without themes everything looks OK, in the one with themes enabled the labels are missing. Could you try on your system with themes enabled, and see whether labels display OK? Or ca...
[ 1, 1 ]
[]
[]
[ "boxsizer", "python", "wxpython", "wxwidgets" ]
stackoverflow_0000484389_boxsizer_python_wxpython_wxwidgets.txt
Q: How can I disable quoting in the Python 2.4 CSV reader? I am writing a Python utility that needs to parse a large, regularly-updated CSV file I don't control. The utility must run on a server with only Python 2.4 available. The CSV file does not quote field values at all, but the Python 2.4 version of the csv li...
How can I disable quoting in the Python 2.4 CSV reader?
I am writing a Python utility that needs to parse a large, regularly-updated CSV file I don't control. The utility must run on a server with only Python 2.4 available. The CSV file does not quote field values at all, but the Python 2.4 version of the csv library does not seem to give me any way to turn off quoting, i...
[ "I don't know if python would like/allow it but could you use a non-printable ascii code such as BEL or BS (backspace) These I would think to be extremely rare.\n", "I tried a few examples using Python 2.4.3, and it seemed to be smart enough to detect that the fields were unquoted. \nI know you've already accept...
[ 13, 3, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0000494054_csv_python.txt
Q: Would Python make a good substitute for the Windows command-line/batch scripts? I've got some experience with Bash, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using the Windows command-line language. For some reason said language reall...
Would Python make a good substitute for the Windows command-line/batch scripts?
I've got some experience with Bash, which I don't mind, but now that I'm doing a lot of Windows development I'm needing to do basic stuff/write basic scripts using the Windows command-line language. For some reason said language really irritates me, so I was considering learning Python and using that instead. Is Pytho...
[ "Python is well suited for these tasks, and I would guess much easier to develop in and debug than Windows batch files.\nThe question is, I think, how easy and painless it is to ensure that all the computers that you have to run these scripts on, have Python installed.\n", "Summary\nWindows: no need to think, use...
[ 25, 15, 9, 5, 5, 5, 3, 2, 1, 1, 0 ]
[ "As much as I love python, I don't think it a good choice to replace basic windows batch scripts. \nI can't see see someone having to import modules like sys, os or getopt to do basic things you can do with shell like call a program, check environment variable or an argument.\nAlso, in my experience, goto is much e...
[ -2 ]
[ "command_line", "python", "scripting" ]
stackoverflow_0000213798_command_line_python_scripting.txt
Q: Python's os.path choking on Hebrew filenames I'm writing a script that has to move some file around, but unfortunately it doesn't seem os.path plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory: (source: thegreenplac...
Python's os.path choking on Hebrew filenames
I'm writing a script that has to move some file around, but unfortunately it doesn't seem os.path plays with internationalization very well. When I have files named in Hebrew, there are problems. Here's a screenshot of the contents of a directory: (source: thegreenplace.net) Now consider this code that goes over the ...
[ "Hmm, after some digging it appears that when supplying os.listdir a unicode string, this kinda works:\nfiles = os.listdir(u'test_source')\n\nfor f in files:\n\n pf = os.path.join(u'test_source', f)\n print pf.encode('ascii', 'replace'), os.path.exists(pf)\n\n===>\ntest_source\\ex True\ntest_source\\joe True\...
[ 17, 3, 1, 0 ]
[]
[]
[ "hebrew", "internationalization", "python" ]
stackoverflow_0000497233_hebrew_internationalization_python.txt
Q: Get rid of '\n' in Python How to get rid of '\n' at the end of a line ? A: "string \n".strip(); or "string \n".rstrip(); A: If, as Rolf suggests in his comment, you want to print text without having a newline automatically appended, use print "foo", Note the trailing comma. A: Get rid of just the "\n" at t...
Get rid of '\n' in Python
How to get rid of '\n' at the end of a line ?
[ "\"string \\n\".strip();\n\nor\n\"string \\n\".rstrip();\n\n", "If, as Rolf suggests in his comment, you want to print text without having a newline automatically appended, use\nprint \"foo\",\n\nNote the trailing comma.\n", "Get rid of just the \"\\n\" at the end of the line:\n>>> \"string \\n\".rstrip(\"\\n\"...
[ 25, 18, 7, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000495424_python.txt
Q: Outputting to a text file How to print the following code to a .txt file y = '10.1.1.' # /24 network, for x in range(255): x += 1 print y + str(x) # not happy that it's in string, but how to print it into a.txt There's copy paste, but would rather try something more interesting. A: f = open('myfile.tx...
Outputting to a text file
How to print the following code to a .txt file y = '10.1.1.' # /24 network, for x in range(255): x += 1 print y + str(x) # not happy that it's in string, but how to print it into a.txt There's copy paste, but would rather try something more interesting.
[ "f = open('myfile.txt', 'w')\nfor x in range(255):\n ip = \"10.1.1.%s\\n\" % str(x)\n f.write(ip)\nf.close()\n\n", "scriptname.py >> output.txt\n", "What is the x += 1 for? It seems to be a workaround for range(255) being 0 based - which gives the sequence 0,1,2...254.\nrange(1,256) will better give you w...
[ 6, 3, 1, 0 ]
[]
[]
[ "python", "text" ]
stackoverflow_0000493816_python_text.txt
Q: How to make python gracefully fail? I was just wondering how do you make python fail in a user defined way in all possible errors. For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spit...
How to make python gracefully fail?
I was just wondering how do you make python fail in a user defined way in all possible errors. For example, I'm writing a program that processes a (large) list of items, and some of the items may not be in the format I defined. If python detects an error, it currently just spits out an ugly error message and stop the ...
[ "The following are a few basic strategies I regularly use in my more-than-trivial scripts and medium-size applications.\nTip 1: Trap the error at every level where it makes sense to continue processing. In your case it may be in the inside the loop. You don't have to protect every single line or every single functi...
[ 25, 8, 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000497952_python.txt
Q: IronPython vs. C# for small-scale projects I currently use Python for most of my programming projects (mainly rapid development of small programs and prototypes). I'd like to invest time in learning a language that gives me the flexibility to use various Microsoft tools and APIs whenever the opportunity arises. I'...
IronPython vs. C# for small-scale projects
I currently use Python for most of my programming projects (mainly rapid development of small programs and prototypes). I'd like to invest time in learning a language that gives me the flexibility to use various Microsoft tools and APIs whenever the opportunity arises. I'm trying to decide between IronPython and C#. Si...
[ "I've built a large-scale application in IronPython bound with C#.\nIt's almost completely seamless. The only things missing in IronPython from the true \"python\" feel are the C-based libraries (gotta use .NET for those) and IDLE.\nThe language interacts with other .NET languages like a dream... Specifically if y...
[ 11, 3 ]
[]
[]
[ ".net", "c#", "ironpython", "python" ]
stackoverflow_0000497747_.net_c#_ironpython_python.txt
Q: What's a good way to keep track of class instance variables in Python? I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. ...
What's a good way to keep track of class instance variables in Python?
I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how d...
[ "I would say, the standard practice to avoid this is to not write classes where you can be 1000 lines away from anything!\nSeriously, that's way too much for just about any useful class, especially in a language that is as expressive as Python. Using more of what the Standard Library offers and abstracting away cod...
[ 10, 8, 5, 4, 3, 3, 2, 2, 0 ]
[ "Consider using slots.\nFor example:\n\n class Foo:\n __slots__ = \"a b c\".split()\n x = Foo()\n x.a =1 # ok\n x.b =1 # ok\n x.c =1 # ok\n x.bb = 1 # will raise \"AttributeError: Foo instance has no attribute 'bb'\"\n\nIt is generally a concern in any dynamic programming language -- any l...
[ -2 ]
[ "python", "variables" ]
stackoverflow_0000496582_python_variables.txt
Q: XML-RPC and Continuum from Python / Perl Has anyone had any success with getting data via Xml-rpc using Python or Perl...? I'm using the continuum.py library: #!/usr/bin/env python from continuum import * c = Continuum( "http://localhost:8080/continuum/xmlrpc" ) or: #!/usr/bin/perl use Frontier::Client; my $u...
XML-RPC and Continuum from Python / Perl
Has anyone had any success with getting data via Xml-rpc using Python or Perl...? I'm using the continuum.py library: #!/usr/bin/env python from continuum import * c = Continuum( "http://localhost:8080/continuum/xmlrpc" ) or: #!/usr/bin/perl use Frontier::Client; my $url = "http://dev.server.com:8080/continuum/xml...
[ "Yes... with Perl. \nI've used XML::RPC. In fact I wrote the CPAN module WWW::FreshMeat::API using it to access Freshmeats XML-RPC API so I know it does work well!\nUsing XML::RPC with Freshmeat the \"system.*\" calls work for me....\nuse XML::RPC;\nuse Data::Dumper;\n\nmy $fm = XML::RPC->new( 'http://freshmeat....
[ 1, 1 ]
[]
[]
[ "continuum", "perl", "python", "xml_rpc" ]
stackoverflow_0000462038_continuum_perl_python_xml_rpc.txt
Q: Python and Bluetooth/OBEX Is there any Python libraries that will let me send files with OBEX (OBject EXchange) and that works cross-platform (Windows, OS X, Linux)? I have found Lightblue, which works for Linux and OS X, but not for Windows. If none such lib exists, are there any decent ones that only works in Wi...
Python and Bluetooth/OBEX
Is there any Python libraries that will let me send files with OBEX (OBject EXchange) and that works cross-platform (Windows, OS X, Linux)? I have found Lightblue, which works for Linux and OS X, but not for Windows. If none such lib exists, are there any decent ones that only works in Windows?
[ "PyOBEX might work, but it has only been tested with a Linux Bluetooth stack:\nhttp://pypi.python.org/pypi/PyOBEX/0.10\nIt would be good to know if it works correctly on Windows and Mac OS X.\n", "PyBluez - Windows \n" ]
[ 2, 1 ]
[]
[]
[ "bluetooth", "python" ]
stackoverflow_0000452018_bluetooth_python.txt
Q: Passing JSON strings larger than 80 characters I'm having a problem passing strings that exceed 80 characters in JSON. When I pass a string that's exactly 80 characters long it works like magic. But once I add the 81st letter it craps out. I've tried looking at the json object in firebug and it seems to think the ...
Passing JSON strings larger than 80 characters
I'm having a problem passing strings that exceed 80 characters in JSON. When I pass a string that's exactly 80 characters long it works like magic. But once I add the 81st letter it craps out. I've tried looking at the json object in firebug and it seems to think the string is an array because it has an expander next t...
[ "What is the 81st character? Sounds like the string isn't properly escaped, making the json decoder think it is an array. If you could post the string here, or at least the 20 or so characters around 80, I could probably tell you what is wrong. Also, if you could tell how the json string was made. In most languages...
[ 1 ]
[]
[]
[ "json", "max", "python", "size", "string" ]
stackoverflow_0000499596_json_max_python_size_string.txt
Q: How do you create python methods(signature and content) in code? I've created a method that generates a new class and adds some methods into the class, but there is a strange bug, and I'm not sure what's happening: def make_image_form(image_fields): ''' Takes a list of image_fields to generate images ''' i...
How do you create python methods(signature and content) in code?
I've created a method that generates a new class and adds some methods into the class, but there is a strange bug, and I'm not sure what's happening: def make_image_form(image_fields): ''' Takes a list of image_fields to generate images ''' images = SortedDict() for image_name in image_fields: image...
[ "Python code behaves like this for functions defined in scope of methods.\nUse this instead:\nfor image_name in image_fields:\n print \"image name is: \", image_name\n setattr(new_form, 'clean_' + image_name, \n lambda self, iname=image_name: self._clean_photo(iname))\n\nThe usage of default keywor...
[ 5 ]
[]
[]
[ "django", "dynamic", "lambda", "methods", "python" ]
stackoverflow_0000499964_django_dynamic_lambda_methods_python.txt
Q: Python 3.0 `wsgiref` server not functioning I can't seem to get the wsgiref module to work at all under Python 3.0. It works fine under 2.5 for me, however. Even when I try the example in the docs, it fails. It fails so hard that even if I have a print function above where I do: "from wsgiref.simple_server import ...
Python 3.0 `wsgiref` server not functioning
I can't seem to get the wsgiref module to work at all under Python 3.0. It works fine under 2.5 for me, however. Even when I try the example in the docs, it fails. It fails so hard that even if I have a print function above where I do: "from wsgiref.simple_server import make_server", it never gets printed for some reas...
[ "issue 4718:wsgiref package totally broken. sorry about that.\n", "You're in uncharted territory with WSGI on Python 3.0 I'm afraid.\nWEB-SIG knew long ago that wsgiref was broken going into 3.0, but chose to do nothing about it. The spec hasn't been updated to cope with 3.0; pushing WSGI forwards even for the th...
[ 2, 0 ]
[]
[]
[ "python", "python_3.x", "wsgi", "wsgiref" ]
stackoverflow_0000497704_python_python_3.x_wsgi_wsgiref.txt
Q: excluding characters in \S regex match I have the following regex expression to match html links: <a\s*href=['|"](http:\/\/(.*?)\S['|"]> it kind of works. Except not really. Because it grabs everything after the < a href... and just keeps going. I want to exclude the quote characters from that last \S match. Is t...
excluding characters in \S regex match
I have the following regex expression to match html links: <a\s*href=['|"](http:\/\/(.*?)\S['|"]> it kind of works. Except not really. Because it grabs everything after the < a href... and just keeps going. I want to exclude the quote characters from that last \S match. Is there any way of doing that? EDIT: This would...
[ "I don't think your regex is doing what you want.\n<a\\s*href=['|\"](http:\\/\\/(.*?)\\S['|\"]>\n\nThis captures anything non-greedily from http:// up to the first non-space character before a quote, single quote, or pipe. For that matter, I'm not sure how it parses, as it doesn't seem to have enough close parens....
[ 4, 3, 1, 0, 0, 0 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0000292167_html_python_regex.txt
Q: Can I log into a web application automatically using a users windows logon? On the intranet at my part time job (not IT related) there are various web applications that we use that do not require logging in explicitly. We are required to login to Windows obviously, and that then authenticates us some how. I'm wond...
Can I log into a web application automatically using a users windows logon?
On the intranet at my part time job (not IT related) there are various web applications that we use that do not require logging in explicitly. We are required to login to Windows obviously, and that then authenticates us some how. I'm wondering how this is done? Without worrying about security TOO much, how would I go ...
[ "Once upon a time Internet Explorer supported NTLM authentication (similar to Basic Auth but it sent cached credentials to the server which could be verified with the domain controller). It was used to enable single-signon within an intranet where everyone was expected to be logged into the domain. I don't recall t...
[ 2, 1, 0 ]
[]
[]
[ "authentication", "python", "web_applications", "windows_authentication" ]
stackoverflow_0000500134_authentication_python_web_applications_windows_authentication.txt
Q: Partial evaluation for parsing I'm working on a macro system for Python (as discussed here) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your units ahead of time), I'm toying around with the ...
Partial evaluation for parsing
I'm working on a macro system for Python (as discussed here) and one of the things I've been considering are units of measure. Although units of measure could be implemented without macros or via static macros (e.g. defining all your units ahead of time), I'm toying around with the idea of allowing syntax to be extend...
[ "Here are a few possible problems:\n\nYou may find it difficult to provide the user with helpful error messages in case of a problem. This seems likely, as any compilation-time syntax error could be just a syntax extension.\nPerformance hit.\n\nI was trying to find some discussion of the pluses, minuses, and/or im...
[ 3, 2, 2, 1, 0, 0 ]
[]
[]
[ "language_design", "macros", "parsing", "python" ]
stackoverflow_0000474275_language_design_macros_parsing_python.txt
Q: Python's version of PHP's time() function I've looked at the Python Time module and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time(). Am I simply missing something here or is there a common way to do this that's simply not listed there? A: import time print int(ti...
Python's version of PHP's time() function
I've looked at the Python Time module and can't find anything that gives the integer of how many seconds since 1970 as PHP does with time(). Am I simply missing something here or is there a common way to do this that's simply not listed there?
[ "import time\nprint int(time.time())\n\n", "time.time() does it, but it might be float instead of int which i assume you expect. that is, precision can be higher than 1 sec on some systems.\n", "I recommend reading \"Date and Time Representation in Python\". I found it very enlightening.\n" ]
[ 23, 6, 3 ]
[]
[]
[ "python", "time" ]
stackoverflow_0000495595_python_time.txt
Q: In Python - how to execute system command with no output Is there a built-in method in Python to execute a system command without displaying the output? I only want to grab the return value. It is important that it be cross-platform, so just redirecting the output to /dev/null won't work on Windows, and the other ...
In Python - how to execute system command with no output
Is there a built-in method in Python to execute a system command without displaying the output? I only want to grab the return value. It is important that it be cross-platform, so just redirecting the output to /dev/null won't work on Windows, and the other way around. I know I can just check os.platform and build the ...
[ "import os\nimport subprocess\nsubprocess.call([\"ls\", \"-l\"], stdout=open(os.devnull, \"w\"), stderr=subprocess.STDOUT)\n\n", "You can redirect output into temp file and delete it afterward. But there's also a method called popen that redirects output directly to your program so it won't go on screen.\n" ]
[ 25, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000500477_python.txt
Q: Python/Twisted multiuser server - what is more efficient? In Python, if I want my server to scale well CPU-wise, I obviously need to spawn multiple processes. I was wondering which is better (using Twisted): A) The manager process (the one who holds the actual socket connections) puts received packets into a share...
Python/Twisted multiuser server - what is more efficient?
In Python, if I want my server to scale well CPU-wise, I obviously need to spawn multiple processes. I was wondering which is better (using Twisted): A) The manager process (the one who holds the actual socket connections) puts received packets into a shared queue (the one from the multiprocessing module), and worker p...
[ "I think that B is problematic. The thread would only run on one CPU, and even if it runs a process, the thread is still running. A may be better.\nIt is best to try and measure both in terms of time and see which one is faster and which one scales well. However, I'll reiterate that I highly doubt that B will scale...
[ 2, 1 ]
[]
[]
[ "multi_user", "python", "twisted" ]
stackoverflow_0000471660_multi_user_python_twisted.txt
Q: unit testing for an application server I wrote an application server (using python & twisted) and I want to start writing some tests. But I do not want to use Twisted's Trial due to time constraints and not having time to play with it now. So here is what I have in mind: write a small test client that connects to ...
unit testing for an application server
I wrote an application server (using python & twisted) and I want to start writing some tests. But I do not want to use Twisted's Trial due to time constraints and not having time to play with it now. So here is what I have in mind: write a small test client that connects to the app server and makes the necessary reque...
[ "You should use Trial. It really isn't very hard. Trial's documentation could stand to be improved, but if you know how to use the standard library unit test, the only difference is that instead of writing\nimport unittest\n\nyou should write\nfrom twisted.trial import unittest\n\n... and then you can return Defe...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "twisted", "unit_testing" ]
stackoverflow_0000464543_python_twisted_unit_testing.txt
Q: is there an alternative way of calling next on python generators? I have a generator and I would like to know if I can use it without having to worry about StopIteration , and I would like to use it without the for item in generator . I would like to use it with a while statement for example ( or other constructs ...
is there an alternative way of calling next on python generators?
I have a generator and I would like to know if I can use it without having to worry about StopIteration , and I would like to use it without the for item in generator . I would like to use it with a while statement for example ( or other constructs ). How could I do that ?
[ "built-in function\n\nnext(iterator[, default])\n Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.\n\nIn Python 2.5 and older:\nraiseStopIteration = object()\ndef next(iterator, defaul...
[ 15, 2, -1 ]
[]
[]
[ "language_features", "python" ]
stackoverflow_0000500578_language_features_python.txt
Q: Python + SQLite query to find entries that sit in a specified time slot I want to store a row in an SQLite 3 table for each booking in my diary. Each row will have a 'start time' and a 'end time'. Does any one know how I can query the table for an event at a given time? E.g. Return any rows that happen at say 10:3...
Python + SQLite query to find entries that sit in a specified time slot
I want to store a row in an SQLite 3 table for each booking in my diary. Each row will have a 'start time' and a 'end time'. Does any one know how I can query the table for an event at a given time? E.g. Return any rows that happen at say 10:30am Thanks
[ "SQLite3 doesn't have a datetime type, though it does have date and time functions.\nTypically you store dates and times in your database in something like ISO 8601 format: YYYY-MM-DD HH:MM:SS. Then datetimes sort lexicographically into time order.\nWith your datetimes stored this way, you simply use text compariso...
[ 2 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0000501021_python_sql_sqlite.txt
Q: list named with a function argument in python I get the feeling this is probably something I should know but I can't think of it right now. I'm trying to get a function to build a list where the name of the list is an argument given in the function; e.g. def make_hand(deck, handname): handname = [] for c i...
list named with a function argument in python
I get the feeling this is probably something I should know but I can't think of it right now. I'm trying to get a function to build a list where the name of the list is an argument given in the function; e.g. def make_hand(deck, handname): handname = [] for c in range(5): handname.append(deck.pop()) ...
[ "You can keep a dictionary where the keys are the name of the hand and the values are the list. \nThen you can just say dictionary[handname] to access a particular hand. Along the lines of:\nhands = {} # Create a new dictionary to hold the hands.\nhands[\"flush\"] = make_hand(deck) # Generate some hands using your ...
[ 6, 2 ]
[]
[]
[ "arguments", "list", "python" ]
stackoverflow_0000501027_arguments_list_python.txt
Q: Komodo Edit and Notepad++ ::: Pros & Cons ::: Python dev I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit. I need Pros and Cons for Python development between this two editors... A: I have worked a bit with Python programming for Google App Engine, which I started o...
Komodo Edit and Notepad++ ::: Pros & Cons ::: Python dev
I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit. I need Pros and Cons for Python development between this two editors...
[ "I have worked a bit with Python programming for Google App Engine, which I started out in Notepad++ and then recently shifted over to Komodo using two excellent startup tutorials - both of which are conveniently linked from this blog post (direct: here and here).\n\nKomodo supports the basic\norganization of your ...
[ 22, 9, 8, 7, 5, 4, 1, 1 ]
[ "Downloaded both myself. Like Komodo better. \nKomodo Pros: Like it better. Does more. Looks like an IDE. Edits Django templates\nNotepad++ Cons: Don't like it as much. Does less. Looks less like and IDE.\n" ]
[ -4 ]
[ "editor", "komodo", "komodoedit", "notepad++", "python" ]
stackoverflow_0000309135_editor_komodo_komodoedit_notepad++_python.txt
Q: Minimal, Standalone, Distributable, cross platform web server I've been writing a fair number of smaller wsgi apps lately and am looking to find a web server that can be distributed, preconfigured to run the specific app. I know there are things like twisted and cherrypy which can serve up wsgi apps, but they see...
Minimal, Standalone, Distributable, cross platform web server
I've been writing a fair number of smaller wsgi apps lately and am looking to find a web server that can be distributed, preconfigured to run the specific app. I know there are things like twisted and cherrypy which can serve up wsgi apps, but they seem to be missing a key piece of functionality for me, which is the a...
[ "Lighttpd has a BSD license, so you should be able to bundle it if you wanted.\nYou say its for small apps, so I guess that means, small, local, single user web interfaces being served by a small http server? If thats is the case, then any python implementation should work. Just use something like py2exe to packa...
[ 5, 3 ]
[]
[]
[ "http", "python", "wsgi" ]
stackoverflow_0000499084_http_python_wsgi.txt
Q: How can I execute Python code without Komodo -ide? I do that without the IDE: $ ipython $ edit file.py $ :x (save and close) It executes Python code, but not the one, where I use Pygame. It gives: WARNING: Failure executing file: In the IDE, my code executes. A: If something doesn't work in ipython, try t...
How can I execute Python code without Komodo -ide?
I do that without the IDE: $ ipython $ edit file.py $ :x (save and close) It executes Python code, but not the one, where I use Pygame. It gives: WARNING: Failure executing file: In the IDE, my code executes.
[ "If something doesn't work in ipython, try the real Python interpreter (just python); ipython has known bugs, and not infrequently code known to work in the real interpreter fails there.\nOn UNIXlike platforms, your script should start with a shebang -- that is, a line like the following:\n#!/usr/bin/env python\n\n...
[ 1 ]
[]
[]
[ "executable", "ide", "python" ]
stackoverflow_0000501817_executable_ide_python.txt
Q: How to modularize a Python application I've got a number of scripts that use common definitions. How do I split them in multiple files? Furthermore, the application can not be installed in any way in my scenario; it must be possible to have an arbitrary number of versions concurrently running and it must work with...
How to modularize a Python application
I've got a number of scripts that use common definitions. How do I split them in multiple files? Furthermore, the application can not be installed in any way in my scenario; it must be possible to have an arbitrary number of versions concurrently running and it must work without superuser rights. Solutions I've come up...
[ "Adding to sys.path (usually using site.addsitedir) is quite common and not particularly frowned upon. Certainly you will want your common working shared stuff to be in modules somewhere convenient.\nIf you are using Python 2.6+ there's already a user-level modules folder you can use without having to add to sys.pa...
[ 8, 4, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000501945_python.txt
Q: How do I send an ARP packet through python on windows without needing winpcap? Is there any way to send ARP packet on Windows without the use of another library such as winpcap? I have heard that Windows XP SP2 blocks raw ethernet sockets, but I have also heard that raw sockets are only blocked for administrators....
How do I send an ARP packet through python on windows without needing winpcap?
Is there any way to send ARP packet on Windows without the use of another library such as winpcap? I have heard that Windows XP SP2 blocks raw ethernet sockets, but I have also heard that raw sockets are only blocked for administrators. Any clarification here?
[ "There is no way to do that in the general case without the use of an external library.\nIf there are no requirements on what the packet should contain (i.e., if any ARP packet will do) then you can obviously send an ARP request if you're on an Ethernet network simply by trying to send something to any IP on your o...
[ 3, 0 ]
[]
[]
[ "arp", "ethernet", "python", "sockets" ]
stackoverflow_0000395846_arp_ethernet_python_sockets.txt
Q: using django-rest-interface with http put I'm trying to figure out how to implement my first RESTful interface using Django and django-rest-interface. I'm having problems with the HTTP PUT requests. How do I access the parameters of the PUT request? I thought they would be in the request.POST array, as PUT is som...
using django-rest-interface with http put
I'm trying to figure out how to implement my first RESTful interface using Django and django-rest-interface. I'm having problems with the HTTP PUT requests. How do I access the parameters of the PUT request? I thought they would be in the request.POST array, as PUT is somewhat similar to POST in my understanding, but ...
[ "request.POST processes form-encoded data into a dictionary, which only makes sense for web browser form submissions. There is no equivalent for PUT, as web browsers don't PUT forms; the data submitted could have any content type. You'll need to get the raw data out of request.raw_post_data, possibly check the co...
[ 13, 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000500434_django_python.txt
Q: Beginner-level Python threading problems As someone new to GUI development in Python (with pyGTK), I've just started learning about threading. To test out my skills, I've written a simple little GTK interface with a start/stop button. The goal is that when it is clicked, a thread starts that quickly increments a n...
Beginner-level Python threading problems
As someone new to GUI development in Python (with pyGTK), I've just started learning about threading. To test out my skills, I've written a simple little GTK interface with a start/stop button. The goal is that when it is clicked, a thread starts that quickly increments a number in the text box, while keeping the GUI r...
[ "Threading with PyGTK is bit tricky if you want to do it right. Basically, you should not update GUI from within any other thread than main thread (common limitation in GUI libs). Usually this is done in PyGTK using mechanism of queued messages (for communication between workers and GUI) which are read periodically...
[ 9, 3, 1, 0, 0 ]
[]
[]
[ "multithreading", "pygtk", "python" ]
stackoverflow_0000482263_multithreading_pygtk_python.txt
Q: Query distinct list of choices for Django form with App Engine Datastore I've been trying to figure this out for hours across a couple of days, and can not get it to work. I've been everywhere. I'll continue trying to figure it out, but was hoping for a quicker solution. I'm using App Engine datastore + Django. Us...
Query distinct list of choices for Django form with App Engine Datastore
I've been trying to figure this out for hours across a couple of days, and can not get it to work. I've been everywhere. I'll continue trying to figure it out, but was hoping for a quicker solution. I'm using App Engine datastore + Django. Using a query in a view and custom forms, I was able to get a list to the form b...
[ "I'm not familiar with App Engine Datastore, but I'm guessing you probably want to do something along these lines:\nclass InfoForm(djangoforms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(InfoForm, self).__init__(*args, **kwargs)\n choices = [(r.id, r.info) for r in Info.objects.filte...
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0000503295_django_google_app_engine_python.txt
Q: Simple simulations for Physics in Python? I would like to know similar, concrete simulations, as the simulation about watering a field here. What is your favorite library/internet page for such simulations in Python? I know little Simpy, Numpy and Pygame. I would like to get examples about them. A: If you are lo...
Simple simulations for Physics in Python?
I would like to know similar, concrete simulations, as the simulation about watering a field here. What is your favorite library/internet page for such simulations in Python? I know little Simpy, Numpy and Pygame. I would like to get examples about them.
[ "If you are looking for some game physics (collisions, deformations, gravity, etc.) which looks real and is reasonably fast consider re-using some physics engine libraries.\nAs a first reference, you may want to look into pymunk, a Python wrapper of Chipmunk 2D physics library. You can find a list of various Open S...
[ 15, 3, 2, 1 ]
[]
[]
[ "modeling", "python", "simulation" ]
stackoverflow_0000501940_modeling_python_simulation.txt
Q: Organising a GUI application This is going to be a generic question. I am struggling in designing a GUI application, esp. with dealing with interactions between different parts. I don't know how I should deal with shared state. On one hand, shared state is bad, and things should be as explicit as possible. On the ...
Organising a GUI application
This is going to be a generic question. I am struggling in designing a GUI application, esp. with dealing with interactions between different parts. I don't know how I should deal with shared state. On one hand, shared state is bad, and things should be as explicit as possible. On the other hand, not having shared stat...
[ "If you've looked at MVC you're probably moving in the right direction. MVC, MVP, Passive View, Supervising Controller. Those are all different ways, each with their own pros and cons, of accomplishing what you're after. I find that Passive View is the \"ideal\", but it causes you to introduce far too many widge...
[ 2, 2, 1 ]
[]
[]
[ "architecture", "model_view_controller", "python", "user_interface", "wxpython" ]
stackoverflow_0000471279_architecture_model_view_controller_python_user_interface_wxpython.txt
Q: Extracting data from MS Word I am looking for a way to extract / scrape data from Word files into a database. Our corporate procedures have Minutes of Meetings with clients documented in MS Word files, mostly due to history and inertia. I want to be able to pull the action items from these meeting minutes into a ...
Extracting data from MS Word
I am looking for a way to extract / scrape data from Word files into a database. Our corporate procedures have Minutes of Meetings with clients documented in MS Word files, mostly due to history and inertia. I want to be able to pull the action items from these meeting minutes into a database so that we can access the...
[ "Word has a little marker thingy that it puts at the end of every cell of text in a table. \nIt is used just like an end-of-paragraph marker in paragraphs: to store the formatting for the entire paragraph.\nJust use the Left() function to strip it out, i.e. \n Left(Target, Len(Target)-1))\n\nBy the way, instead of ...
[ 4, 1, 1, 0, 0, 0 ]
[]
[]
[ "ms_word", "python", "pywin32", "vba" ]
stackoverflow_0000505925_ms_word_python_pywin32_vba.txt
Q: Python includes, module scope issue I'm working on my first significant Python project and I'm having trouble with scope issues and executing code in included files. Previously my experience is with PHP. What I would like to do is have one single file that sets up a number of configuration variables, which would ...
Python includes, module scope issue
I'm working on my first significant Python project and I'm having trouble with scope issues and executing code in included files. Previously my experience is with PHP. What I would like to do is have one single file that sets up a number of configuration variables, which would then be used throughout the code. Also, I...
[ "In python, it is a common practice to have a bunch of modules that implement various functions and then have one single module that is the point-of-access to all the functions. This is basically the facade pattern.\nAn example: say you're writing a package foo, which includes the bar, baz, and moo modules.\n~/proj...
[ 6, 1, 0, 0 ]
[]
[]
[ "import", "include", "module", "python" ]
stackoverflow_0000507425_import_include_module_python.txt
Q: get site name from a URL in python I am new to Python and it seems to have a lot of nice functions that I don't know about. What function can I use to get the root site name? For example, how would I get faqs.org if I gave the function the URL "http://www.faqs.org/docs/diveintopython/kgp_commandline.html"? A: >...
get site name from a URL in python
I am new to Python and it seems to have a lot of nice functions that I don't know about. What function can I use to get the root site name? For example, how would I get faqs.org if I gave the function the URL "http://www.faqs.org/docs/diveintopython/kgp_commandline.html"?
[ " >>> from urllib.parse import urlparse\n >>> urlparse('http://www.cwi.nl:80/%7Eguido/Python.html').hostname\n 'www.cwi.nl'\n\n", "The much overlooked urlparse module:\nfrom urlparse import urlparse\nscheme, netloc, path, params, query, fragment = urlparse(\"http://www.faqs.org/docs/diveintopython/kgp_commandline...
[ 5, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000508183_python.txt
Q: Why does Django only serve files containing a space? I'm writing a basic Django application. For testing / development purposes I'm trying to serve the static content of the website using Django's development server as per http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files. My urls.py cont...
Why does Django only serve files containing a space?
I'm writing a basic Django application. For testing / development purposes I'm trying to serve the static content of the website using Django's development server as per http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files. My urls.py contains: (r'^admin/(.*)', admin.site.root), (r'^(?P<...
[ "You have wrong patterns order in urls.py.\nWhen you try to retrieve path without space it matches:\n(r'^(?P<page_name>\\S*)$', 'Blah.content.views.index'),\n\nnot static.serve and of course you have not such page, But when you try to access path with space it matches proper static.serve pattern because it is more ...
[ 10 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000508609_django_python.txt
Q: Problem in understanding Python list comprehensions What does the last line mean in the following code? import pickle, urllib handle = urllib.urlopen("http://www.p...
Problem in understanding Python list comprehensions
What does the last line mean in the following code? import pickle, urllib handle = urllib.urlopen("http://www.pythonchallenge.com/pc/def/banner.p") data = pickle.load...
[ "Maybe best explained with an example:\nprint \"\".join([e[1] * e[0] for e in elt])\n\nis the short form of\nx = []\nfor e in elt:\n x.append(e[1] * e[0])\nprint \"\".join(x)\n\nList comprehensions are simply syntactic sugar for for loops, which make an expression out of a sequence of statements.\nelt can be an ar...
[ 21, 7, 4, 2, 1, 1 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0000501308_list_comprehension_python.txt
Q: How to overwrite some bytes in the middle of a file with Python? I'd like to be able to overwrite some bytes at a given offset in a file using Python. My attempts have failed miserably and resulted in: overwriting the bytes at the offset but also truncating the file just after (file mode = "w" or "w+") appendin...
How to overwrite some bytes in the middle of a file with Python?
I'd like to be able to overwrite some bytes at a given offset in a file using Python. My attempts have failed miserably and resulted in: overwriting the bytes at the offset but also truncating the file just after (file mode = "w" or "w+") appending the bytes at the end of the file (file mode = "a" or "a+") Is i...
[ "Try this:\nfh = open(\"filename.ext\", \"r+b\")\nfh.seek(offset)\nfh.write(bytes)\nfh.close()\n\n", "According to this python page you can type file.seek to seek to a particualar offset. You can then write whatever you want.\nTo avoid truncating the file, you can open it with \"a+\" then seek to the right offset...
[ 47, 5, 0 ]
[]
[]
[ "file", "patch", "python" ]
stackoverflow_0000508983_file_patch_python.txt
Q: Symbolic Mathematics Python? I am extreamly interested in math and programming and planning to start symbolic math project from scratch. Is this good project idea? Where to start? How should one approach this project? Any good resources? Thanks in advance. A: It's a good project to practice programming ski...
Symbolic Mathematics Python?
I am extreamly interested in math and programming and planning to start symbolic math project from scratch. Is this good project idea? Where to start? How should one approach this project? Any good resources? Thanks in advance.
[ "\nIt's a good project to practice programming skills. But if you want to create a real library that other people will want to use this is a project you do not want to start allone and from scratch ...\nWhere to start: Have a look at the solutions that are already out there and think about what it is that you want ...
[ 19, 10, 7, 4, 3, 1, 1 ]
[]
[]
[ "algorithm", "math", "python", "symbolic_math" ]
stackoverflow_0000506748_algorithm_math_python_symbolic_math.txt
Q: Passing self to class functions in Python What's the reason of passing a value for a self reference in class functions in python? For instance: class MyClass: """A simple example class""" i = 12345 def f(**self**): return 'hello world' By doing this, aren't you doing the compiler's work? A: ...
Passing self to class functions in Python
What's the reason of passing a value for a self reference in class functions in python? For instance: class MyClass: """A simple example class""" i = 12345 def f(**self**): return 'hello world' By doing this, aren't you doing the compiler's work?
[ "Many electrons have given their lives to discussing this question over the years.\nGuido (python's creator) weighs forth on the issue in his blog here, in response to a proposal last year to get rid of the explicit self. The python FAQ also covers the issue.\nFinally, if you don't mind a bit of grey magic, you ca...
[ 9, 2 ]
[]
[]
[ "class", "function", "python" ]
stackoverflow_0000509421_class_function_python.txt
Q: Python M2Crypto - generating a DSA key pair and separating public/private components Could anybody explain what is the cause of the following: >>> from M2Crypto import DSA, BIO >>> dsa = DSA.gen_params(1024) ..+........+++++++++++++++++++++++++++++++++++++++++++++++++++* ............+.+.+..+.........+................
Python M2Crypto - generating a DSA key pair and separating public/private components
Could anybody explain what is the cause of the following: >>> from M2Crypto import DSA, BIO >>> dsa = DSA.gen_params(1024) ..+........+++++++++++++++++++++++++++++++++++++++++++++++++++* ............+.+.+..+.........+.............+.....................+. ...+.............+...........+......................................
[ "Call dsa.gen_key(), then save. You aren't actually generating the public key.\n>>> from M2Crypto import DSA, BIO\n>>> dsa = DSA.gen_params(1024)\n..+..etc\n>>> mem = BIO.MemoryBuffer()\n>>> dsa.gen_key()\n>>> dsa.save_key_bio(mem, cipher=None)\n1\n>>> dsa.save_pub_key_bio(mem)\n1\n>>> print mem.getvalue()\n-----BE...
[ 7 ]
[]
[]
[ "cryptography", "m2crypto", "python", "rsa" ]
stackoverflow_0000509449_cryptography_m2crypto_python_rsa.txt
Q: python reading lines w/o \n? Would this work on all platforms? i know windows does \r\n, and remember hearing mac does \r while linux did \n. I ran this code on windows so it seems fine, but do any of you know if its cross platform? while 1: line = f.readline() if line == "": break line = line[...
python reading lines w/o \n?
Would this work on all platforms? i know windows does \r\n, and remember hearing mac does \r while linux did \n. I ran this code on windows so it seems fine, but do any of you know if its cross platform? while 1: line = f.readline() if line == "": break line = line[:-1] print "\"" + line + "\"" ...
[ "First of all, there is universal newline support\nSecond: just use line.strip(). Use line.rstrip('\\r\\n'), if you want to preserve any whitespace at the beginning or end of the line.\nOh, and\nprint '\"%s\"' % line\n\nor at least\nprint '\"' + line + '\"'\n\nmight look a bit nicer.\nYou can iterate over the lines...
[ 13, 4, 0 ]
[]
[]
[ "file", "newline", "python" ]
stackoverflow_0000509446_file_newline_python.txt
Q: Fast PDF splitter library pyPdf is a great library to split, merge PDF files. I'm using it to split pdf documents into 1 page documents. pyPdf is pure python and spends quite a lot of time in the _sweepIndirectReferences() method of the PdfFileWriter object when saving the extracted page. I need something with be...
Fast PDF splitter library
pyPdf is a great library to split, merge PDF files. I'm using it to split pdf documents into 1 page documents. pyPdf is pure python and spends quite a lot of time in the _sweepIndirectReferences() method of the PdfFileWriter object when saving the extracted page. I need something with better performance. I've tried us...
[ "mbtPdfAsm is a fast, open source command line tool for PDF processing.\nXpdf is also worth mentioning since it's GPL and written in C++. The source code is well modularized and allows for writing command line tools. \n", "Does it have to be python? My pure-Perl library CAM::PDF is pretty fast at appending and d...
[ 4, 2, 1, 1 ]
[]
[]
[ "c", "pdf", "pypdf", "python" ]
stackoverflow_0000508144_c_pdf_pypdf_python.txt
Q: How to chain views in Django? I'm implementing James Bennett's excellent django-contact-form but have hit a snag. My contact page not only contains the form, but also additional flat page information. Without rewriting the existing view the contact form uses, I'd like to be able to wrap, or chain, the views. T...
How to chain views in Django?
I'm implementing James Bennett's excellent django-contact-form but have hit a snag. My contact page not only contains the form, but also additional flat page information. Without rewriting the existing view the contact form uses, I'd like to be able to wrap, or chain, the views. This way I could inject some additio...
[ "There's a context processor that may do what you want.\nhttp://docs.djangoproject.com/en/dev/ref/templates/api/\nYou can probably add your various pieces of \"flat page information\" to the context.\n", "\nWrite a wrapper which uses the URL to look up the appropriate flat page object.\nFrom your wrapper, call (a...
[ 2, 2, 1 ]
[]
[]
[ "django", "django_views", "extension_methods", "python", "word_wrap" ]
stackoverflow_0000505703_django_django_views_extension_methods_python_word_wrap.txt
Q: How do I use django mptt? I have a model: class Company(models.Model): name = models.CharField( max_length=100) parent = models.ForeignKey('self', null=True, blank=True, related_name='children') mptt.register(Company, order_insertion_by=['name']) and class Financials(models.Model): year = models.Inte...
How do I use django mptt?
I have a model: class Company(models.Model): name = models.CharField( max_length=100) parent = models.ForeignKey('self', null=True, blank=True, related_name='children') mptt.register(Company, order_insertion_by=['name']) and class Financials(models.Model): year = models.IntegerField() revenue = models...
[ "I don't quite follow your question. A tree stores one type of object, in your case Company. To link Financials to Company just add a foreign key from Financials to Company.\nIf this doesn't help please expand your question to give us some more detail about what you are trying to achieve.\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_mptt", "python" ]
stackoverflow_0000510339_django_django_models_django_mptt_python.txt
Q: Valid use case for django admin? I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't s...
Valid use case for django admin?
I want to build a django site where a certain group of trusted users can edit their profile information. Does it make sense to have each trusted user go through the django admin interface? I'd only want them to be able to see and edit their own information (obviously). It doesn't seem like this fits the way the django ...
[ "No, the Django admin is not suited for individual user profiles, each user would be able to see, and edit, all other user profiles. This is suited more to an administrator who has to manage all the users at once.\nWhat you need to build is a user profile page. Django already has a nice login system courtesy of t...
[ 17, 5, 3, 3, 1, 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0000498199_django_django_admin_python.txt
Q: How can I tell python which version of libmysqlclient.so to use? I'm running a python script on a shared hosting server which until this morning had MySQL version 4. Now it has version 5. My python script can no longer connect to MySQL, as it can't find libmysqlclient_r.so.14: $ python my_script.py Traceback (most...
How can I tell python which version of libmysqlclient.so to use?
I'm running a python script on a shared hosting server which until this morning had MySQL version 4. Now it has version 5. My python script can no longer connect to MySQL, as it can't find libmysqlclient_r.so.14: $ python my_script.py Traceback (most recent call last): File "my_script.py", line 6, in ? import MySQLdb ...
[ "You can't tell the dynamic linker which version of a library to use, because the SONAME (full name of the library + interface) is part of the binary.\nIn your case, you can try to upload libmysqlclient_r.so.14 to the host and set LD_LIBRARY_PATH accordingly, so tell the dynamic linker which directories to search a...
[ 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000511011_python.txt
Q: Django Installed Apps Location I am an experienced PHP programmer using Django for the first time, and I think it is incredible! I have a project that has a lot of apps, so I wanted to group them in an apps folder. So the structure of the project is: /project/ /project/apps/ /project/apps/app1/ /project/apps/app2 ...
Django Installed Apps Location
I am an experienced PHP programmer using Django for the first time, and I think it is incredible! I have a project that has a lot of apps, so I wanted to group them in an apps folder. So the structure of the project is: /project/ /project/apps/ /project/apps/app1/ /project/apps/app2 Then in Django settings I have put ...
[ "Make sure that the '__init__.py' file is in your apps directory, if it's not there it won't be recognized as part of the package.\nSo each of the folders here should have '__init__.py' file in it. (empty is fine).\n/project/\n/project/apps/\n/project/apps/app1/\n/project/apps/app2\n\nThen as long as your root 'mod...
[ 41, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000511291_django_python.txt
Q: creating blank field and receving the INTEGER PRIMARY KEY with sqlite, python I am using sqlite with python. When i insert into table A i need to feed it an ID from table B. So what i wanted to do is insert default data into B, grab the id (which is auto increment) and use it in table A. Whats the best way receive...
creating blank field and receving the INTEGER PRIMARY KEY with sqlite, python
I am using sqlite with python. When i insert into table A i need to feed it an ID from table B. So what i wanted to do is insert default data into B, grab the id (which is auto increment) and use it in table A. Whats the best way receive the key from the table i just inserted into?
[ "As Christian said, sqlite3_last_insert_rowid() is what you want... but that's the C level API, and you're using the Python DB-API bindings for SQLite.\nIt looks like the cursor method lastrowid will do what you want (search for 'lastrowid' in the documentation for more information). Insert your row with cursor.exe...
[ 7, 1, 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0000510135_python_sqlite.txt
Q: How to call a python function from a foreign language thread (C++) I am developing a program that use DirectShow to grab audio data from media files. DirectShow use thread to pass audio data to the callback function in my program, and I let that callback function call another function in Python. I use Boost.Python...
How to call a python function from a foreign language thread (C++)
I am developing a program that use DirectShow to grab audio data from media files. DirectShow use thread to pass audio data to the callback function in my program, and I let that callback function call another function in Python. I use Boost.Python to wrapper my library, the callback function : class PythonCallback { p...
[ "Take a look at PyGILState_Ensure()/PyGILState_Release(), from PEP 311\nhttp://www.python.org/dev/peps/pep-0311/\nHere is an example taken from the PEP itself:\nvoid SomeCFunction(void)\n{\n /* ensure we hold the lock */\n PyGILState_STATE state = PyGILState_Ensure();\n /* Use the Python API */\n ...\n ...
[ 6, 1 ]
[]
[]
[ "boost", "c++", "locking", "multithreading", "python" ]
stackoverflow_0000510085_boost_c++_locking_multithreading_python.txt
Q: Using Python Ctypes for ssdeep's fuzzy.dll but receive error I am trying to use Python and ctypes to use the fuzzy.dll from ssdeep. So far everything I have tried fails with an access violation error. Here is what I do after changing to the proper directory which contains the fuzzy.dll and fuzzy.def files: >>> imp...
Using Python Ctypes for ssdeep's fuzzy.dll but receive error
I am trying to use Python and ctypes to use the fuzzy.dll from ssdeep. So far everything I have tried fails with an access violation error. Here is what I do after changing to the proper directory which contains the fuzzy.dll and fuzzy.def files: >>> import os,sys >>> from ctypes import * >>> fn = create_string_buffer(...
[ "There are two problems with your code:\n\nYou should not use windll.fuzzy, but cdll.fuzzy -- from ctypes documentation:\n\ncdll loads libraries which export functions using the standard cdecl calling convention, while windll libraries call functions using the stdcall calling convention.\n\n\nFor return value (chas...
[ 4 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0000510443_ctypes_python.txt
Q: Why doesn't PyRun_String evaluate bool literals? I need to evaluate a Python expression from C++. This code seems to work: PyObject * dict = PyDict_New(); PyObject * val = PyRun_String(expression, Py_eval_input, dict, 0); Py_DECREF(dict); Unfortunately, it fails horribly if expression is "True" of "False" (that i...
Why doesn't PyRun_String evaluate bool literals?
I need to evaluate a Python expression from C++. This code seems to work: PyObject * dict = PyDict_New(); PyObject * val = PyRun_String(expression, Py_eval_input, dict, 0); Py_DECREF(dict); Unfortunately, it fails horribly if expression is "True" of "False" (that is, val is 0 and PyErr_Occurred() returns true). What a...
[ "PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals);\n\nIf you want True and False they will have to be in the *globals dict passed to the interpreter. You might be able to fix that by calling PyEval_GetBuiltins.\nFrom the Python 2.6 source code:\nif (PyDict_GetItemString(global...
[ 5 ]
[]
[]
[ "boolean", "cpython", "python" ]
stackoverflow_0000512036_boolean_cpython_python.txt
Q: How to access templates in Python? Sometimes, for a program with a lot of data, it is common to place the data in an external file. An example is a script that produces an HTML report, using an external file to hold a template. In Java, the most recommended way to retrieve a resource of the program is to use getCl...
How to access templates in Python?
Sometimes, for a program with a lot of data, it is common to place the data in an external file. An example is a script that produces an HTML report, using an external file to hold a template. In Java, the most recommended way to retrieve a resource of the program is to use getClass().getClassLoader().getResource() or ...
[ "You can use os.path.dirname(__file__) to get the directory of the current module. Then use the path manipulation functions (specifically, os.path.join) and file input/output to open a file under the current module.\n", "What Daniel said. :-) Also, py2exe can be told to include external files (this is often use...
[ 2, 1 ]
[]
[]
[ "python", "templates" ]
stackoverflow_0000512499_python_templates.txt
Q: How can I write a wrapper around ngrep that highlights matches? I just learned about ngrep, a cool program that lets you easily sniff packets that match a particular string. The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these mat...
How can I write a wrapper around ngrep that highlights matches?
I just learned about ngrep, a cool program that lets you easily sniff packets that match a particular string. The only problem is that it can be hard to see the match in the big blob of output. I'd like to write a wrapper script to highlight these matches -- it could use ANSI escape sequences: echo -e 'This is \e[31mRE...
[ "This seems to do the trick, at least comparing two windows, one running a straight ngrep (e.g. ngrep whatever) and one being piped into the following program (with ngrep whatever | ngrephl target-string).\n#! /usr/bin/perl\n\nuse strict;\nuse warnings;\n\n$| = 1; # autoflush on\n\nmy $keyword = shift or die \"No p...
[ 4, 3, 3, 1, 1, 0 ]
[ "See the script at this post to Linux-IL where someone asked a similar question. It's written in Perl and uses the CPAN Term::ANSIColor module.\n" ]
[ -1 ]
[ "networking", "perl", "python", "unix" ]
stackoverflow_0000214059_networking_perl_python_unix.txt
Q: Various Python datetime issues I have two methods that I'm using as custom tags in a template engine: # Renders a <select> form field def select_field(options, selected_item, field_name): options = [(str(v),str(v)) for v in options] html = ['<select name="%s">' % field_name] for k,v in options: ...
Various Python datetime issues
I have two methods that I'm using as custom tags in a template engine: # Renders a <select> form field def select_field(options, selected_item, field_name): options = [(str(v),str(v)) for v in options] html = ['<select name="%s">' % field_name] for k,v in options: tmp = '<option ' if k == se...
[ "To turn an integer range into two digit strings:\n>>> range(13)\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n>>> [ '%02d' % i for i in range(13) ]\n['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']\n\nThen to get the AM/PM indicator:\n>>> import datetime\n>>> current_dt = datetime.date...
[ 5, 1, 1, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0000513291_datetime_python.txt
Q: Spawn subprocess that expects console input without blocking? I am trying to do a CVS login from Python by calling the cvs.exe process. When calling cvs.exe by hand, it prints a message to the console and then waits for the user to input the password. When calling it with subprocess.Popen, I've noticed that the c...
Spawn subprocess that expects console input without blocking?
I am trying to do a CVS login from Python by calling the cvs.exe process. When calling cvs.exe by hand, it prints a message to the console and then waits for the user to input the password. When calling it with subprocess.Popen, I've noticed that the call blocks. The code is subprocess.Popen(cvscmd, shell = True, std...
[ "\nRemove the shell=True part. Your shell has nothing to do with it. Using shell=True is a common cause of trouble.\nUse a list of parameters for cmd.\n\nExample:\ncmd = ['cvs', \n '-d:pserver:anonymous@bayonne.cvs.sourceforge.net:/cvsroot/bayonne', \n 'login']\np = subprocess.Popen(cmd, stdin=subproce...
[ 2, 0 ]
[]
[]
[ "python", "subprocess", "windows" ]
stackoverflow_0000510751_python_subprocess_windows.txt
Q: How to distribute script using gdata-python-client? I've written several scripts that make use of the gdata API, and they all (obviously) have my API key and client ID in plain-text. How am I supposed to distribute these? A: Move the variables into a separate module and replace your values with dummy values. Ma...
How to distribute script using gdata-python-client?
I've written several scripts that make use of the gdata API, and they all (obviously) have my API key and client ID in plain-text. How am I supposed to distribute these?
[ "Move the variables into a separate module and replace your values with dummy values. Make sure you trap for an invalid key and provide instructions on how to obtain a key and where to place it. In your code you can just import the values from that module.\nimport gdata_api_key\nprint gdata_api_key.key_value\n\n"...
[ 3, 0 ]
[]
[]
[ "gdata_api", "python" ]
stackoverflow_0000513806_gdata_api_python.txt
Q: Newline characters in non ASCII encoded files I'm using Python 2.6 to read latin2 encoded file with windows line endings ('\r\n'). import codecs file = codecs.open('stackoverflow_secrets.txt', encoding='latin2', mode='rt') line = file.readline() print(repr(line)) outputs : u'login: yabcok\n' file = codecs.open('...
Newline characters in non ASCII encoded files
I'm using Python 2.6 to read latin2 encoded file with windows line endings ('\r\n'). import codecs file = codecs.open('stackoverflow_secrets.txt', encoding='latin2', mode='rt') line = file.readline() print(repr(line)) outputs : u'login: yabcok\n' file = codecs.open('stackoverflow_secrets.txt', encoding='latin2', mode...
[ "Are you sure that your examples are correct? The documentation of the codecs module says: \n\nNote: Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8-bit values. This means that no automatic conversion of '\\n' is done on reading ...
[ 3, 0 ]
[]
[]
[ "encoding", "file", "python" ]
stackoverflow_0000513675_encoding_file_python.txt
Q: Combined Python & Ruby extension module I have a C extension module for Python and I want to make it available to Rubyists. The source has a number of C modules, with only one being Python-dependent. The rest depend only on each other and the standard library. I can build it with python setup.py build in the usual...
Combined Python & Ruby extension module
I have a C extension module for Python and I want to make it available to Rubyists. The source has a number of C modules, with only one being Python-dependent. The rest depend only on each other and the standard library. I can build it with python setup.py build in the usual way. I've been experimenting with adding Rub...
[ "One way to solve it is to create three different projects:\n\nThe library itself, independent on python & ruby\nPython bindings\nRuby bindings\n\nThat's probably the cleanest solution, albeit it requires a bit more work when doing releases, but it has the advantage that you can release a new version of the Ruby bi...
[ 5, 0 ]
[]
[]
[ "newgem", "python", "ruby", "setuptools" ]
stackoverflow_0000511412_newgem_python_ruby_setuptools.txt
Q: Is it possible for a running python program to overwrite itself? Is it possible for a python script to open its own source file and overwrite it? The idea was to have a very simple and very dirty way for a python script to download an update of itself so that the next time it is run it would be an updated version....
Is it possible for a running python program to overwrite itself?
Is it possible for a python script to open its own source file and overwrite it? The idea was to have a very simple and very dirty way for a python script to download an update of itself so that the next time it is run it would be an updated version.
[ "That's certainly possible. After the script is loaded/imported, the Python interpreter won't access it anymore, except when printing source line in a exception stack trace. Any pyc file will be regenerated the next time as the source file is newer than the pyc.\n", "If you put most of the code into a module, yo...
[ 25, 15, 8, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000291448_python.txt
Q: Help building a regular expression in python using the re module im writing a simple propositional logic formula parser in python which uses regular expressions re module and the lex/yacc module for lexing/parsing. Originally my code could pick out implication as ->, but adding logical equivalence (<->) caused iss...
Help building a regular expression in python using the re module
im writing a simple propositional logic formula parser in python which uses regular expressions re module and the lex/yacc module for lexing/parsing. Originally my code could pick out implication as ->, but adding logical equivalence (<->) caused issues with the compiled expressions IMPLICATION = re.compile('[\s]*\-\>[...
[ "As far as I can tell, your regular expressions are equivalent to the following:\n# This is bad, because IMPLICATION also will match every\n# string that EQUIVALENCE matches\nIMPLICATION = re.compile(\"->\")\nEQUIVALENCE = re.compile(\"<->\")\n\nAs you've written it, you're also matching for zero or more whitespace...
[ 4, 0 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0000514475_parsing_python_regex.txt
Q: Random name generator strategy - help me improve it I have a small project I am doing in Python using web.py. It's a name generator, using 4 "parts" of a name (firstname, middlename, anothername, surname). Each part of the name is a collection of entites in a MySQL databse (name_part (id, part, type_id), and name_...
Random name generator strategy - help me improve it
I have a small project I am doing in Python using web.py. It's a name generator, using 4 "parts" of a name (firstname, middlename, anothername, surname). Each part of the name is a collection of entites in a MySQL databse (name_part (id, part, type_id), and name_part_type (id, description)). Basic stuff, I guess. My ge...
[ "I think what you're after is:\nselect * from name_part\n where type_id=[something]\n order by used_count asc, rand()\n limit 1\n\nThis will put the lesser used names at the top of the list and, if there's multiples with the same (lowest) used_count, they'll sort randomly.\n", "I agree with your intuitio...
[ 4, 1 ]
[]
[]
[ "mysql", "python", "random", "web.py" ]
stackoverflow_0000514617_mysql_python_random_web.py.txt
Q: Web based wizard with Python What is a good/simple way to create, say a five page wizard, in Python, where the web server component composes the wizard page content mostly dynamically by fetching the data via calls to a XML-RPC back-end. I have experienced a bit with the XML-RPC Python module, but I don't know whi...
Web based wizard with Python
What is a good/simple way to create, say a five page wizard, in Python, where the web server component composes the wizard page content mostly dynamically by fetching the data via calls to a XML-RPC back-end. I have experienced a bit with the XML-RPC Python module, but I don't know which Python module would be providin...
[ "If we break down to the components you'll need, we get:\n\nHTTP server to receive the request from the clients browser.\nA URL router to look at the URL sent from client browser and call your function/method to handle that URL.\nAn XML-RPC client library to fetch the data for that URL.\nA template processor to ren...
[ 3 ]
[]
[]
[ "python", "wizard", "xml_rpc" ]
stackoverflow_0000514912_python_wizard_xml_rpc.txt
Q: How best to pass database objects to a turbogears WidgetList? I am trying to set up form widgets for adding some objects to the database but I'm getting stuck because it seems impossible to pass any arguments to Widgets contained within a WidgetList. To clarify that, here is my WidgetList: class ClientFields(forms...
How best to pass database objects to a turbogears WidgetList?
I am trying to set up form widgets for adding some objects to the database but I'm getting stuck because it seems impossible to pass any arguments to Widgets contained within a WidgetList. To clarify that, here is my WidgetList: class ClientFields(forms.WidgetsList): """Form to create a client""" name = forms....
[]
[]
[ "A page in the TurboGears documentation may help.\n" ]
[ -1 ]
[ "python", "turbogears" ]
stackoverflow_0000515522_python_turbogears.txt
Q: pure web based versioning system My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. I am looking for a pure php/python/ruby version control system (not just a client for a ve...
pure web based versioning system
My hosting service does not currently run/allow svn, git, cvs on their server. I would really like to be able to 'sync' my current source on my development machine with my production server. I am looking for a pure php/python/ruby version control system (not just a client for a version control system) that does not re...
[ "Get a better hosting service. Seriously. Even if you found something that worked in PHP/Ruby/Perl/Whatever, it would still be a sub-par solution. It most likely wouldn't integrate with any IDE you have, and wouldn't have a good tool set available for working with it. It would be really clunky to do correctly.\...
[ 7, 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "php", "python", "version_control", "web_applications" ]
stackoverflow_0000513173_php_python_version_control_web_applications.txt
Q: Is it possible to google search with the gdata API? I might be just thick (nothing new), but I can't seem to find anything related to an old-fashioned, vanilla google search in the gdata API docs. Anyone know if it's possible? (I know it probably is with a little tinkering, but I already have a Python web-scraping...
Is it possible to google search with the gdata API?
I might be just thick (nothing new), but I can't seem to find anything related to an old-fashioned, vanilla google search in the gdata API docs. Anyone know if it's possible? (I know it probably is with a little tinkering, but I already have a Python web-scraping class created that does it for me, but I was wondering i...
[ "AFAIK, the gdata API is just for the Google Doc's application (Google Spreadsheet etc). \nThe search API does expose a REST interface for \"Flash and other Non-Javascript Environments\" though:\nhttp://code.google.com/apis/ajaxsearch/documentation/#fonje\n" ]
[ 4 ]
[]
[]
[ "gdata_api", "python" ]
stackoverflow_0000516335_gdata_api_python.txt
Q: How to vertically align Paragraphs within a Table using Reportlab? I'm using Reportlab to generate report cards. The report cards are basically one big Table object. Some of the content in the table cells needs to wrap, specifically titles and comments, and I also need to bold certain elements. To accomplish bot...
How to vertically align Paragraphs within a Table using Reportlab?
I'm using Reportlab to generate report cards. The report cards are basically one big Table object. Some of the content in the table cells needs to wrap, specifically titles and comments, and I also need to bold certain elements. To accomplish both the wrapping and ability to bold, I'm using Paragraph objects within t...
[ "I have to ask: have you tried the tablestyle VALIGN:MIDDLE?\nsomething like:\nt=Table(data) \nt.setStyle(TableStyle([('VALIGN',(-1,-1),(-1,-1),'MIDDLE')])) \n\n(more details in section 7.2 of the ReportLab user guide)\nIf that doesn't do it, then your paragraph object must be the full height of the cell, and inter...
[ 12 ]
[]
[]
[ "alignment", "pdf", "python", "reportlab" ]
stackoverflow_0000500406_alignment_pdf_python_reportlab.txt
Q: Python regex: Turn "ThisFileName.txt" into "This File Name.txt" I'm trying to add a space before every capital letter, except the first one. Here's what I have so far, and the output I'm getting: >>> tex = "ThisFileName.txt" >>> re.sub('[A-Z].', ' ', tex) ' his ile ame.txt' I want: 'This File Name.txt' (It'd b...
Python regex: Turn "ThisFileName.txt" into "This File Name.txt"
I'm trying to add a space before every capital letter, except the first one. Here's what I have so far, and the output I'm getting: >>> tex = "ThisFileName.txt" >>> re.sub('[A-Z].', ' ', tex) ' his ile ame.txt' I want: 'This File Name.txt' (It'd be nice if I could also get rid of .txt, but I can do that in a separa...
[ "Key concept here is backreferences in regular expressions:\nimport re\ntext = \"ThisFileName.txt\"\nprint re.sub('([a-z])([A-Z])', r'\\1 \\2', text)\n# Prints: \"This File Name.txt\"\n\nFor pulling off the '.txt' in a reliable way, I recommend os.path.splitext()\nimport os\nfilename = \"ThisFileName.txt\"\nprint o...
[ 9, 2, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000516451_python_regex.txt
Q: Mixed language source directory layout We are running a large project with several different languages: Java, Python, PHP, SQL and Perl. Until now people have been working in their own private repositories, but now we want to merge the entire project in a single repository. The question now is: how should the dir...
Mixed language source directory layout
We are running a large project with several different languages: Java, Python, PHP, SQL and Perl. Until now people have been working in their own private repositories, but now we want to merge the entire project in a single repository. The question now is: how should the directory structure look? Should we have separa...
[ "My experience indicates that this kind of layout is best:\nmylib/\n src/\n java/\n python/\n perl/\n .../\n bin/\n java/\n python/\n perl/\n stage/\n dist/\n\nsrc is your source, and is the only thing checked in.\nbin is where \"compilation\" occurs to during t...
[ 6, 2 ]
[]
[]
[ "directory", "java", "python", "sql" ]
stackoverflow_0000516798_directory_java_python_sql.txt
Q: List/Arrays - Check Dates I'm trying to make a program that checks an array to make sure there are four folders with partially same names. So For a date like 0103 (jan 3rd), there should be 0103-1, 0103-2, 0103-3, and 0103-4. Other folders are like 0107-1, 0107-2, 0107-3, 0107-4. How do I go about doing this? I th...
List/Arrays - Check Dates
I'm trying to make a program that checks an array to make sure there are four folders with partially same names. So For a date like 0103 (jan 3rd), there should be 0103-1, 0103-2, 0103-3, and 0103-4. Other folders are like 0107-1, 0107-2, 0107-3, 0107-4. How do I go about doing this? I thought about using glob.glob (py...
[ "import os\n\ndef myfunc(date, num):\n for x in range(1, num+1):\n filename = str(date) + \"-\" + str(x)\n if os.path.exists(filename):\n print(filename+\" exists\")\n else:\n print(filename+\" does not exist\")\n\nmyfunc('0102', 3);\n\n0102-1 does not exist\n0102-2 doe...
[ 3, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0000518782_python_sorting.txt
Q: Thread specific data with webpy I'm writing a little web app with webpy, and I'm wondering if anyone has any information on a little problem I'm having. I've written a little ORM system, and it seems to be working pretty well. Ideally I'd like to stitch it in with webpy, but it appears that just using it as is cau...
Thread specific data with webpy
I'm writing a little web app with webpy, and I'm wondering if anyone has any information on a little problem I'm having. I've written a little ORM system, and it seems to be working pretty well. Ideally I'd like to stitch it in with webpy, but it appears that just using it as is causes thread issues (DB connection is i...
[ "We use SQLAlchemy with web.py and use hooks to create and close db connections per request. SQLAlchemy handles pooling, so not every connection is a tcp connection.\nThe thread local storage you want to use is web.ctx ie. any time you access web.ctx you only see properties set by that thread.\nOur code looks some...
[ 4, 2 ]
[]
[]
[ "database", "multithreading", "python", "web.py" ]
stackoverflow_0000459608_database_multithreading_python_web.py.txt
Q: django facebook connect missing libs? I'm trying to integrate some photo related functionality with my site and facebook. I checked out facebook connect and it seems like the way to go for this (since I don't want to make an app, just have users authenticate and then grab some content from facebook to integrate in...
django facebook connect missing libs?
I'm trying to integrate some photo related functionality with my site and facebook. I checked out facebook connect and it seems like the way to go for this (since I don't want to make an app, just have users authenticate and then grab some content from facebook to integrate into our site) First of all, if you think the...
[ "I've just added the missing file folks. Sorry for the inconveniences. :/\n", "the solution proposeed by van gale (removing the lines which reference the signals.py file) work well enough. I think I may end up needing to write my own signals.py eventually... I keep you updated.\nAnyway here's is the answer:\nRemo...
[ 2, 0 ]
[]
[]
[ "django", "facebook", "fbconnect", "integration", "python" ]
stackoverflow_0000503462_django_facebook_fbconnect_integration_python.txt
Q: How do I remove VSS hooks from a VS Web Site? I have a Visual Studio 2008 solution with 7 various projects included with it. 3 of these 'projects' are Web Sites (the kind of project without a project file). I have stripped all the various Visual Sourcesafe files from all the directories, removed the Scc reference...
How do I remove VSS hooks from a VS Web Site?
I have a Visual Studio 2008 solution with 7 various projects included with it. 3 of these 'projects' are Web Sites (the kind of project without a project file). I have stripped all the various Visual Sourcesafe files from all the directories, removed the Scc references in the SLN file and all the project files that ex...
[ "It probably is only trying to add it on your instance of VS. You have to remove the cache so VS thinks its no longer under SS\n\nunder file -> SourceControl -> Workspaces\nSelect the SS location\nEdit\nChoose the working folder\nRemove!\n\n", "Those things are pernicious! Visual Studio sticks links to SourceSaf...
[ 1, 1, 0 ]
[]
[]
[ "python", "visual_sourcesafe", "visual_studio" ]
stackoverflow_0000471190_python_visual_sourcesafe_visual_studio.txt
Q: Is there a Vim equivalent to the Linux/Unix "fold" command? I realize there's a way in Vim to hide/fold lines, but what I'm looking for is a way to select a block of text and have Vim wrap lines at or near column 80. Mostly I want to use this on comments in situations where I'm adding some text to an existing co...
Is there a Vim equivalent to the Linux/Unix "fold" command?
I realize there's a way in Vim to hide/fold lines, but what I'm looking for is a way to select a block of text and have Vim wrap lines at or near column 80. Mostly I want to use this on comments in situations where I'm adding some text to an existing comment that pushes it over 80 characters. It would also be nice i...
[ "gq\n\nIt's controlled by the textwidth option, see \":help gq\" for more info. \ngq will work on the current line by default, but you can highlight a visual block with Ctrl+V and format multiple lines / paragraphs like that.\ngqap does the current \"paragraph\" of text.\n", "Take a look at \":help =\" and \":hel...
[ 11, 0 ]
[]
[]
[ "comments", "formatting", "python", "vim", "word_wrap" ]
stackoverflow_0000516501_comments_formatting_python_vim_word_wrap.txt
Q: Python "property object has no attribute" Exception confirmation = property(_get_confirmation, _set_confirmation) confirmation.short_description = "Confirmation" When I try the above I get an Exception I don't quite understand: AttributeError: 'property' object has no attribute 'short_description' This was an an...
Python "property object has no attribute" Exception
confirmation = property(_get_confirmation, _set_confirmation) confirmation.short_description = "Confirmation" When I try the above I get an Exception I don't quite understand: AttributeError: 'property' object has no attribute 'short_description' This was an answer to another question on here but I couldn't comment o...
[ "The result of property() is an object where you can't add new fields or methods. It's immutable which is why you get the error.\nOne way to achieve what you want is with using four arguments to property():\nconfirmation = property(_get_confirmation, _set_confirmation, None, \"Confirmation.\")\n\nor put the explan...
[ 2 ]
[]
[]
[ "django", "properties", "python" ]
stackoverflow_0000520152_django_properties_python.txt
Q: Search Files& Dirs on Website Hi im coding to code a Tool that searchs for Dirs and files. have done so the tool searchs for dirs, but need help to make it search for files on websites. Any idea how it can be in python? A: Is this tool scanning the directories of your own website (in which the tool is running), ...
Search Files& Dirs on Website
Hi im coding to code a Tool that searchs for Dirs and files. have done so the tool searchs for dirs, but need help to make it search for files on websites. Any idea how it can be in python?
[ "Is this tool scanning the directories of your own website (in which the tool is running), or external sites?\n", "You can only do this if you have permission to browse directories on the site and no default page exists.\n", "You cannot get a directory listing on a website.\nPedantically, HTTP has no notion of ...
[ 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000520362_python.txt