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: Unwanted rounding when subtracting numpy arrays in Python I'm running into an issue with python automatically rounding very small numbers (smaller than 1e-8) when subtracting an array from an single float. Take this example: import numpy as np float(1) - np.array([1e-10, 1e-5]) Any thoughts on how to force p...
Unwanted rounding when subtracting numpy arrays in Python
I'm running into an issue with python automatically rounding very small numbers (smaller than 1e-8) when subtracting an array from an single float. Take this example: import numpy as np float(1) - np.array([1e-10, 1e-5]) Any thoughts on how to force python not to round? This is forcing me to divide by zero in so...
[ "Mostly, it's just the repr of numpy arrays that's fooling you.\nConsider your example above:\nimport numpy as np \nx = float(1) - np.array([1e-10, 1e-5]) \nprint x\nprint x[0]\nprint x[0] == 1.0\n\nThis yields:\n[ 1. 0.99999 ]\n0.99999999999\nFalse\n\nSo the first element isn't actually zero, it's just the p...
[ 6, 1 ]
[]
[]
[ "arrays", "numpy", "python", "rounding", "subtraction" ]
stackoverflow_0006867348_arrays_numpy_python_rounding_subtraction.txt
Q: Can I trigger a window action from the tree view in OpenERP? I'm trying to make a shortcut to get from a production order to the packing list for its raw materials in OpenERP. I can get the related window link to appear on the production order form, but I'd really like to be able to get to the packing list from th...
Can I trigger a window action from the tree view in OpenERP?
I'm trying to make a shortcut to get from a production order to the packing list for its raw materials in OpenERP. I can get the related window link to appear on the production order form, but I'd really like to be able to get to the packing list from the production order tree view by clicking on the Action button at t...
[ "Thanks to QGerome's help, I got this working. I found an example to follow in the hr module:\n <record id=\"action2\" model=\"ir.actions.act_window\">\n <field name=\"name\">Employee Hierarchy</field>\n <field name=\"type\">ir.actions.act_window</field>\n <field name=\"res_model\">hr.employ...
[ 6, 1 ]
[]
[]
[ "openerp", "python" ]
stackoverflow_0006852967_openerp_python.txt
Q: How can I remove \n's and \t's from a Python string in order to parse JSON? Python thinks I have the following text: "[\n\t{\n\t\t\"my_key\": 3}]" However, I want it to think this is JSON, so that I can load it with simplejson.dumps(). What is the Python way to parse / remove \n and \t from a string so that I can...
How can I remove \n's and \t's from a Python string in order to parse JSON?
Python thinks I have the following text: "[\n\t{\n\t\t\"my_key\": 3}]" However, I want it to think this is JSON, so that I can load it with simplejson.dumps(). What is the Python way to parse / remove \n and \t from a string so that I can parse it as JSON?
[ "If you want to load, why are you using dump?\n>>> import json\n>>> json.loads(\"[\\n\\t{\\n\\t\\t\\\"my_key\\\": 3}]\")\n[{u'my_key': 3}]\n\n", "Check out Python's replace method. Replace these items with a empty string and they will be gone. Be careful you don't chew up newlines you need.\n" ]
[ 8, 1 ]
[]
[]
[ "json", "python", "string", "unicode" ]
stackoverflow_0006867619_json_python_string_unicode.txt
Q: Regex to match lines in-between two specific lines, in Python I am trying to use regex to parse out some lines from text read in from a file. I know this could be done by reading in the file, line-by-line, but I like the elegance in capturing all the relevant bits of info in a single regex match. The example file ...
Regex to match lines in-between two specific lines, in Python
I am trying to use regex to parse out some lines from text read in from a file. I know this could be done by reading in the file, line-by-line, but I like the elegance in capturing all the relevant bits of info in a single regex match. The example file contents: --- title: a title layout: page --- here's some text ===...
[ "The end of line markers are considered whitespace so you can use the construct \\s+ to match the end of line (and other whitespace) that is platform independent.\n", "The sequence (\\r\\n|\\r|\\n) will match all 'normal' line endings (Windows, old Mac, and *nix, respectively).\n" ]
[ 4, 3 ]
[]
[]
[ "newline", "python", "regex" ]
stackoverflow_0006868141_newline_python_regex.txt
Q: join new tuple to first list of tuples in Python I am newbie to python and don't know how to do this. I have a list of tuples which represent data and another list which represents header. I need a set of combinations into new tuples to look from this. data = [( 1, 'a'),( 2, 'b'),( 3, 'c'),( 4, 'd'),(5, 'e')] hea...
join new tuple to first list of tuples in Python
I am newbie to python and don't know how to do this. I have a list of tuples which represent data and another list which represents header. I need a set of combinations into new tuples to look from this. data = [( 1, 'a'),( 2, 'b'),( 3, 'c'),( 4, 'd'),(5, 'e')] header = ["ID", "MyData"] into this newdata = [("ID", "M...
[ "Here:\ndata.insert(0, tuple(header))\n\nNote that this will modify data in-place. You can achieve the same results without modifying data like so:\nnewdata = [tuple(header)]\nnewdata.extend(data)\n\n", "Creating a completely new value, without any temporaries:\n[tuple(header)] + data\n\nAddition of two lists con...
[ 5, 1, 0 ]
[]
[]
[ "arrays", "list", "python", "tuples" ]
stackoverflow_0006868145_arrays_list_python_tuples.txt
Q: Views and models as python package cannot be resolved I'm fairly new to Django, and I try to get the hang of using modules for views and models. Strangely enough, the URls work fine. My app structure is templatetags/ urls/ views/ models.py tests.py The views-dir has an __init__.py, and animals.py, containing one...
Views and models as python package cannot be resolved
I'm fairly new to Django, and I try to get the hang of using modules for views and models. Strangely enough, the URls work fine. My app structure is templatetags/ urls/ views/ models.py tests.py The views-dir has an __init__.py, and animals.py, containing one view. from myapp.models import Animal from django.shortcu...
[ "Well, generally, you don't need to import myapp.views.animals. The URL dispatcher imports the required view as necessary when the regex matches a requested URL, as per: https://docs.djangoproject.com/en/dev/topics/http/urls/#how-django-processes-a-request.\nGenerally speaking, I would expect your urls.py to look s...
[ 1, 0 ]
[]
[]
[ "django", "module", "python" ]
stackoverflow_0006863322_django_module_python.txt
Q: Python shlex.split(), ignore single quotes How, in Python, can I use shlex.split() or similar to split strings, preserving only double quotes? For example, if the input is "hello, world" is what 'i say' then the output would be ["hello, world", "is", "what", "'i", "say'"]. A: import shlex def newSplit(value): ...
Python shlex.split(), ignore single quotes
How, in Python, can I use shlex.split() or similar to split strings, preserving only double quotes? For example, if the input is "hello, world" is what 'i say' then the output would be ["hello, world", "is", "what", "'i", "say'"].
[ "import shlex\n\ndef newSplit(value):\n lex = shlex.shlex(value)\n lex.quotes = '\"'\n lex.whitespace_split = True\n lex.commenters = ''\n return list(lex)\n\nprint newSplit('''This string has \"some double quotes\" and 'some single quotes'.''')\n\n", "You can use shlex.quotes to control which char...
[ 16, 8 ]
[]
[]
[ "python", "quotes", "shlex", "split" ]
stackoverflow_0006868382_python_quotes_shlex_split.txt
Q: Perl Vs Python variable Scoping - gotchas to be aware of While investigating scoping in Perl and Python, I came across a silent scoping related behavior of Perl that can cause bugs very difficult to trace. Specifically for programmers who are new to the language and not fully aware of all it's nuances. I have pr...
Perl Vs Python variable Scoping - gotchas to be aware of
While investigating scoping in Perl and Python, I came across a silent scoping related behavior of Perl that can cause bugs very difficult to trace. Specifically for programmers who are new to the language and not fully aware of all it's nuances. I have provided example code for both Perl and Python to illustrate how...
[ "The line $x = shift in your second Perl example just overwrites a global, lexically-scoped variable, same as if you would add global x to your Python code.\nThis has nothing to do with dynamic scoping, and there are many other languages with the same behaviour as Perl - I'd consider Python the odd man out here for...
[ 9 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0006868846_perl_python.txt
Q: Audio Recording in Python I want to record short audio clips from a USB microphone in Python. I have tried pyaudio, which seemed to fail communicating with ALSA, and alsaaudio, the code example of which produces an unreadable files. So my question: What is the easiest way to record clips from a USB mic in Python? ...
Audio Recording in Python
I want to record short audio clips from a USB microphone in Python. I have tried pyaudio, which seemed to fail communicating with ALSA, and alsaaudio, the code example of which produces an unreadable files. So my question: What is the easiest way to record clips from a USB mic in Python?
[ "This script records to test.wav while printing the current amplitute:\nimport alsaaudio, wave, numpy\n\ninp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE)\ninp.setchannels(1)\ninp.setrate(44100)\ninp.setformat(alsaaudio.PCM_FORMAT_S16_LE)\ninp.setperiodsize(1024)\n\nw = wave.open('test.wav', 'w')\nw.setnchannels(1)\nw.set...
[ 13 ]
[]
[]
[ "alsa", "audio_recording", "microphone", "pyaudio", "python" ]
stackoverflow_0006867675_alsa_audio_recording_microphone_pyaudio_python.txt
Q: Python Syntax / List Slicing Question: What does this syntax mean? lines = file('info.csv','r').readlines() counts = [] for i in xrange(4): counts.append(fromstring(lines[i][:-2],sep=',')[0:-1]) If anyone can explain this code to me, it would be greatly appreciated. I can't seem to find more advanced example...
Python Syntax / List Slicing Question: What does this syntax mean?
lines = file('info.csv','r').readlines() counts = [] for i in xrange(4): counts.append(fromstring(lines[i][:-2],sep=',')[0:-1]) If anyone can explain this code to me, it would be greatly appreciated. I can't seem to find more advanced examples on slicing--only very simple ones that don't explain this situation. T...
[ "A slice takes the form o[start:stop:step], all of which are optional. start defaults to 0, the first index. stop defaults to len(o), the closed upper bound on the indicies of the list. step defaults to 1, including every value of the list.\nIf you specify a negative value, it represents an offset from the end of t...
[ 5, 5, 2 ]
[]
[]
[ "delimiter", "list", "python", "slice" ]
stackoverflow_0006868941_delimiter_list_python_slice.txt
Q: How can I override the index view (sites.py) for Django admin? I want to override the index view present in class AdminSite in django.contrib.admin.sites. What I want to do through this is I want to check here if user is superuser then show index.html template with all models otherwise if user is an normal staff u...
How can I override the index view (sites.py) for Django admin?
I want to override the index view present in class AdminSite in django.contrib.admin.sites. What I want to do through this is I want to check here if user is superuser then show index.html template with all models otherwise if user is an normal staff user then show him/her a test.html template with different content.
[ "The auth package lets you set up permissions on a model-by-model basis out of the box. There's not necessarily a need to override the view. See https://docs.djangoproject.com/en/dev/topics/auth/#permissions\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "django_views", "python" ]
stackoverflow_0006869042_django_django_admin_django_views_python.txt
Q: Python and GTK+: How to create garbage collector friendly objects? I started writing a small application in Python with GTK+ as my widget toolkit. Recently I decided to do some memory optimization and noticed that a most of PyGTK objects I create never gets released by garbage collector. This number keeps growing ...
Python and GTK+: How to create garbage collector friendly objects?
I started writing a small application in Python with GTK+ as my widget toolkit. Recently I decided to do some memory optimization and noticed that a most of PyGTK objects I create never gets released by garbage collector. This number keeps growing even if I open a window and properly destroy it afterward. Can someone p...
[ "Did you call .destroy()?\nAccording to the gtk.Widget.destroy docu GTK maintains a list of toplevel windows that will keep a reference alive.\nAnd in case you use any Python destructors, they can also prevent cyclic references from being freed.\n" ]
[ 0 ]
[]
[]
[ "garbage_collection", "gtk", "pygtk", "python" ]
stackoverflow_0006866578_garbage_collection_gtk_pygtk_python.txt
Q: python regex to split on certain patterns with skip patterns I want to split a Python string on certain patterns but not others. For example, I have the string Joe, Dave, Professional, Ph.D. and Someone else I want to split on \sand\s and ,, but not , Ph.D. How can this be accomplished in Python regex? A: You c...
python regex to split on certain patterns with skip patterns
I want to split a Python string on certain patterns but not others. For example, I have the string Joe, Dave, Professional, Ph.D. and Someone else I want to split on \sand\s and ,, but not , Ph.D. How can this be accomplished in Python regex?
[ "You can use:\nre.split(r'\\s+and\\s+|,(?!\\s*Ph\\.D\\.)\\s*', 'Joe, Dave, Professional, Ph.D. and Someone else')\n\nResult:\n['Joe', 'Dave', 'Professional, Ph.D.', 'Someone else']\n\n", "You can basically do this with either regular expressions or just regular\nstring manipulation operations, (i.e. str.split())\...
[ 3, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006868345_python_regex.txt
Q: Something like the wx.MultiChoiceDialog in a panel instead of a dialog I'd like to use the list (with checkboxes next to each item) that is contained in the wxMultiChoice dialog in a panel. Is that possible? A: The equivalent to a wx.MultiChoiceDialog is the wx.CheckListBox import wx class MyFrame(wx.Frame): ...
Something like the wx.MultiChoiceDialog in a panel instead of a dialog
I'd like to use the list (with checkboxes next to each item) that is contained in the wxMultiChoice dialog in a panel. Is that possible?
[ "The equivalent to a wx.MultiChoiceDialog is the wx.CheckListBox\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init__(self, parent):\n wx.Frame.__init__(self, parent, -1)\n\n sampleList = ['zero', 'one', 'two', 'three', 'four', 'five',\n 'six', 'seven', 'eight', 'nine', 'ten',...
[ 0 ]
[]
[]
[ "python", "user_interface", "wxpython", "wxwidgets" ]
stackoverflow_0006864682_python_user_interface_wxpython_wxwidgets.txt
Q: GeoDjango distance queries returning incorrect results I just got GeoDjango up and running on my development machine. Problem is that I can't get a distance query to work correctly. No matter what SRID I use, the distance results are totally off. Here's an example. >>> from django.contrib.gis.measure import D >>> ...
GeoDjango distance queries returning incorrect results
I just got GeoDjango up and running on my development machine. Problem is that I can't get a distance query to work correctly. No matter what SRID I use, the distance results are totally off. Here's an example. >>> from django.contrib.gis.measure import D >>> from app.models import Place >>> from django.contrib.gis.geo...
[ "I hate to be answering my own question, but no one else stepped up to the plate and I figured out the solution.\nI delved into PostGIS to isolate the issue to either the location database itself or to Django. So I converted the Django ORM query I had been using above into the ideal query that I would have expected...
[ 9 ]
[]
[]
[ "django", "geodjango", "postgis", "postgresql", "python" ]
stackoverflow_0006853800_django_geodjango_postgis_postgresql_python.txt
Q: Google app engine fails on OSX Lion with python I am using Google App Engine and just updated to Lion on my mac. I am using eclipse with Pydev. Now as soon as I updated I have been unable to launch the dev server. I get the stack trace below. Anyone else with the same problem? Traceback (most recent call last): ...
Google app engine fails on OSX Lion with python
I am using Google App Engine and just updated to Lion on my mac. I am using eclipse with Pydev. Now as soon as I updated I have been unable to launch the dev server. I get the stack trace below. Anyone else with the same problem? Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Conte...
[ "I ended up uninstalling GAE and eclipse and reinstalling. It works now.\nFrom looking at the stack trace it seems like the PyDev plugin was the culprit\n", "I had the same problem, but I just pointed my library stuff to 2.7 in the same root, e.g. \n/System/Library/Frameworks/Python.framework/Versions/2.6/...\n/S...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "osx_lion", "python" ]
stackoverflow_0006822624_google_app_engine_osx_lion_python.txt
Q: Outputting a Python dictionary with values in an array to a CSV file. First question here, please forgive the various and sundry errors I'm sure to make. I've been working on this for awhile, and I admit to being stumped - dictionaries in a general sense make my head hurt a bit, as my background is more on the sta...
Outputting a Python dictionary with values in an array to a CSV file.
First question here, please forgive the various and sundry errors I'm sure to make. I've been working on this for awhile, and I admit to being stumped - dictionaries in a general sense make my head hurt a bit, as my background is more on the statistical side, where data has pretty explicit structure. I'm working in Pyt...
[ "Replace\nwriter.writerow([node,value])\nwith\nwriter.writerow([node]+value)\n", "You're passing a list containing a name and a list with two numbers to writer.writerow. To get what you want, flatten the list into just a list of the name and numbers. Simple approach:\nfor node, value in output.items():\n write...
[ 2, 1 ]
[]
[]
[ "dictionary", "export_to_csv", "python" ]
stackoverflow_0006870103_dictionary_export_to_csv_python.txt
Q: generate pdf from text file in python Is there a solution to create pdf file from txt, maybe in ReportLab? To produce like this +------+-------+------------+ | Name | Age | Nickname | +======+=======+============+ | 107 | Ella | Fitzgerald | +------+-------+------------+ | 108 | Louis | Armstrong | +-----...
generate pdf from text file in python
Is there a solution to create pdf file from txt, maybe in ReportLab? To produce like this +------+-------+------------+ | Name | Age | Nickname | +======+=======+============+ | 107 | Ella | Fitzgerald | +------+-------+------------+ | 108 | Louis | Armstrong | +------+-------+------------+ | 109 | Miles | ...
[ "ReportLab is an option. LaTeX is another option.\n", "EMACS org mode make this task exceedingly simple. Org makes it easy to format tables in plain ASCII. Any line with ‘|’ as the first non-whitespace character is considered part of a table. ‘|’ is also the column separator.\nC-c C-e p (org-export-as-pdf)\n ...
[ 3, 0, 0 ]
[]
[]
[ "module", "pdf", "python", "reportlab", "text_processing" ]
stackoverflow_0006869629_module_pdf_python_reportlab_text_processing.txt
Q: Buildout vs virtualenv + pip for django? Pros and cons? I'm personally using buildout for my django projects but thinking of switching to virtualenv + pip for its simplicity. A: At the core, buildout and pip+virtualenv do the same. They both use python packages, install them, isolate them from the rest of your p...
Buildout vs virtualenv + pip for django?
Pros and cons? I'm personally using buildout for my django projects but thinking of switching to virtualenv + pip for its simplicity.
[ "At the core, buildout and pip+virtualenv do the same. They both use python packages, install them, isolate them from the rest of your python environment, handle dependencies (through setup.py) and so on.\nBuildout does more. Which, naturally, means a bit more configuration than with pip. You'll have to figure out ...
[ 12 ]
[]
[]
[ "buildout", "django", "pip", "python", "virtualenv" ]
stackoverflow_0006865896_buildout_django_pip_python_virtualenv.txt
Q: Python GUI hangs during eval So, I'm building a GUI in Python using Tkinter which will be used to, during runtime, load a textfile listing a number of python scripts. The scripts will then be executed and return a number indicating whether they were successful or not (returncode will not be returned with sys.exit,...
Python GUI hangs during eval
So, I'm building a GUI in Python using Tkinter which will be used to, during runtime, load a textfile listing a number of python scripts. The scripts will then be executed and return a number indicating whether they were successful or not (returncode will not be returned with sys.exit, script files will have a function...
[ "There could be 2 ways. \n\nUse Python multiprocessing library http://docs.python.org/library/multiprocessing.html\nPython thread. \n\nOption 1 is good compared to Option 2 due to Python's GIL.\nfrom multiprocessing import Process\ndef runtest(test):\n exec 'import ' + test\n func=test+'.'+test+'()'\n return ...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006870349_python_tkinter.txt
Q: What is the 'Python' way of creating class attributes I am a beginner in Python. I would like to know which is the better way of creating attributes... In the first method I am explicitly defining the attribute and then having a method return a value to it: class A: def __init__(self, number): self.a =...
What is the 'Python' way of creating class attributes
I am a beginner in Python. I would like to know which is the better way of creating attributes... In the first method I am explicitly defining the attribute and then having a method return a value to it: class A: def __init__(self, number): self.a = self._meth( number) def _meth(self, num): #so...
[ "Note that you're creating object attributes, not class attributes (Those go directly in the class body). If meth is only called on initialization, I'd prefer:\nclass A(object):\n def __init__():\n # Some executable code here\n self.a = 8\n\nOtherwise, if your class can't handle meth being called...
[ 3, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006870106_python.txt
Q: iterating dictionary and fetching values from inner dictionaries am trying to build a logic which am not quit sure how to do with python. I have the following dictionary {datetime.datetime(2011, 7, 18, 13, 59, 25): (u'hello-world', u'hello world'), datetime.datetime(2011, 7, 17, 15, 45, 54): (u'mazban-archetictur...
iterating dictionary and fetching values from inner dictionaries
am trying to build a logic which am not quit sure how to do with python. I have the following dictionary {datetime.datetime(2011, 7, 18, 13, 59, 25): (u'hello-world', u'hello world'), datetime.datetime(2011, 7, 17, 15, 45, 54): (u'mazban-archeticture', u'mazban arch'), datetime.datetime(2011, 7, 7, 15, 51, 49): (u'blo...
[ "In python when you use 'for x in dic' it is the same as to use 'for x in dic.keys()' - you are iterating trough only keys not (key,value) pairs. \nTo do what you want you can take a look at the items() and iteritems() dictionary methods, they allows you to get access to (key,value) pairs:\nfor key,value in dic.ite...
[ 6, 0 ]
[]
[]
[ "dictionary", "iterator", "python" ]
stackoverflow_0006870501_dictionary_iterator_python.txt
Q: How to get a child attributes in parent object I'm fairly new to Django and it seems like there might be an easy and obvious way to do this, but if so I haven't been able to find it. (Slightly simplified code) I have a primary class class Article(models.Model): ... and a secondary class class Headline(models....
How to get a child attributes in parent object
I'm fairly new to Django and it seems like there might be an easy and obvious way to do this, but if so I haven't been able to find it. (Slightly simplified code) I have a primary class class Article(models.Model): ... and a secondary class class Headline(models.Model): article = models.ForeignKey(Article) ...
[ "If you have a single instance of Article, then you can get all of the headline objects with\narticle.headline_set.all()\n\nThis returns a QuerySet that you can use just like any other.\nEdit: If you want to get the actual headline value, then just like for any other query set you will need to get a single instance...
[ 5, 4, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006861890_django_python.txt
Q: Boost.Python: Take possession of argument If I have a function that takes possession of one of the arguments, are there any call policies that I should use when I expose that function with Boost.Python? void func(MyClass* obj) { // Code that takes possession of `obj` } A: I think you can use boost::weak_ptr....
Boost.Python: Take possession of argument
If I have a function that takes possession of one of the arguments, are there any call policies that I should use when I expose that function with Boost.Python? void func(MyClass* obj) { // Code that takes possession of `obj` }
[ "I think you can use boost::weak_ptr.\nusing boost::shared_ptr;\nusing boost::weak_ptr;\n\nfunc (weak_ptr<MyClass> wp)\n{\n shared_ptr<MyClass> sp = wp.lock ();\n if (sp)\n // sp stays alive until it goes out of scope or is reset\n}\n\nBasically, this is the example offered in the documentation of boost::weak_...
[ 1 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0006870261_boost_boost_python_c++_python.txt
Q: Why is unpack so slow? I have a simple example: def __init__(self,string): self.string = string def UI32(self): tmp = self.string[:4] self.string = self.string[4:] return unpack(">I",tmp)[0] data = file.read() U = UI(data) for i in range(60000): test = UI32() Total time: 22 seconds! A: Fi...
Why is unpack so slow?
I have a simple example: def __init__(self,string): self.string = string def UI32(self): tmp = self.string[:4] self.string = self.string[4:] return unpack(">I",tmp)[0] data = file.read() U = UI(data) for i in range(60000): test = UI32() Total time: 22 seconds!
[ "First of all, I cannot reproduce the 22s on my system (Intel Nehalem, 64-bit Ubuntu, Python 2.6.5).\nThe following takes 1.4s (this is essentially your code with some blanks filled in by me):\nimport struct\n\nclass UI(object):\n def __init__(self,string):\n self.string = string\n\n def UI32(self):\n ...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0006870992_python.txt
Q: fatal python error pygame parachute I have written a small program in WindowsXP-python-pygame. It runs fine when I run it in the dos. Then, I tried to create a windows executable using py2exe. .exe was created without any issue. Initially on running the executable, I got a NotImplemented error which went away afte...
fatal python error pygame parachute
I have written a small program in WindowsXP-python-pygame. It runs fine when I run it in the dos. Then, I tried to create a windows executable using py2exe. .exe was created without any issue. Initially on running the executable, I got a NotImplemented error which went away after I copied some dll files from pygame fol...
[ "I got it working. Edited the line extra_data in the following place: \npygame.org/wiki/Pygame2exe \n\nto: \nself.extra_datas = [\"freesansbold.ttf\",\n \"SDL.dll\",\n \"SDL_ttf.dll\",\n \"libfreetype-6.dll\",\n \"zlib1.dll\"]\n\nThis works...
[ 1 ]
[]
[]
[ "py2exe", "pygame", "python" ]
stackoverflow_0006646154_py2exe_pygame_python.txt
Q: An elegant way of overloading Python class properties Consider a base class: class A(object): def __init__(self, x): self._x = x def get_x(self): #... return self._x def set_x(self, x): #... self._x = x x = property(get_x, set_x) and a derived class: class B(A): def...
An elegant way of overloading Python class properties
Consider a base class: class A(object): def __init__(self, x): self._x = x def get_x(self): #... return self._x def set_x(self, x): #... self._x = x x = property(get_x, set_x) and a derived class: class B(A): def set_x(self, x): #... self._x = x**2 x = pr...
[ "Add an extra layer of indirection (i.e. use a hook):\nclass A(object):\n def __init__(self, x):\n self._x = x\n\n # Using a _get_hook is not strictly necessary for your problem...\n def _get_hook(self):\n return self._x\n def get_x(self):\n return self._get_hook()\n\n # By deleg...
[ 3, 2 ]
[]
[]
[ "overloading", "properties", "python" ]
stackoverflow_0006870616_overloading_properties_python.txt
Q: How to plot 2 variables on a plane Let's say I have an equation: x**2 + y**2 - 4 = 0 How can I see the circle using sympy, matplotplib or another python solution? I know in sympy I can from sympy import Plot from sympy import Symbol x = Symbol('x') y = Symbol('y') Plot(x**2 + y**2 - 4) But then I get z = x**2 + ...
How to plot 2 variables on a plane
Let's say I have an equation: x**2 + y**2 - 4 = 0 How can I see the circle using sympy, matplotplib or another python solution? I know in sympy I can from sympy import Plot from sympy import Symbol x = Symbol('x') y = Symbol('y') Plot(x**2 + y**2 - 4) But then I get z = x**2 + y**2 - 4, a 3D graph instead of the plan...
[ "Yes KillianDS, I now understand this is a duplicate of Is it possible to plot implicit equations using Matplotlib?\nThough I still don't know how to do it in sympy. The answer for matplotlib would be:\nimport matplotlib.pyplot\nfrom numpy import arange\nfrom numpy import meshgrid\n\ndelta = 0.025\nxrange = arange(...
[ 0 ]
[]
[]
[ "matplotlib", "python", "sympy" ]
stackoverflow_0006870472_matplotlib_python_sympy.txt
Q: Python: is there a TrueType font library? I need to extract information from .ttf files. Such as the font's name and style. Maybe some more info in future. How to do this in Python more easily than looking for a specification and coding a lot? A short code example would be great. A: Check this out: How to extrac...
Python: is there a TrueType font library?
I need to extract information from .ttf files. Such as the font's name and style. Maybe some more info in future. How to do this in Python more easily than looking for a specification and coding a lot? A short code example would be great.
[ "Check this out: How to extract font names from TTF files using Python and our old friend 'the command line'\nNote: This took me about 10 seconds to google...\n" ]
[ 5 ]
[]
[]
[ "python", "truetype" ]
stackoverflow_0006871385_python_truetype.txt
Q: Python or Jython for Django based application? We are going to start developing Django based application. It requires speed optimisation (need to serve k+ requests/sec), n number of nodes with HAproxy and PostgreSQL load-balancing. Presently we consider using Python, Apache, memcached Jython, Glassfish The appli...
Python or Jython for Django based application?
We are going to start developing Django based application. It requires speed optimisation (need to serve k+ requests/sec), n number of nodes with HAproxy and PostgreSQL load-balancing. Presently we consider using Python, Apache, memcached Jython, Glassfish The application should scale overtime, Python or Jython. Any ...
[ "Which language you know better?\nJVM based languages are faster than Python but any access to data(sql,nosql) is 100X slower than Python or Java. \nYou will have problems with the database first.\nConcentrate on that first.\n\nseparate frequently changing data from static data\nbe ready to split data/databases\nth...
[ 4 ]
[]
[]
[ "apache", "glassfish", "jython", "memcached", "python" ]
stackoverflow_0006871097_apache_glassfish_jython_memcached_python.txt
Q: python.el shell and execute buffer I am using the python.el from fgallina python.el github There is a long list of features but I am unaware of how to use them. EDIT: Found this mode was working, however didn't automatically open the interpreter went the information was sent there. How can I send/load my current p...
python.el shell and execute buffer
I am using the python.el from fgallina python.el github There is a long list of features but I am unaware of how to use them. EDIT: Found this mode was working, however didn't automatically open the interpreter went the information was sent there. How can I send/load my current python buffer to be evaluated? I am tryin...
[ "For your first question: Usually you can load a buffer/file using C-c C-l. (Just tested this for python.el, and it works for this one as well) This will send the file to the inferior python process -- so you should open the *Python* buffer to see the results. The *Python* buffer is also your regular python interpr...
[ 6 ]
[]
[]
[ "emacs", "mode", "python" ]
stackoverflow_0006867834_emacs_mode_python.txt
Q: Select random values from two vector (python) I have two vectors A B which are coupled, I mean that they define a certain scalar field at a given position. I want to select 1000 random items from A and plot them versus other the other 1000 B coupled items. With this code A_rand=random.sample(A,1000) I se...
Select random values from two vector (python)
I have two vectors A B which are coupled, I mean that they define a certain scalar field at a given position. I want to select 1000 random items from A and plot them versus other the other 1000 B coupled items. With this code A_rand=random.sample(A,1000) I select 1000 random values of A. For example they are ...
[ "You can select indexes, not items:\nrand = random.sample(range(len(A)), 1000)\n\nThen you can use A[rand[i]] and B[rand[i]].\nFor all selected items:\nA_rand = [A[x] for x in rand]\nB_rand = [B[x] for x in rand]\n\n", "You can also couple them in beforehand with zip and then select the sample,\nrand = random.sam...
[ 2, 2 ]
[]
[]
[ "arrays", "python", "random" ]
stackoverflow_0006871503_arrays_python_random.txt
Q: Python coding style enforcement Possible Duplicate: Tool to enforce python code style/standards Are there any tools to enforce code standards in Python and print out a list of violations? I am looking for a tool which similar to checkstyle in Java. A: pylint pyflakes pychecker
Python coding style enforcement
Possible Duplicate: Tool to enforce python code style/standards Are there any tools to enforce code standards in Python and print out a list of violations? I am looking for a tool which similar to checkstyle in Java.
[ "pylint\npyflakes\npychecker\n" ]
[ 8 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0006871608_coding_style_python.txt
Q: Output of time command for a python script I executed a python script on the server with the time command like time python myscript.py The time output was : 312.90user 15.57system 2:10:42elapsed 4%CPU (0avgtext+0avgdata 0maxresident)k 0inputs+0outputs (1major+152440minor)pagefaults 0swaps So, does that mean the ...
Output of time command for a python script
I executed a python script on the server with the time command like time python myscript.py The time output was : 312.90user 15.57system 2:10:42elapsed 4%CPU (0avgtext+0avgdata 0maxresident)k 0inputs+0outputs (1major+152440minor)pagefaults 0swaps So, does that mean the script took 2 hours 10 minutes and 42 seconds to...
[ "To put it simply:\n\"user\" is the time the cpu spent running non-system calls in your myscript.py. These are the python codes.\n\"system\" is the time the cpu spent serving system calls made by your myscript.py. These are code that call the c library functions like open, write, etc., for example.\n\"elapsed\" is...
[ 0, 0 ]
[]
[]
[ "python", "time", "unix" ]
stackoverflow_0006871843_python_time_unix.txt
Q: Pyphantomjs makes python crash I'm just trying to open a web page with pyphantomjs, but it makes python crash. I don't know if there is a problem or if I am just using it wrong, as the documentation is one of the crappiest I've seen... My code: from pyphantomjs import webpage if __name__ == '__main__': wp = w...
Pyphantomjs makes python crash
I'm just trying to open a web page with pyphantomjs, but it makes python crash. I don't know if there is a problem or if I am just using it wrong, as the documentation is one of the crappiest I've seen... My code: from pyphantomjs import webpage if __name__ == '__main__': wp = webpage.WebPage() wp.open("www.go...
[ "Did you do a Google search for \"PhantomJS API reference\" or \"PyPhantomJS API reference\"? Both search terms yield good results as the first link. I don't know how you can say the documentation is bad, as it's all over the place if you simply look for it.\nIf you had read the project description1, you would know...
[ 1 ]
[]
[]
[ "crash", "pyqt", "python" ]
stackoverflow_0006742662_crash_pyqt_python.txt
Q: Share video data between C++ and Python I have a USB camera (uEye) which has a C++ interface allowing you to configure some features of the camera. The C++ program can read the image data from the camera and store it somewhere in pre-allocated memory. All of this runs under Windows. Python with numpy gives me a si...
Share video data between C++ and Python
I have a USB camera (uEye) which has a C++ interface allowing you to configure some features of the camera. The C++ program can read the image data from the camera and store it somewhere in pre-allocated memory. All of this runs under Windows. Python with numpy gives me a simple environment to manipulate images and spe...
[ "There was a recent post on the PyPy blog about real-time video processing. In the example they use mplayer to be grab and display video, which might be preferable to trying to interface with your C++ program (assuming it works with your webcam). If not, thinking along those lines a simple solution is to just conne...
[ 3, 2 ]
[]
[]
[ "c++", "ipc", "python", "windows" ]
stackoverflow_0006871537_c++_ipc_python_windows.txt
Q: How to modify the "-h" output.when using optparse.optionParser() Is there a neat way to modify the "-h" output when usion optparse? Basically there's a load of additional text I want to add in addition to the "freebie" usage instructions that are ouput. Or is this completely the wrong approach to doing this? A: ...
How to modify the "-h" output.when using optparse.optionParser()
Is there a neat way to modify the "-h" output when usion optparse? Basically there's a load of additional text I want to add in addition to the "freebie" usage instructions that are ouput. Or is this completely the wrong approach to doing this?
[ "optparse.OptionParser - see description for parameters usage, prog and epilog.\n" ]
[ 2 ]
[]
[]
[ "command_line", "command_line_arguments", "optparse", "python" ]
stackoverflow_0006872458_command_line_command_line_arguments_optparse_python.txt
Q: Python api for taking picture from a webcam on a Linux machine Im using ubuntu 11.04 on my Lenovo Thinkpad machine. Is there a python api for taking a picture programmatically from the webcam ? . Some example would be really appreciated. Please Help Thank You A: opencv has python wrappers http://opencv.willowgar...
Python api for taking picture from a webcam on a Linux machine
Im using ubuntu 11.04 on my Lenovo Thinkpad machine. Is there a python api for taking a picture programmatically from the webcam ? . Some example would be really appreciated. Please Help Thank You
[ "opencv has python wrappers\nhttp://opencv.willowgarage.com/documentation/python/index.html\n", "There is a package here: http://pypi.python.org/pypi/v4l2\nYou might also want to study the Video4Linux 2 API specification.\n" ]
[ 4, 2 ]
[]
[]
[ "linux", "python", "ubuntu" ]
stackoverflow_0006872725_linux_python_ubuntu.txt
Q: Intersection of infinite volumes of any dimension I need code/text/google keywords/other resources to implement this class. Speed doesn't matter. It should just work for any number of dimensions. class InfiniteVolume: # such as a point, line, plane, volume, 4d-volume def __init__(self, points): # two points fo...
Intersection of infinite volumes of any dimension
I need code/text/google keywords/other resources to implement this class. Speed doesn't matter. It should just work for any number of dimensions. class InfiniteVolume: # such as a point, line, plane, volume, 4d-volume def __init__(self, points): # two points for line, three points for plane, etc. self.point...
[ "You're trying to represent an N-dimensional space embedded in an M-dimensional space. For example, (N=2, M=3) is a plane in a 3-dimensional \"world\".\nYou can implement a defining set of points if you like, but the natural way to represent such a subspace is with a set of linear equations or basis vectors, so thi...
[ 6 ]
[]
[]
[ "intersection", "math", "multidimensional_array", "python" ]
stackoverflow_0006871686_intersection_math_multidimensional_array_python.txt
Q: how to download using django? I have a download link on one of my webpage in django. When i download a audio file of 75mb it downloads but nothing in the audio, its 0bytes. this is my code: from django.core.servers.basehttp import FileWrapper import mimetypes rec_file = settings.WEB_PATH + "/media/recording/" + f...
how to download using django?
I have a download link on one of my webpage in django. When i download a audio file of 75mb it downloads but nothing in the audio, its 0bytes. this is my code: from django.core.servers.basehttp import FileWrapper import mimetypes rec_file = settings.WEB_PATH + "/media/recording/" + filename wrapper = FileWrapper( ope...
[ "Couldn't say what's wrong with your code, but you shouldn't be doing that anyways. You should serve static files directly from Apache or use X-Sendfile.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006872275_django_python.txt
Q: 75 MB Helloworld with py2app ! I'm testing different languages to developp a desktop application for Mac&Windows. I thought that Python+Wx worth a try so I wrote a simple hello world. Then, I tried the py2app to package my application as a Mac application. What a surprise to find that my hellworld.app weight as m...
75 MB Helloworld with py2app !
I'm testing different languages to developp a desktop application for Mac&Windows. I thought that Python+Wx worth a try so I wrote a simple hello world. Then, I tried the py2app to package my application as a Mac application. What a surprise to find that my hellworld.app weight as much as 75 MB !! (then I have an erro...
[ "I would highly remmoend you using PyINstaller, which can be found here: link\nit works like a chamr for me so far and it support most of the major libraries:\nwxpython pyqt and even django (although i dont really understand the whole django support thing ;-) )\n\nPyInstaller is a program that converts (packages) P...
[ 3 ]
[]
[]
[ "py2app", "python", "wxpython" ]
stackoverflow_0006843156_py2app_python_wxpython.txt
Q: Is there a better way to check Python code for a syntax errors without external modules? As the title says, is there a better way to check a Python source for syntax errors without the use of external modules? I mean, in sense of a more Pythonic style or a more performant way. def CheckSyntax(source, raw = False):...
Is there a better way to check Python code for a syntax errors without external modules?
As the title says, is there a better way to check a Python source for syntax errors without the use of external modules? I mean, in sense of a more Pythonic style or a more performant way. def CheckSyntax(source, raw = False): lines = source.count("\n") source += "\nThis is a SyntaxError" # add a syntax error ...
[ "exec doesn't sound like a particularly good idea. What if the script in question has side effects (e.g. creates or modifies files) or takes a long time to run?\nTake a look at the compile function and the parser module.\n" ]
[ 6 ]
[]
[]
[ "python", "syntax_checking", "syntax_error" ]
stackoverflow_0006873094_python_syntax_checking_syntax_error.txt
Q: Python: special characters giving me problems (from PDFminer) I used pdf2text from PDFminer to reduce a PDF to text. Unfortunately it contains special characters. Let me show output from my console >>>a=pdf_to_text("ap.pdf") heres a sample of it, a little truncated >>>a[5000:5500] 'f one architect. Decades .........
Python: special characters giving me problems (from PDFminer)
I used pdf2text from PDFminer to reduce a PDF to text. Unfortunately it contains special characters. Let me show output from my console >>>a=pdf_to_text("ap.pdf") heres a sample of it, a little truncated >>>a[5000:5500] 'f one architect. Decades ...... but to re\xef\xac\x82ect\none set of design ideas, than to have on...
[ "This problem often occurs when non-ASCII text is stored in str objects. What you are trying to do is to encode in utf-8 a string already encoded in some encoding (because it contains characters with codes above 0x7f). \nTo encode such a string in utf-8 it has to be first decoded. Assuming that the original text en...
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0006870214_python.txt
Q: Activate method in Python I'm trying to set my Python programs in classes. But when I have this: class program: def test(value): print value + 1 def functionTest(): a = test(2) if __name__ == "__main__": functionTest() I get the error : NameError: global name 'test' is not d...
Activate method in Python
I'm trying to set my Python programs in classes. But when I have this: class program: def test(value): print value + 1 def functionTest(): a = test(2) if __name__ == "__main__": functionTest() I get the error : NameError: global name 'test' is not defined What do I have to do to ...
[ "class Program:\n def test(self, value):\n print value + 1\n\n def functionTest(self):\n a = self.test(2)\n\nif __name__ == \"__main__\":\n myprog = Program()\n myprog.functionTest()\n\n\nYou have to supply self as an argument\nYou have to call test with self.test()\nYou have to instantiat...
[ 6, 5, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006873497_python.txt
Q: Matplotlib contour isn't working I'm trying to plot the batman equation. A solution in sympy or matplotlib will be great (sage isn't cool because I'm using windows). The problem is that if I comment out certain parts the part of the figure appears but with all the F *= parts, I get a blank plot. import matplotlib....
Matplotlib contour isn't working
I'm trying to plot the batman equation. A solution in sympy or matplotlib will be great (sage isn't cool because I'm using windows). The problem is that if I comment out certain parts the part of the figure appears but with all the F *= parts, I get a blank plot. import matplotlib.pyplot from numpy import arange from n...
[ "The parameter of sqrt is negative for many points, so the finally products are all NaN. You can plot every factor as following:\nfrom __future__ import division # this is important, otherwise 1/2 will be 0\nimport matplotlib.pyplot\nfrom numpy import arange\nfrom numpy import meshgrid\nfrom numpy import sqrt\nfro...
[ 8, 0, 0 ]
[]
[]
[ "matplotlib", "python", "sympy" ]
stackoverflow_0006871369_matplotlib_python_sympy.txt
Q: py2exe executable doesn't use sys.argv[x] I've written a very simple code in python and generated one .exe with py2exe. I've added the imports to see if there's a problem with importing those modules. import sys import time, os, httplib2 from csv import writer, reader, DictWriter from BeautifulSoup import Beautifu...
py2exe executable doesn't use sys.argv[x]
I've written a very simple code in python and generated one .exe with py2exe. I've added the imports to see if there's a problem with importing those modules. import sys import time, os, httplib2 from csv import writer, reader, DictWriter from BeautifulSoup import BeautifulSoup def main(): print sys.argv[1] if __...
[ "My guess would be that you are using the windows option instead of the console option. That is used for gui apps. If the gui option works, then it would probably spawn a new terminal, which would immediately close once your program is done executing.\nYou should be able to compile it on windows 7 with 32 bit pytho...
[ 2 ]
[]
[]
[ "32bit_64bit", "py2exe", "python" ]
stackoverflow_0006873548_32bit_64bit_py2exe_python.txt
Q: How to run the same test for different class? I have a test (unittest.TestCase) and I want to test more different implementation of a class with the same interface. The max that I have do it's something like this: def create_test(class_to_test): class TestClass(unittest.TestCase): def setUp(self): ...
How to run the same test for different class?
I have a test (unittest.TestCase) and I want to test more different implementation of a class with the same interface. The max that I have do it's something like this: def create_test(class_to_test): class TestClass(unittest.TestCase): def setUp(self): self.class_to_test = class_to_test ...
[ "Not entirely sure if this is what you're looking for, but you can subclass unittests:\nclass A:\n def __init__(self):\n self.a = 10\n\nclass B(A):\n def __init__(self):\n A.__init__(self)\n self.b = 50\n\nclass A_Test(unittest.TestCase):\n def setUp(self):\n self.test_obj = A()\n\n def ...
[ 2 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0006873938_python_unit_testing.txt
Q: python string manipulation Going to re-word the question. Basically I'm wondering what is the easiest way to manipulate a string formatted like this: Safety/Report/Image/489 or Safety/Report/Image/490 And sectioning off each word seperated by a slash(/), and storing each section(token) into a store so I can call ...
python string manipulation
Going to re-word the question. Basically I'm wondering what is the easiest way to manipulate a string formatted like this: Safety/Report/Image/489 or Safety/Report/Image/490 And sectioning off each word seperated by a slash(/), and storing each section(token) into a store so I can call it later. (Reading in about 1200...
[ "The answer for your question: \n>>> mystring = \"Safety/Report/Image/489\"\n>>> mystore = mystring.split('/')\n>>> mystore\n['Safety', 'Report', 'Image', '489']\n>>> mystore[2]\n'Image'\n>>> \n\nIf you want to store data from more than one string, then you have several options depending on how do you want to or...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006872718_python.txt
Q: Effecient way to create 2 django objects that link to each other with a ForeignKey? This seems like a simple question, but I feel like I'm missing something. I have 2 objects: A, and B. B has a ForeignKey to A called my_a, and for various reasons I need to have a ForeignKey on A to B, i.e. A.the_b_used. In a view ...
Effecient way to create 2 django objects that link to each other with a ForeignKey?
This seems like a simple question, but I feel like I'm missing something. I have 2 objects: A, and B. B has a ForeignKey to A called my_a, and for various reasons I need to have a ForeignKey on A to B, i.e. A.the_b_used. In a view function I want to create an instance of A (a = A()), and an instance of B (b = B()), and...
[ "In most cases, you shouldn't need to have a foriegn key from a parent object to a child object if there's already a foreign key from the child back to the parent. A One-to-one correspondence is achieved by making the foreign key column on the child object unique, so that only one child can link to a particular pa...
[ 1 ]
[]
[]
[ "database", "django", "django_models", "performance", "python" ]
stackoverflow_0006874296_database_django_django_models_performance_python.txt
Q: Django: add a field to a modelform I want to add an extra field to a ModelForm. It seems easy, but I get the following error: Django Version: 1.4 pre-alpha SVN-16573 Exception Type: TypeError Exception Value: argument of type 'NoneType' is not iterable Exception Location: /usr/local/lib/django-trunk/django/for...
Django: add a field to a modelform
I want to add an extra field to a ModelForm. It seems easy, but I get the following error: Django Version: 1.4 pre-alpha SVN-16573 Exception Type: TypeError Exception Value: argument of type 'NoneType' is not iterable Exception Location: /usr/local/lib/django-trunk/django/forms/models.py in construct_instance, line...
[ "You should return cleaned data from clean method as documented here\nThat is:\ndef clean(self):\n # perform checks\n return self.cleaned_data\n\n" ]
[ 8 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0006874149_django_django_forms_python.txt
Q: What is the best way to manage db connection in a preforking daemon I am pretty new to python and am using pythons SocketServer.ForkingTCPServer to create a network script that needs to connect to a database(mysql). I expect the program to get hit at around 30 - 40 times a second. Is it possible to share the same ...
What is the best way to manage db connection in a preforking daemon
I am pretty new to python and am using pythons SocketServer.ForkingTCPServer to create a network script that needs to connect to a database(mysql). I expect the program to get hit at around 30 - 40 times a second. Is it possible to share the same database connection across the processes? import os import SocketServer ...
[ "Yes, it's possible. For example this http://mysql-python.sourceforge.net/MySQLdb.html is/can be thread safe. You can connect before starting forks and than use global variable. It's not pretty but will work. \nYou can pass connection as a parameter to constructor.\nIt will be better if you paste some code in que...
[ 0 ]
[]
[]
[ "mysql", "python", "socketserver" ]
stackoverflow_0006874524_mysql_python_socketserver.txt
Q: Python: Why does this non-blocking call to recv block? I have the following code in the $init call of a thread: self.conn = copy.deepcopy(conn) self.conn.setblocking(0) conn is a socket and is passed as an argument to $init Every thread recieves a unique socket. In the run method I have: self.running = True self....
Python: Why does this non-blocking call to recv block?
I have the following code in the $init call of a thread: self.conn = copy.deepcopy(conn) self.conn.setblocking(0) conn is a socket and is passed as an argument to $init Every thread recieves a unique socket. In the run method I have: self.running = True self.conn.send("Connected") print self.name, "has a timeout of", ...
[ "Propably because recv is reading from file and I/O is blocking? (sockets are files too as you may know) :)\nLook here: python socket.recv/sendall call blocking for more info :)\n" ]
[ 1 ]
[]
[]
[ "blocking", "nonblocking", "python", "recv", "sockets" ]
stackoverflow_0006874767_blocking_nonblocking_python_recv_sockets.txt
Q: Convert integer to hex-string with specific format I am new to python and have following problem: I need to convert an integer to a hex string with 6 bytes. e.g. 281473900746245 --> "\xFF\xFF\xBF\xDE\x16\x05" The format of the hex-string is important. The length of the int value is variable. The format '0xffffbf94...
Convert integer to hex-string with specific format
I am new to python and have following problem: I need to convert an integer to a hex string with 6 bytes. e.g. 281473900746245 --> "\xFF\xFF\xBF\xDE\x16\x05" The format of the hex-string is important. The length of the int value is variable. The format '0xffffbf949309L' don't work for me. (I get this with hex(int-value...
[ "There might be a better solution, but you can do this:\nx = 281473900746245\ndecoded_x = hex(x)[2:].decode('hex') # value: '\\xff\\xff\\xbf\\xde\\x16\\x05'\n\nBreakdown:\nhex(x) # value: '0xffffbfde1605'\nhex(x)[2:] # value: 'ffffbfde1605'\nhex(x)[2:].decode('hex') # value: '\...
[ 13, 4, 1 ]
[]
[]
[ "hex", "int", "python", "string" ]
stackoverflow_0006874906_hex_int_python_string.txt
Q: integers when reading a csv file in python I'm trying to read a csv file in python, so that I can then find the average of the values in one of the columns using numpy.average. My script looks like this: import os import numpy import csv listing = os.listdir('/path/to/directory/of/files/i/need') os.chdir('/path/t...
integers when reading a csv file in python
I'm trying to read a csv file in python, so that I can then find the average of the values in one of the columns using numpy.average. My script looks like this: import os import numpy import csv listing = os.listdir('/path/to/directory/of/files/i/need') os.chdir('/path/to/directory/of/files/i/need') for file in list...
[ "Judging by the comments, your program is running into problems with the headers.\nTwo solutions of this are to use r.next(), which skips a line, before your for loop, or to use the DictReader class. The advantage of the DictReader class is that you can treat each row as a dictionary instead of a tuple, which may ...
[ 2, 0 ]
[]
[]
[ "csv", "floating_point", "python" ]
stackoverflow_0006874851_csv_floating_point_python.txt
Q: string matching replace with case sensitive in python I am quite new in python & trying to do some new stuff.I have two list in a dictionary.Let's say, List1: List2: Anterior cord cuneate nucleus Medulla oblongata nucleus ...
string matching replace with case sensitive in python
I am quite new in python & trying to do some new stuff.I have two list in a dictionary.Let's say, List1: List2: Anterior cord cuneate nucleus Medulla oblongata nucleus Spinal cord Intermediolateral nucleus ...
[ "Basically, you want to put some words in <e1> tags and other words in <e2> tags. Is that right?\nIf so, then something like this will do:\n#!/usr/bin/python\n\nfrom __future__ import print_function\nimport re\n\ntext = '''\\\n<s id=\"5239778-2\">The name refers collectively to the cuneate nucleus and gracile nucle...
[ 5, 1 ]
[]
[]
[ "python", "string_matching" ]
stackoverflow_0006875124_python_string_matching.txt
Q: separating JSS from CSS at plone.htmlhead I'm using Plone 3.1.7 in a project that needs performance tweaks. One of the tweaks requests that CSS should be at the top of page and the JS should be at the bottom. However both are located at <div tal:replace="structure provider:plone.htmlhead" /> In main_template. How...
separating JSS from CSS at plone.htmlhead
I'm using Plone 3.1.7 in a project that needs performance tweaks. One of the tweaks requests that CSS should be at the top of page and the JS should be at the bottom. However both are located at <div tal:replace="structure provider:plone.htmlhead" /> In main_template. How do I split these ones? Thanks in advance
[ "My workmates have found the solution:\nplone.htmlhead is a viewlet registered by the product plone.app.layout that loads other three viewlets:\n\nplone.resourceregistries.styles\nplone.resourceregistries.scripts\nplone.resourceregistries.kineticstylesheets\n\nI put the following at the HEAD tag:\n<div tal:replace=...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "plone", "plone_3.x", "python" ]
stackoverflow_0002412350_plone_plone_3.x_python.txt
Q: Looking for python video editing/processing capabilities that will work with Google App Engine Does know any python video editing/processing libraries or frameworks that work with Google App Engine? I need to pro grammatically edit video files (adding a soundtrack, layering video clips on top etc.) on my App Engin...
Looking for python video editing/processing capabilities that will work with Google App Engine
Does know any python video editing/processing libraries or frameworks that work with Google App Engine? I need to pro grammatically edit video files (adding a soundtrack, layering video clips on top etc.) on my App Engine site.
[ "With most video/audio codecs written in C for maximum portability, and any muxing libraries being written in C for speed working with large byte streams, finding these features in pure python libraries is going to be difficult.\nIf you could tie yourself down to just a single codec/container format you could proba...
[ 4 ]
[]
[]
[ "editing", "google_app_engine", "python", "video", "video_processing" ]
stackoverflow_0006872388_editing_google_app_engine_python_video_video_processing.txt
Q: Variable not the same type in two different functions I have two functions which print into an excel file. THe only input is the file name. Here is the code: #excelpy import excelpy #Tinker from Tkinter import * from tkSimpleDialog import * from tkFileDialog import * Function Mode1 def Mode1(full_name): prin...
Variable not the same type in two different functions
I have two functions which print into an excel file. THe only input is the file name. Here is the code: #excelpy import excelpy #Tinker from Tkinter import * from tkSimpleDialog import * from tkFileDialog import * Function Mode1 def Mode1(full_name): print full_name print type(full_name) testwbook = exce...
[ "The only function call in the line you get the error is a call to the built-in function type(), so the only explanation for your error message is that you overwrote the built-in name type by a global name type pointing to a string object. Try adding \nprint type\n\nbefore\nprint type(full_name)\n\n", "It looks ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006875626_python.txt
Q: Nonzero function help, Python Numpy I have two arrays, and I have a complex condition like this: new_arr<0 and old_arr>0 I am using nonzero but I am getting an error. The code I have is this: indices = nonzero(new_arr<0 and old_arr>0) I tried: indices = nonzero(new_arr<0) and nonzero(old_arr>0) But it ga...
Nonzero function help, Python Numpy
I have two arrays, and I have a complex condition like this: new_arr<0 and old_arr>0 I am using nonzero but I am getting an error. The code I have is this: indices = nonzero(new_arr<0 and old_arr>0) I tried: indices = nonzero(new_arr<0) and nonzero(old_arr>0) But it gave me incorrect results. Is there any way...
[ "Try indices = nonzero((new_arr < 0) & (old_arr > 0)):\nIn [5]: import numpy as np\n\nIn [6]: old_arr = np.array([ 0,-1, 0,-1, 1, 1, 0, 1])\n\nIn [7]: new_arr = np.array([ 1, 1,-1,-1,-1,-1, 1, 1])\n\nIn [8]: np.nonzero((new_arr < 0) & (old_arr > 0))\nOut[8]: (array([4, 5]),)\n\n", "Try\nindices = nonzero(logical_...
[ 5, 2 ]
[]
[]
[ "conditional_statements", "numpy", "python" ]
stackoverflow_0006875682_conditional_statements_numpy_python.txt
Q: An universal way to set unicode cookies in Python Only the first word is saved into a cookie using an "example" code if there is a space in value. What is a really correct, unicode-compatible way to make that? response.headers.add_header( 'Set-Cookie', '%s=%s; expires:Sun, 31-May-2020 23:59:59 GMT; path=/;' % ...
An universal way to set unicode cookies in Python
Only the first word is saved into a cookie using an "example" code if there is a space in value. What is a really correct, unicode-compatible way to make that? response.headers.add_header( 'Set-Cookie', '%s=%s; expires:Sun, 31-May-2020 23:59:59 GMT; path=/;' % (key, value)) UPD. A solution is below
[ "Finally the job is done:\n\ncookies escaped with Cookie.SimpleCookie\nunescaped with custom code\nunicode encoded/decoded with string's encode/decode\n\nThe code:\nimport Cookie\ndef set_unicode_cookie(response, key, value):\n c = Cookie.SimpleCookie()\n c[key] = value.encode('unicode-escape')\n c[key][\"expire...
[ 2 ]
[]
[]
[ "cookies", "http", "python" ]
stackoverflow_0006873064_cookies_http_python.txt
Q: Getting more detail from stack traces Is there a convenient way to get a more detailed stack trace on a Python exception? I'm hoping to find a wrapper utility/module or some other way to get a bit more info from the stack trace without having to actually modify the Python script that generates it. I'd like to be...
Getting more detail from stack traces
Is there a convenient way to get a more detailed stack trace on a Python exception? I'm hoping to find a wrapper utility/module or some other way to get a bit more info from the stack trace without having to actually modify the Python script that generates it. I'd like to be able to use this when running unit tests, ...
[ "Not specifically related to your problem, but you might find this code useful -- automatically starts up the python debugger when a fatal exception occurs. Good for working with interactive code. It's originally from ActiveState\n# code snippet, to be included in 'sitecustomize.py'\nimport sys\n\ndef info(type, va...
[ 2, 0, 0 ]
[]
[]
[ "debugging", "python", "stack_trace" ]
stackoverflow_0003911624_debugging_python_stack_trace.txt
Q: Pythonize if/else My mind is probably feeling Friday afternoon and I cannot see a way to pytonize the code below: filepath = None if 'HALLO' in os.environ: filepath = os.environ['HALLO'] elif os.path.isfile( os.path.join(os.environ['HOME'], 'host.hallo') ): filepath = os.path.join(os.environ['HOME'], 'host...
Pythonize if/else
My mind is probably feeling Friday afternoon and I cannot see a way to pytonize the code below: filepath = None if 'HALLO' in os.environ: filepath = os.environ['HALLO'] elif os.path.isfile( os.path.join(os.environ['HOME'], 'host.hallo') ): filepath = os.path.join(os.environ['HOME'], 'host.hallo') elif os.path.i...
[ "This should work pretty well:\npaths = [\n os.environ.get('HALLO', None),\n os.path.join(os.environ['HOME'], 'host.hallo'),\n '/etc/app/host.hallo',\n]\n\nfor path in paths:\n if path and os.path.isfile(path):\n break\nelse:\n # Handle no path\n pass\n\n# Use path here\n\nAdditionally, it ...
[ 10, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006876064_python.txt
Q: using LEPL to parse a Boolean search query I'm trying to write a LEPL grammar to describe a Boolean search language. This is what I have so far: from lepl import * text = String() | Word() tail = ~Lookahead('AND') & ~Lookahead('OR') & text with DroppedSpace(): andClause = (tail & Lookahead('AND') & Drop('AND'...
using LEPL to parse a Boolean search query
I'm trying to write a LEPL grammar to describe a Boolean search language. This is what I have so far: from lepl import * text = String() | Word() tail = ~Lookahead('AND') & ~Lookahead('OR') & text with DroppedSpace(): andClause = (tail & Lookahead('AND') & Drop('AND') & tail)[1:] > tuple orClause = (tail & Loo...
[ "Edit: got rid of sloooooow left recursion thanks to this article and added keyword parameters.\nfrom lepl import *\ndef ander(result):\n if len(result) == 2:\n return (result[0], result[1])\n return result[0]\ntext = String() | Word()\nandClausePrime = Delayed()\nlabel = text & Drop(':')\nwith Dropped...
[ 5 ]
[]
[]
[ "boolean", "grammar", "lepl", "parsing", "python" ]
stackoverflow_0006875361_boolean_grammar_lepl_parsing_python.txt
Q: no UnicodeError when using print with a default encoding set to ASCII After reading: Dive into Python: Unicode Discussion I got curious to try printing my name in the indic script. I am using v2.7.2 - >>> import sys >>> sys.getdefaultencoding() 'ascii' >>> name = u'\u0935\u0948\u092D\u0935' >>> print name वैभव ...
no UnicodeError when using print with a default encoding set to ASCII
After reading: Dive into Python: Unicode Discussion I got curious to try printing my name in the indic script. I am using v2.7.2 - >>> import sys >>> sys.getdefaultencoding() 'ascii' >>> name = u'\u0935\u0948\u092D\u0935' >>> print name वैभव I was expecting print name to give me UnicodeError since the defaultencodin...
[ "print uses sys.stdout.encoding, not sys.getdefaultencoding():\n\nWhen Python finds its output attached to a terminal, it sets the\n sys.stdout.encoding attribute to the terminal's encoding. The print\n statement's handler will automatically encode unicode arguments into\n str output.\n\n>>> import sys\n>>> prin...
[ 9 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0006876877_python_unicode.txt
Q: Python to C++: From Deriv, to Base, to Deriv again I'm using Boost.Python to expose my C++ code to Python. I've encountered a difficulty related to having an object passed from one language to the other multiple times. Here's what I want to do: The C++ code class Base { public: void baseTest() { std:...
Python to C++: From Deriv, to Base, to Deriv again
I'm using Boost.Python to expose my C++ code to Python. I've encountered a difficulty related to having an object passed from one language to the other multiple times. Here's what I want to do: The C++ code class Base { public: void baseTest() { std::cout << "Base::basetest()"; } }; class Deriv :...
[ "Thanks for the comments, I found the solution to this. It's actually quite simple, you just have to wrap the Base object in a shared_ptr instead of passing it by reference, like this:\nvoid call(boost::shared_ptr<Base> b, boost::python::object func)\n{\n func(b);\n}\n\nBut be careful about something. I tried to...
[ 1 ]
[]
[]
[ "boost", "c++", "python" ]
stackoverflow_0006872701_boost_c++_python.txt
Q: How to "weak link" to the Python framework on Mac OS X? I'm trying to create an app that can link to Mac OS X's built-in Python framework and have it work on Mac OS X 10.5, 10.6 and 10.7. If I try to hard-link to the framework (the default), Leopard complains that he can't find 10.7. If I try to weakly link the f...
How to "weak link" to the Python framework on Mac OS X?
I'm trying to create an app that can link to Mac OS X's built-in Python framework and have it work on Mac OS X 10.5, 10.6 and 10.7. If I try to hard-link to the framework (the default), Leopard complains that he can't find 10.7. If I try to weakly link the framework (using -weak_framework Python in the compiler flags)...
[ "I'm not sure what you are trying to do here but here are a few suggestions. The only Python version common to the system Python frameworks in those three operating system releases is Python 2.5 so you may be able to explicitly target that version. But, more likely, you would be better off packaging your own Pyth...
[ 2 ]
[]
[]
[ "macos", "pyobjc", "python", "xcode" ]
stackoverflow_0006874167_macos_pyobjc_python_xcode.txt
Q: Is there a security risk when using a user-inputted variable in sqlite3.connect()? I am having users both create and connect to a database through a python application, dbname = raw_input("Please enter the game name you wish to connect to, or the name of a new game: ") db = sqlite3.connect(d...
Is there a security risk when using a user-inputted variable in sqlite3.connect()?
I am having users both create and connect to a database through a python application, dbname = raw_input("Please enter the game name you wish to connect to, or the name of a new game: ") db = sqlite3.connect(dbname) I'm curious: is there any kind of input a potentially malicious user could use t...
[ "They can pass in \":memory\", which may or may not have an adverse effect on the system, depending on what your application does.\nThey can control transactions (via the isolation_level parameter), which might mess up your program's interaction with the database.\nI would check user-input against a dictionary of p...
[ 3, 1, 0, 0 ]
[]
[]
[ "python", "security", "sqlite" ]
stackoverflow_0006867195_python_security_sqlite.txt
Q: unsupported operand type(s) for +: 'int' and 'unicode' I am working with a templatetag to return the variable from a formula I have written. I have been trying to find out why I am getting this traceback. I have tested the formula's in the shell and all are working properly. I have done some print statements in th...
unsupported operand type(s) for +: 'int' and 'unicode'
I am working with a templatetag to return the variable from a formula I have written. I have been trying to find out why I am getting this traceback. I have tested the formula's in the shell and all are working properly. I have done some print statements in the tag and views. But can't figure out the reason for this. T...
[ "Assuming args is an array of strings, as it usually is, you're passing string values into your functions where you want numbers.\nreturn MinMonthlyPaymentsNode(args[1], args[2], args[3], args[5])\n\nIt's then trying to do math with them, which doesn't work because Python doesn't automatically convert them. If all ...
[ 1, 1 ]
[]
[]
[ "django", "python", "tags", "templates" ]
stackoverflow_0006877152_django_python_tags_templates.txt
Q: Developing an application server: django vs. zend vs. cakephp vs. codeigniter vs. other I'm trying to develop an application server that will deliver content to a core group of websites, as well as provide third party services to other websites that also want to use this content. The app server will be hosting we...
Developing an application server: django vs. zend vs. cakephp vs. codeigniter vs. other
I'm trying to develop an application server that will deliver content to a core group of websites, as well as provide third party services to other websites that also want to use this content. The app server will be hosting web services for these core + 3rd party websites. Authentication and all that comes into play....
[ "All of the frameworks that you mentioned are capable. Pick one in the language that you know the best and use that. \n", "I agree with @gpojd's opinion. All of them that you mentioned are fully capable.\nHowever, it looks like they are too powerful for your job. Because they are all full-stack MVC-like web frame...
[ 1, 0 ]
[]
[]
[ "cakephp", "django", "php", "python", "zend_framework" ]
stackoverflow_0006876120_cakephp_django_php_python_zend_framework.txt
Q: Suggest a standalone python web framework? I have a python program that I would like to present as a simple web application. The program currently uses sqlite for storage. I also need to distribute the whole thing to colleagues so having something standalone and easy to start would be ideal ( no install if possi...
Suggest a standalone python web framework?
I have a python program that I would like to present as a simple web application. The program currently uses sqlite for storage. I also need to distribute the whole thing to colleagues so having something standalone and easy to start would be ideal ( no install if possible). This web app is meant to be used locally ...
[ "I have never tried it myself, but you could try Bottle:\n\nBottle is a fast, simple and lightweight WSGI micro web-framework for\n Python. It is distributed as a single file module and has no\n dependencies other than the Python Standard Library.\n\n", "try http://docs.python.org/library/simplehttpserver.html\...
[ 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "frameworks", "python" ]
stackoverflow_0006877301_frameworks_python.txt
Q: can't access imported functions in Python Can anyone please help me with this ? I am moving on using PyDev Aptana for developing python codes. Here is my project structure under PyDev IDE : /testProject /src /testModule __init__.py testMod.py main.py testMod....
can't access imported functions in Python
Can anyone please help me with this ? I am moving on using PyDev Aptana for developing python codes. Here is my project structure under PyDev IDE : /testProject /src /testModule __init__.py testMod.py main.py testMod.py file : def test(n): print "echo"+n ma...
[ "You missed the testMod module. The full name of your method is testModule.testMod.test.\n", "Well, this is basically because there is no method test() in testModule. In fact, your testModule is not module, but is a package, while testMod is a module in testModule package.\nSo, with your structure, the following ...
[ 8, 4 ]
[]
[]
[ "aptana", "import", "pydev", "python" ]
stackoverflow_0006877745_aptana_import_pydev_python.txt
Q: Exposing Static Constant with Boost I am using Boost 1.44.0 to cross-compile C++ code for Python. I'm trying to expose a static constant defined in ExposureSinusoid.h like this: static const UINT _min_exp = 20; And in the file extending.cpp, I am trying to expose them like this, according to documentation from th...
Exposing Static Constant with Boost
I am using Boost 1.44.0 to cross-compile C++ code for Python. I'm trying to expose a static constant defined in ExposureSinusoid.h like this: static const UINT _min_exp = 20; And in the file extending.cpp, I am trying to expose them like this, according to documentation from the Boost team: .def_readonly("_min_exp", &...
[ "In addition to being declared, static data members must also be defined.\n// ExposureSinusoid.h\nclass ExposureSinusoid\n{\n // ...\npublic:\n static const UINT _min_exp = 20; // declaration\n // ...\n};\n\n// ExposureSinusoid.cpp\nconst UINT ExposureSinusoid::_min_exp; // definition\n\nThe only scenari...
[ 4, 3 ]
[]
[]
[ "boost", "c++", "python" ]
stackoverflow_0006877587_boost_c++_python.txt
Q: Can I use javascript with bottle (framework)? I'm trying to display a page of html using bottle (the python web framework). The page has javascript embedded but it won't display it when I serve it with bottle. The JS I'm using is EditArea, I can clean it up how I want and put it an html page that displays properl...
Can I use javascript with bottle (framework)?
I'm trying to display a page of html using bottle (the python web framework). The page has javascript embedded but it won't display it when I serve it with bottle. The JS I'm using is EditArea, I can clean it up how I want and put it an html page that displays properly when I open the page in chrome. But when I use b...
[ "You need to create a view to serve static files, as described in Bottle documentation.\nI suggest you to put all your static files (css, js, images) in a static folder next to your application. The view to serve static files would then look like this:\nfrom bottle import static_file \n\n@route('/static/:filenam...
[ 4, 2 ]
[]
[]
[ "bottle", "javascript", "python" ]
stackoverflow_0006877806_bottle_javascript_python.txt
Q: Is there a Python module to get next runtime from a crontab-style time definition? I'm writing a dashboard application and I need a way to figure out how long an item is "valid", i.e. when should it have been superseded by a new value (it's possible to have an error such that the next value never arrives). Since I...
Is there a Python module to get next runtime from a crontab-style time definition?
I'm writing a dashboard application and I need a way to figure out how long an item is "valid", i.e. when should it have been superseded by a new value (it's possible to have an error such that the next value never arrives). Since I know the schedules for the processes producing data, I can define valid as "until the n...
[ "I ran into some issues using the code (from http://www.koders.com/python/fidA55A9DB55093A78DD26B55C606B267B2C5063A79.aspx?s=config) , and have fixed some of them. It used to break going from one month to the next. next_run now works fine, but prev_run gets stuck going from one month the previous (instead of failin...
[ 3 ]
[]
[]
[ "crontab", "parsing", "python" ]
stackoverflow_0004190997_crontab_parsing_python.txt
Q: Change permissions for folder, all subfolders, and all files I am trying to call shutil.rmtree(some_folder), but it is causing an error that another process is using some file in the subtree. This is not the case, so I'm assuming permissions are not set correctly. How can I change the permissions of all subfold...
Change permissions for folder, all subfolders, and all files
I am trying to call shutil.rmtree(some_folder), but it is causing an error that another process is using some file in the subtree. This is not the case, so I'm assuming permissions are not set correctly. How can I change the permissions of all subfolders and files under some root to writeable, so I can call shutil.r...
[ "On a platform with the chmod command available, you could do this:\nsubprocess.call(['chmod', '-R', '+w', some_folder])\n\nAssuming that some_folder is a string that is the full-path to the folder you want to modify.\n", "Using os:\nimport os\ndef change_permissions_recursive(path, mode):\n for root, dirs, fi...
[ 9, 6 ]
[]
[]
[ "python" ]
stackoverflow_0006874970_python.txt
Q: Extract data from HTML table using Python I want to extract data from HTML table using Python script and save it as variables(that I can later use in same script after loading them in if they exist) into a separate file. Also I want the script to ignore the first row of table(Component, Status, Time / Error). I wo...
Extract data from HTML table using Python
I want to extract data from HTML table using Python script and save it as variables(that I can later use in same script after loading them in if they exist) into a separate file. Also I want the script to ignore the first row of table(Component, Status, Time / Error). I would prefer not to use external libraries. The ...
[ "Using lxml:\nimport lxml.html as lh\n\ncontent='''\\\n<table border=1>\n<tr>\n<td><b>Component</b></td>\n<td><b>Status</b></td>\n<td><b>Time / Error</b></td>\n</tr>\n<tr><td>SAVE_DOCUMENT</td><td>OK</td><td>0.408 s</td></tr>\n<tr><td>GET_DOCUMENT</td><td>OK</td><td>0.361 s</td></tr>\n<tr><td>DVK_SEND</td><td>OK</t...
[ 4, 2 ]
[]
[]
[ "extract", "html", "python" ]
stackoverflow_0006878032_extract_html_python.txt
Q: Is it OK to pass complex data structures through the clipboard with wxPython? I'd like my wxPython application to support cut/copy/paste operations between different running instances of the application. Is it OK to simply pickle a data structure, copy it to clipboard as text, and then unpickle it for paste operat...
Is it OK to pass complex data structures through the clipboard with wxPython?
I'd like my wxPython application to support cut/copy/paste operations between different running instances of the application. Is it OK to simply pickle a data structure, copy it to clipboard as text, and then unpickle it for paste operations? I know I'd have to check the data for some sign that it's from my app. Or cou...
[ "You should not trust data from the clipboard for unpickling, unless you have a sure way to make sure it was wrtten by your app, and has not been altered.\nFrom the python documentation: \n\nWarning The pickle module is not intended to be secure against\n erroneous or maliciously constructed data. Never unpickle d...
[ 1, 1 ]
[]
[]
[ "clipboard", "pickle", "python", "wxpython" ]
stackoverflow_0006877326_clipboard_pickle_python_wxpython.txt
Q: need to create a .pem file What the .pem file contain? simply a key or a function which generate the key. I need to create a .pem file and also need to call this file in a function. here is code to which I have to proceed: pk = open( 'public_key.pem', 'rb' ).read() rsa = M2Crypto.RSA.load_pub_key(pk) A: You can ...
need to create a .pem file
What the .pem file contain? simply a key or a function which generate the key. I need to create a .pem file and also need to call this file in a function. here is code to which I have to proceed: pk = open( 'public_key.pem', 'rb' ).read() rsa = M2Crypto.RSA.load_pub_key(pk)
[ "You can use openssl to create a pem file. You will need to supply it the correct parameters to get the correct type of key. The genkey command of openssl looks like what you want to use.\n", "You can use this code to create a public key pair, then save them unencrypted to two files. \n from M2Crypto import ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001170700_python.txt
Q: GDAL Raster Output I'm trying to create a .tif file using GDAL in python. It's creating a file, but saying "no preview available" whenever I browse to it. Right now, I'm just trying to get it to make a copy of the input file. Here's my code: gdal.AllRegister() inDs = gdal.Open("C:\\Documents and Settings\\pat...
GDAL Raster Output
I'm trying to create a .tif file using GDAL in python. It's creating a file, but saying "no preview available" whenever I browse to it. Right now, I'm just trying to get it to make a copy of the input file. Here's my code: gdal.AllRegister() inDs = gdal.Open("C:\\Documents and Settings\\patrick\\Desktop\\tiff elev...
[ "Do you mean you're getting \"No preview available\" from the Windows Picture and Fax Viewer application when trying to preview the TIFF file as an image? (See below screenshot.)\n\nBear in mind that there are many different flavors of TIFF, and not all are the same. In particular, the Windows Picture and Fax Vie...
[ 2, 1 ]
[]
[]
[ "arcgis", "gdal", "io", "python", "raster" ]
stackoverflow_0006710368_arcgis_gdal_io_python_raster.txt
Q: lxml: how to discard all elements containing a link with particular class? As is often the case, I'm struggling with the lack of proper lxml documentation (note to self: should write a proper lmxl tutorial and get lots of traffic!). I want to find all <li> items that do not contain an <a> tag with a particular c...
lxml: how to discard all elements containing a link with particular class?
As is often the case, I'm struggling with the lack of proper lxml documentation (note to self: should write a proper lmxl tutorial and get lots of traffic!). I want to find all <li> items that do not contain an <a> tag with a particular class. For example: <ul> <li><small>pudding</small>: peaches and <a href="/cream"...
[ "import lxml.html as lh\n\ncontent='''\\\n<ul>\n<li><small>pudding</small>: peaches and <a href=\"/cream\">cream</a></li>\n<li><small>cheese</small>: Epoisses and <a href=\"/st-marcellin\" class=\"new\">St Marcellin</a></li>\n</ul>\n'''\n\ntree=lh.fromstring(content)\nfor elt in tree.xpath('//li[not(descendant::a[@...
[ 2, 0 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0006878315_lxml_python.txt
Q: Why would you open an xml file in binary mode for editing in Python? According to Pydocs, fp = file('blah.xml', 'w+b') or fp = file('blah.xml', 'wb') means open the file in write and binary mode. This is an xml file, however, so why do these two chaps http://www.pixelmender.com/2010/10/12/scraping-data-using-s...
Why would you open an xml file in binary mode for editing in Python?
According to Pydocs, fp = file('blah.xml', 'w+b') or fp = file('blah.xml', 'wb') means open the file in write and binary mode. This is an xml file, however, so why do these two chaps http://www.pixelmender.com/2010/10/12/scraping-data-using-scrapy-framework/ and http://doc.scrapy.org/topics/exporters.html#scrapy....
[ "It just doesn't make sense with plain XML files.\nOn Unix there is no difference between binary and non-binary. On Windows written '\\n' get translated to '\\r\\n' if you write non-binary.\nBut it will make a difference if you embed binary BLOBs, but I don't see those on the sites you mentioned.\n" ]
[ 0 ]
[]
[]
[ "file_io", "python", "scrapy", "xml", "xml_serialization" ]
stackoverflow_0006878221_file_io_python_scrapy_xml_xml_serialization.txt
Q: How to serve static files in production for Django 1.3 I'm deploying my app and I wonder what I'm missing. I did the following: Set my STATIC_ROOT to an empty folder in my server. Set the STATIC_URL to '/static/' Added 'django.contrib.staticfiles' to INSTALLED_APPS In development my static files are in the root ...
How to serve static files in production for Django 1.3
I'm deploying my app and I wonder what I'm missing. I did the following: Set my STATIC_ROOT to an empty folder in my server. Set the STATIC_URL to '/static/' Added 'django.contrib.staticfiles' to INSTALLED_APPS In development my static files are in the root of my app in a folder named static. So, I ran manage.py coll...
[ "As explained in Django's documentation, Django serves static files itself in development only, when deploying your application in production, it's up to you to make your web server (apache, lighttpd, nginx, whatever) serve the static files.\nDjango's documentation provides instructions for doing so with Apache her...
[ 3, 3, 3 ]
[]
[]
[ "apache", "django", "python", "wsgi" ]
stackoverflow_0006878404_apache_django_python_wsgi.txt
Q: rough estimate time it takes to do string comparisons Python I have a string, call it paragraph that contains about 50-100 words separated by spaces. I have an array of 5500 strings all about 3-5 characters long. What I want to do is check each word in paragraph and see if any of the words are also containe...
rough estimate time it takes to do string comparisons Python
I have a string, call it paragraph that contains about 50-100 words separated by spaces. I have an array of 5500 strings all about 3-5 characters long. What I want to do is check each word in paragraph and see if any of the words are also contained in my array of 5500 strings. does anyone have a rough estimate o...
[ "I would convert your array of 5500 strings to a set and just use a set intersection.\n>>> paragraph = \"five hundred to one hundred words separated by spaces\"\n>>> array_of_strings = set(['hundred', 'spaces', ]) # make a set..\n\n>>> print set(paragraph.split()).intersection(array_of_strings)\nset(['hundred', 's...
[ 3, 1 ]
[]
[]
[ "python", "time" ]
stackoverflow_0006878474_python_time.txt
Q: Searching ID or property for match in Mongo Goal: I want to allow the user to search for a document by ID, or allow other text-based queries. Code: l_search_results = list( cll_sips.find( { '$or': [ {'_id': ObjectId(s_term)}, {'s_text': re.compile(s_term, re....
Searching ID or property for match in Mongo
Goal: I want to allow the user to search for a document by ID, or allow other text-based queries. Code: l_search_results = list( cll_sips.find( { '$or': [ {'_id': ObjectId(s_term)}, {'s_text': re.compile(s_term, re.IGNORECASE)}, {'choices': re.comp...
[ "s_term needs to be a valid object ID (or at least in the right format) when you pass it to the ObjectId constructor. Since it's sometimes not an ID, that explains why you get the exception.\nTry something like this instead:\nfrom pymongo.errors import InvalidId\n\nor_filter = [\n {'s_text': re.compile(s_term, r...
[ 3 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0006877264_mongodb_pymongo_python.txt
Q: Django - routing to non-django script? (e.g. simple WSGI/CGI application) How (if it is possible) can set up a route in Django that would point a certain url to a non-django script? E.g. I'd like to have /independent handled by a very simple CGI script such as this one: import os print 'Status: 200 OK' print 'Con...
Django - routing to non-django script? (e.g. simple WSGI/CGI application)
How (if it is possible) can set up a route in Django that would point a certain url to a non-django script? E.g. I'd like to have /independent handled by a very simple CGI script such as this one: import os print 'Status: 200 OK' print 'Content-type: text/html' print for key, value in os.environ.items(): print key...
[ "If you have permissions to change your Apache conf, you can just add a line above the bit that handles Django. (Assuming you run your Django via WSGI.) Mine is something like\n<Directory \"/cgi-bin/\">\n Options +ExecCGI\n AddHandler cgi-script .cgi .py\n</Directory>\n\nScriptAlias /cgi-bin/ /path/to/cgi/d...
[ 2, 1, 1 ]
[]
[]
[ "django", "python", "routes" ]
stackoverflow_0006664678_django_python_routes.txt
Q: Opening a file for append I just had a passing thought and figured what better place to ask then right here. Out of curiosity, does anyone know if opening a file for append, like this: file_name = "abc" file_handle = open(file_name,"a") Is essentially the same as opening a file for writing and seeking to the end...
Opening a file for append
I just had a passing thought and figured what better place to ask then right here. Out of curiosity, does anyone know if opening a file for append, like this: file_name = "abc" file_handle = open(file_name,"a") Is essentially the same as opening a file for writing and seeking to the end: file_name = "abc" file_handle...
[ "After playing a bit in my terminal, I can say what the differences are on ubuntu linux 11.04 using python 2.7.1. \nOpening with 'w' truncates (i.e. erases the contents of) the file as soon as it's opened. In other words, just opening the file with open('file.txt', 'w') and exiting leaves behind an empty file.\nO...
[ 19, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006878628_python.txt
Q: minidom.Document v minidom.Document.documentElement? Dive into Python: Scripts and Streams - class KantGenerator: def _load(self, source): sock = toolbox.openAnything(source) xmldoc = minidom.parse(sock).documentElement sock.close() return xmldoc I am curious, why do we have d...
minidom.Document v minidom.Document.documentElement?
Dive into Python: Scripts and Streams - class KantGenerator: def _load(self, source): sock = toolbox.openAnything(source) xmldoc = minidom.parse(sock).documentElement sock.close() return xmldoc I am curious, why do we have documentElement attribute when - xmldoc = minidom.parse(soc...
[ "The minidom.Document is a xml.dom.Document object, while minidom.Document.documentElement is an xml.dom.Element object.\nThe Document contains extra things, like encoding, where the Element contains the actual XML data.\nThere can only be one Element in the main document (hence documentElement), where an element c...
[ 4 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0006878813_python_xml.txt
Q: ld under cygwin unable to find libs that exist I'm trying to install p4python, a Python extension for the Perforce revision control system. I'm using cygwin to accomplish this as p4python requires the P4 C++ API (it's really just a wrapper), which in turn requires g++ (not to mention, Python extensions require a C...
ld under cygwin unable to find libs that exist
I'm trying to install p4python, a Python extension for the Perforce revision control system. I'm using cygwin to accomplish this as p4python requires the P4 C++ API (it's really just a wrapper), which in turn requires g++ (not to mention, Python extensions require a C compiler, hence, gcc). I'm on Windows 7 64-bit (not...
[ "Here's a way I've used to turn lib files into shared libraies for use with gcc:\n\necho EXPORTS > NAME.def\nnm NAME.lib | grep ' T _' | sed 's/.* T _//' >> NAME.def\ndlltool --input-def NAME.def --dllname NAME --output-lib libNAME.a\n\nFurther notes on using Cygwin (but I use gcc 3 on an older 32-bit system, so YM...
[ 3, 0 ]
[]
[]
[ "c++", "g++", "perforce", "python" ]
stackoverflow_0006877889_c++_g++_perforce_python.txt
Q: web2py, Database relationships and permissions So i've this problem i've 2 tables for example templates(id,user_id,template_name,reference) user_settings(id,user_id,default_template) so each user can create many templates and in his settings he can choose a default template that he will always use so now there is ...
web2py, Database relationships and permissions
So i've this problem i've 2 tables for example templates(id,user_id,template_name,reference) user_settings(id,user_id,default_template) so each user can create many templates and in his settings he can choose a default template that he will always use so now there is many users so when a user want to choose a default t...
[ "First, shouldn't\n Field('standard_template_id', templates,\n\nbe\n Field('standard_template_id', db.i2l_templates,\n\nFor a reference field, the default form validator is IS_IN_DB(db,'<table>.id'), which will select all records in the referenced table. However, you can override the default validator and spe...
[ 0 ]
[]
[]
[ "database", "permissions", "python", "relationships", "web2py" ]
stackoverflow_0006875727_database_permissions_python_relationships_web2py.txt
Q: How to extend django template from python string I have a string that looks like string ''' <html> <head> {% block head %}{% endblock %} ... other stuff ... </head> <body> {% block body %}{% endblock %} ... other stuff ... </body> ...
How to extend django template from python string
I have a string that looks like string ''' <html> <head> {% block head %}{% endblock %} ... other stuff ... </head> <body> {% block body %}{% endblock %} ... other stuff ... </body> </html> ''' I would like the following django temp...
[ "In order to implement string-only template extender, you would probably have to implement your template loader. Actually, a much cleaner solution is to use threed's suggestion below. Pass a parent Template() in the context rather than the name of disk template:\n>>> from django.template import Context, Template\n...
[ 6, 4 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0006868433_django_django_templates_python.txt
Q: How can I get the name/file of the script from sitecustomize.py? When I run any Python script, I would like to see the script's filename appear in the Windows command line window's titlebar. For example, if I run a script called "mytest.py", I want to see "mytest" in the titlebar. I would like this to be automatic...
How can I get the name/file of the script from sitecustomize.py?
When I run any Python script, I would like to see the script's filename appear in the Windows command line window's titlebar. For example, if I run a script called "mytest.py", I want to see "mytest" in the titlebar. I would like this to be automatic, so I don't have to add code to every one of my scripts. Currently I'...
[ "I'm glad you asked! I now have it working for my scripts, and it's pretty cool.\nHere's the code:\nimport sys\nimport time\nfrom ctypes import windll\n\nclass SetTitle(object):\n def __del__(self):\n time.sleep(1)\n command = ' '.join(sys.argv)\n windll.kernel32.SetConsoleTitleA(command)\n...
[ 5, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006485678_python_python_3.x.txt
Q: How to transform a column field into a list I'm trying to make a simple field calculation with ArcGIS 9.3: New field = Old field - Old field(first value) which in Calculate Field with python code should be Expression: !Old field! - first Code Block: list= [AngOriz] first = list[0] The error is ERROR 000539: Runti...
How to transform a column field into a list
I'm trying to make a simple field calculation with ArcGIS 9.3: New field = Old field - Old field(first value) which in Calculate Field with python code should be Expression: !Old field! - first Code Block: list= [AngOriz] first = list[0] The error is ERROR 000539: Runtime error : name 'AngOriz' is not defined Failed t...
[ "I'm not getting the whole picture, what do you mean by Old field(first value)?? is Old field a text field with multiple values on it separated by commas or something like that? and if so, how come you use Old field before that?\nBut anyway, the error you're getting is because on the code block you haven't defined ...
[ 0, 0 ]
[]
[]
[ "arcgis", "python" ]
stackoverflow_0006847518_arcgis_python.txt
Q: Improve speed for list concatenation? I have a list called L inside a loop that must iterate though millions of lines. The salient features are: for line in lines: L = ['a', 'list', 'with', 'lots', 'of', 'items'] L[3] = 'prefix_text_to_item3' + L[3] Do more stuff with L... Is there a better approach t...
Improve speed for list concatenation?
I have a list called L inside a loop that must iterate though millions of lines. The salient features are: for line in lines: L = ['a', 'list', 'with', 'lots', 'of', 'items'] L[3] = 'prefix_text_to_item3' + L[3] Do more stuff with L... Is there a better approach to adding text to a list item that would spe...
[ "In a performance oriented code, it is not a good idea to add 2 strings together, it is preferable to use a \"\".join(_items2join_) instead. (I found some benchmarks there : http://www.skymind.com/~ocrow/python_string/)\n", "Since accessing an element in a python list is O(1), and appending a list to another is O...
[ 2, 1, 1, 0 ]
[]
[]
[ "concatenation", "list", "python", "string" ]
stackoverflow_0006877528_concatenation_list_python_string.txt
Q: Why is the Python CSV reader ignoring double-quoted fields? I think this is probably something simple, but after an hour of searching, I've had no luck figuring out what I'm doing wrong. I'm using the following code to read a CSV file - I have no problem reading the file, but when a line contains a field that is d...
Why is the Python CSV reader ignoring double-quoted fields?
I think this is probably something simple, but after an hour of searching, I've had no luck figuring out what I'm doing wrong. I'm using the following code to read a CSV file - I have no problem reading the file, but when a line contains a field that is double-quoted because it contains the delimiter, the CSV reader ig...
[ "If you look at the dialect that you're using, you'll notice that the excel dialect is\nconfigured as follows:\nclass excel(Dialect):\n \"\"\"Describe the usual properties of Excel-generated CSV files.\"\"\"\n delimiter = ','\n quotechar = '\"'\n doublequote = True\n skipinitialspace = False\n lin...
[ 30, 5 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0006879596_csv_python.txt
Q: mod_wsgi && virtualenvwrapper && python executable I'm on a virtualhost with no access to the apache httpd.conf, there is no system virtualenv configuration, I've installed and set up one virtualenv on my home, it's possible to run the virtualenv's python interpreter as my user, instead of apache's nobody?? What i...
mod_wsgi && virtualenvwrapper && python executable
I'm on a virtualhost with no access to the apache httpd.conf, there is no system virtualenv configuration, I've installed and set up one virtualenv on my home, it's possible to run the virtualenv's python interpreter as my user, instead of apache's nobody?? What i'm really searching with this, is write permissions in m...
[ "There are two modes that mod_wsgi can run in, embedded mode and daemon mode. If they have set you up to run in embedded mode and this is a shared system, that is a bad idea. They should instead be looking at daemon mode. When running daemon mode the user/group of the process can be overridden.\nhttp://code.google....
[ 0 ]
[]
[]
[ "apache", "mod_wsgi", "python" ]
stackoverflow_0006876128_apache_mod_wsgi_python.txt
Q: Python GtkTreeview; How to refresh the list when an item is selected I'm making a rudimentary file manager and am stuck on the question in my post's title. First it looks in a directory, generates a list of items, and appends them to the treeview list. If a subdirectory is clicked, it becomes the new current direc...
Python GtkTreeview; How to refresh the list when an item is selected
I'm making a rudimentary file manager and am stuck on the question in my post's title. First it looks in a directory, generates a list of items, and appends them to the treeview list. If a subdirectory is clicked, it becomes the new current directory. All I need is to send this back into the def where it reads and dis...
[ "Changes I made:\n\nReplace treeView with self.treeView so I can access it easily in other methods.\nIn on_activated, create a new model with create_model, and set self.treeView to use that model using gtk.TreeView.set_model.\n\nIt seems to work. Code:\nimport gtk, os\n\nclass PyApp(gtk.Window): \n def __init__(...
[ 1 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python", "refresh" ]
stackoverflow_0006878944_gtk_gtktreeview_pygtk_python_refresh.txt
Q: Removing duplicates from a list of lists? Possible Duplicate: Python: removing duplicates from a list of lists What is the best way to remove duplicates from a list of lists? I was trying to use set like this: L1 = [['fox', 'dog'],['bat', 'rat'],['fox', 'dog']] L1 = list(set(L1)) Unfortunately, I get a TypeEr...
Removing duplicates from a list of lists?
Possible Duplicate: Python: removing duplicates from a list of lists What is the best way to remove duplicates from a list of lists? I was trying to use set like this: L1 = [['fox', 'dog'],['bat', 'rat'],['fox', 'dog']] L1 = list(set(L1)) Unfortunately, I get a TypeError: unhashable type: 'list'. In my list there...
[ "If you convert the inner lists to tuples you will be able to add them to a set successfully, for example:\n>>> set(map(tuple, L1))\nset([('fox', 'dog'), ('bat', 'rat')])\n\nIf necessary, you can get back to lists of lists like this:\n>>> map(list, set(map(tuple, L1)))\n[['fox', 'dog'], ['bat', 'rat']]\n\n" ]
[ 9 ]
[]
[]
[ "list", "python", "set" ]
stackoverflow_0006879806_list_python_set.txt
Q: vectorized indexing/slicing in numpy/scipy? I have an array A, and I have a list of slicing indices (s,t), let's called this list L. I want to find the 85 percentiles of A[s1:t1], A[s2:t2] ... Is there a way to vectorize these operations in numpy? ans = [] for (s,t) in L: ans.append( numpy.percentile( A[s:t]...
vectorized indexing/slicing in numpy/scipy?
I have an array A, and I have a list of slicing indices (s,t), let's called this list L. I want to find the 85 percentiles of A[s1:t1], A[s2:t2] ... Is there a way to vectorize these operations in numpy? ans = [] for (s,t) in L: ans.append( numpy.percentile( A[s:t], 85) ); looks cumbersome. Thanks a lot! PS: ...
[ "Given that you're dealing with a non-uniform interval (i.e. the slices aren't the same size), no, there's no way to have numpy do it in a single function call.\nIf it was a uniform slice size, then you could do so with various tricks, as @eat commented.\nHowever, what's wrong with a list comprehension? It's exact...
[ 1 ]
[]
[]
[ "numpy", "python", "scipy", "statistics", "vectorization" ]
stackoverflow_0006877008_numpy_python_scipy_statistics_vectorization.txt
Q: zlib module missing - python 2.4.3 I am trying to get simplejson installed on this python 2.4.3 - I cannot upgrade, I know it is old, there is nothing I can do about it, it is not my fault, please help. however when i do the ..\python.exe .\setup.py install i get: File "C:\Program Files (x86)\WorldViz\Vizard30\bi...
zlib module missing - python 2.4.3
I am trying to get simplejson installed on this python 2.4.3 - I cannot upgrade, I know it is old, there is nothing I can do about it, it is not my fault, please help. however when i do the ..\python.exe .\setup.py install i get: File "C:\Program Files (x86)\WorldViz\Vizard30\bin\lib\zipfile.py", line 188, in __init__...
[ "Copying the .py files into site-packages will get some stuff to work - particularly you can read files from an uncompressed zip archive, but you will not be able to inflate compressed files. The problem you are having is that ./config is not finding zlib.so (or possibly zlib.h) where it expects to find it and ski...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004060799_python.txt
Q: Arithmetic operations in regex I am using gedit regex plugin (Python style regex). I would like to do some arithmetic operation on a backreference to a group. For example: PART 1 DATA MODELS Chapter 2 Entity-Relationship Model 27 I would like to change it to be PART 1 DATA MODELS Chapter 25 2 Entity-Relationsh...
Arithmetic operations in regex
I am using gedit regex plugin (Python style regex). I would like to do some arithmetic operation on a backreference to a group. For example: PART 1 DATA MODELS Chapter 2 Entity-Relationship Model 27 I would like to change it to be PART 1 DATA MODELS Chapter 25 2 Entity-Relationship Model 27 My regex is ^(PART.*)\n...
[ "You can pass to re.sub lambda function which takes re.MatchObject object for every non-overlapping pattern match and returns replacement string. For example:\nimport re \nprint re.sub(\"(\\d+)\\+(\\d+)\",\n lambda m: str(int(m.group(1))+int(m.group(2))),\n \"If 2+2 is 4 then 1+2+3+4 is 1...
[ 13, 5, 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006824471_python_regex.txt