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: Normalising book titles - Python I have a list of books titles: "The Hobbit: 70th Anniversary Edition" "The Hobbit" "The Hobbit (Illustrated/Collector Edition)[There and Back Again]" "The Hobbit: or, There and Back Again" "The Hobbit: Gift Pack" and so on... I thought that if I normalised the titles somehow, it...
Normalising book titles - Python
I have a list of books titles: "The Hobbit: 70th Anniversary Edition" "The Hobbit" "The Hobbit (Illustrated/Collector Edition)[There and Back Again]" "The Hobbit: or, There and Back Again" "The Hobbit: Gift Pack" and so on... I thought that if I normalised the titles somehow, it would be easier to implement an autom...
[ "It depends completely on your data. For the examples you gave, a simple normalization solution could be:\nimport re\n\nbook_normalized = re.sub(r':.*|\\[.*?\\]|\\(.*?\\)|\\{.*?\\}', '', book_name).strip()\n\nThis will return \"The Hobbit\" for all the examples. What it does is remove anything after and including t...
[ 1, 1 ]
[]
[]
[ "data_cleaning", "django", "python", "string" ]
stackoverflow_0002458720_data_cleaning_django_python_string.txt
Q: Are Python properties broken? How can it be that this test case import unittest class PropTest(unittest.TestCase): def test(self): class C(): val = 'initial val' def get_p(self): return self.val def set_p(self, prop): if prop == 'le...
Are Python properties broken?
How can it be that this test case import unittest class PropTest(unittest.TestCase): def test(self): class C(): val = 'initial val' def get_p(self): return self.val def set_p(self, prop): if prop == 'legal val': self....
[ "Your class C does not inherit from object or any other new-style class, so it is an old-style class (and therefore does not support properties). Descriptors are for new-style classes only. To fix, change class C() to class C(object).\nhttp://www.python.org/download/releases/2.2.3/descrintro/ provides some details,...
[ 13 ]
[]
[]
[ "properties", "python" ]
stackoverflow_0002459715_properties_python.txt
Q: UTF-8 HTML and CSS files with BOM (and how to remove the BOM with Python) First, some background: I'm developing a web application using Python. All of my (text) files are currently stored in UTF-8 with the BOM. This includes all my HTML templates and CSS files. These resources are stored as binary data (BOM and a...
UTF-8 HTML and CSS files with BOM (and how to remove the BOM with Python)
First, some background: I'm developing a web application using Python. All of my (text) files are currently stored in UTF-8 with the BOM. This includes all my HTML templates and CSS files. These resources are stored as binary data (BOM and all) in my DB. When I retrieve the templates from the DB, I decode them using te...
[ "Since you state:\n\nAll of my (text) files are currently\n stored in UTF-8 with the BOM\n\nthen use the 'utf-8-sig' codec to decode them:\n>>> s = u'Hello, world!'.encode('utf-8-sig')\n>>> s\n'\\xef\\xbb\\xbfHello, world!'\n>>> s.decode('utf-8-sig')\nu'Hello, world!'\n\nIt automatically removes the expected BOM, ...
[ 24, 10, 1, 0 ]
[]
[]
[ "byte_order_mark", "file", "python", "utf_8" ]
stackoverflow_0002456380_byte_order_mark_file_python_utf_8.txt
Q: Troubleshooting 'ValueError: time data ... does not match format' when using datetime.strptime My input string is '16-MAR-2010 03:37:04' and i want to store it as datetime. I am trying to use: db_inst.HB_Create_Ship_Date = datetime.strptime(fields[7]," %d-%b-%Y %H:%M:%S ") fields[7] = '16-MAR-2010 03:37:04' I...
Troubleshooting 'ValueError: time data ... does not match format' when using datetime.strptime
My input string is '16-MAR-2010 03:37:04' and i want to store it as datetime. I am trying to use: db_inst.HB_Create_Ship_Date = datetime.strptime(fields[7]," %d-%b-%Y %H:%M:%S ") fields[7] = '16-MAR-2010 03:37:04' I am getting an error: ::ValueError: time data '16-MAR-2010 03:37:04' does not match format ' %d-%b-%...
[ "Edit:\nAs John mentions, make it easier on yourself and remove the leading and trailing spaces.\nAnother thought:\nYour current locale may not specify \"MAR\" as a month abbreviation.\nWhat does the output of this code give?:\nimport locale\nlocale.getdefaultlocale()\n\nI tested your code on a Linux machine (Ubunt...
[ 4, 2, 2, 0 ]
[]
[]
[ "python", "strptime" ]
stackoverflow_0002460233_python_strptime.txt
Q: In Python, if I have a unix timestamp, how do I insert that into a MySQL datetime field? I am using Python MySQLDB, and I want to insert this into DATETIME field in Mysql . How do I do that with cursor.execute? A: To convert from a UNIX timestamp to a Python datetime object, use datetime.fromtimestamp() (docume...
In Python, if I have a unix timestamp, how do I insert that into a MySQL datetime field?
I am using Python MySQLDB, and I want to insert this into DATETIME field in Mysql . How do I do that with cursor.execute?
[ "To convert from a UNIX timestamp to a Python datetime object, use datetime.fromtimestamp() (documentation).\n>>> from datetime import datetime\n>>> datetime.fromtimestamp(0)\ndatetime.datetime(1970, 1, 1, 1, 0)\n>>> datetime.fromtimestamp(1268816500)\ndatetime.datetime(2010, 3, 17, 10, 1, 40)\n\nFrom Python dateti...
[ 8, 3, 1 ]
[]
[]
[ "database", "date", "datetime", "mysql", "python" ]
stackoverflow_0002460491_database_date_datetime_mysql_python.txt
Q: Whats the best way to duplicate data in a django template? <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <h1>{% block title %}{% endblock %}</h1> </body> </html> This is my template, more or less. The h1 heading is always the same as the title tag. Th...
Whats the best way to duplicate data in a django template?
<html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <h1>{% block title %}{% endblock %}</h1> </body> </html> This is my template, more or less. The h1 heading is always the same as the title tag. The above snippet of code is not valid because there can't be two ...
[ "In base.html:\n<head>\n <title>{% block title %}{% endblock %}</title>\n</head>\n\n<body>\n <h1>{% block h1 %}{% endblock %}</h1>\n</body>\n\nThen, make another \"base\" layer on top of that called content_base.html (or something):\n{% extends \"base.html\" %}\n\n{% block h1 %}{% block title %}{% endblock %}{% e...
[ 24, 13, 8, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0001178743_django_django_templates_python.txt
Q: Is there a simple way to make lists behave as files (with ftplib) I'd like to use ftplib to upload program-generated data as lists. The nearest method I can see for doing this is ftp.storlines, but this requires a file object with a readlines() method. Obviously I could create a file, but this seems like overkill ...
Is there a simple way to make lists behave as files (with ftplib)
I'd like to use ftplib to upload program-generated data as lists. The nearest method I can see for doing this is ftp.storlines, but this requires a file object with a readlines() method. Obviously I could create a file, but this seems like overkill as the data isn't persistent. Is there anything that could do this?: se...
[ "You could always use StringIO (documentation), it is a memory buffer that is a file-like object.\nfrom io import StringIO # version < 2.6: from StringIO import StringIO\n\nbuffer = StringIO()\nbuffer.writelines(mylist)\nbuffer.seek(0)\n\nsession.storlines(\"...\", buffer)\n\nNote that the writelines method does...
[ 3 ]
[]
[]
[ "file_upload", "ftp", "iterator", "list", "python" ]
stackoverflow_0002461169_file_upload_ftp_iterator_list_python.txt
Q: django: search forms and redirect After processing form from POST I should redirect, to prevent user from hitting back. However, I am using form to determine search query on a database, so I need to either pass params to the redirected site or the result of a search. Or maybe there is some other good practice, how...
django: search forms and redirect
After processing form from POST I should redirect, to prevent user from hitting back. However, I am using form to determine search query on a database, so I need to either pass params to the redirected site or the result of a search. Or maybe there is some other good practice, how to solve this problem? Maybe in this s...
[ "Search queries should probably be GETs, rather than POSTs, because they are not changing anything - they are simply passing parameters to get certain information. POST should be reserved for forms that actually change things in the database, or result in a specific action (eg submitting an email).\nTo reply to you...
[ 3 ]
[]
[]
[ "django", "python", "redirect", "search_form" ]
stackoverflow_0002461364_django_python_redirect_search_form.txt
Q: Protocols/Interfaces in Ruby While coding in Ruby I did not really miss the type-orientedness of Java or C++ so far, but for some cases I think it is useful to have them. For Python there was a project PyProtocols which defined interfaces and protocols for objects. Does a similar initiative also exist for Ruby? I ...
Protocols/Interfaces in Ruby
While coding in Ruby I did not really miss the type-orientedness of Java or C++ so far, but for some cases I think it is useful to have them. For Python there was a project PyProtocols which defined interfaces and protocols for objects. Does a similar initiative also exist for Ruby? I would like to be able to declare t...
[ "Check project Ruby-Contract \nNot more work is happening on it. :(\n", "This might be interesting for the second part of your question:\nType checking in ruby\n" ]
[ 1, 1 ]
[]
[]
[ "interface", "python", "ruby", "types" ]
stackoverflow_0002461320_interface_python_ruby_types.txt
Q: Python style question, function parameters Which is preferred def method(self): or def method( self ): With spaces in the parenthesis. A: Check out PEP 8. It says to do the first one. A: The common reference for Python style is PEP8, see: http://www.python.org/dev/peps/pep-0008/ To answer your question sp...
Python style question, function parameters
Which is preferred def method(self): or def method( self ): With spaces in the parenthesis.
[ "Check out PEP 8. It says to do the first one.\n", "The common reference for Python style is PEP8, see: http://www.python.org/dev/peps/pep-0008/\nTo answer your question specifically, this is under \"Pet Peeves\":\nAvoid extraneous whitespace in the following situations:\n\nImmediately inside parentheses, bracke...
[ 16, 9, 3, 1, 1, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0001313694_coding_style_python.txt
Q: idiomatic way to take groups of n items from a list in Python? Given a list A = [1 2 3 4 5 6] Is there any idiomatic (Pythonic) way to iterate over it as though it were B = [(1, 2) (3, 4) (5, 6)] other than indexing? That feels like a holdover from C: for a1,a2 in [ (A[i], A[i+1]) for i in range(0, len(A), 2) ]:...
idiomatic way to take groups of n items from a list in Python?
Given a list A = [1 2 3 4 5 6] Is there any idiomatic (Pythonic) way to iterate over it as though it were B = [(1, 2) (3, 4) (5, 6)] other than indexing? That feels like a holdover from C: for a1,a2 in [ (A[i], A[i+1]) for i in range(0, len(A), 2) ]: I can't help but feel there should be some clever hack using itert...
[ "From http://docs.python.org/library/itertools.html:\nfrom itertools import izip_longest\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fillvalue, *args)\n\ni = grouper(3,range(100))\ni.next()\n(0, 1,...
[ 11 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0002461484_iteration_python.txt
Q: Python: Class factory using user input as class names I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasses should depend on user input. There is a superclass "Unit", to which I can add attr...
Python: Class factory using user input as class names
I want to add class atttributes to a superclass dynamically. Furthermore, I want to create classes that inherit from this superclass dynamically, and the name of those subclasses should depend on user input. There is a superclass "Unit", to which I can add attributes at runtime. This already works. def add_attr (cls,...
[ "To create a class from a name, use the class statement and assign the name. Observe:\ndef meta(name):\n class cls(Unit):\n pass\n\n cls.__name__ = name\n return cls\n\nNow I suppose I should explain myself, and so on. When you create a class using the class statement, it is done dynamically-- it is...
[ 14, 7 ]
[]
[]
[ "factory", "metaclass", "metaprogramming", "python" ]
stackoverflow_0002461751_factory_metaclass_metaprogramming_python.txt
Q: Logical python question - handling directories and files in them I'm using this function to extract files from .zip archive and store it on the server: def unzip_file_into_dir(file, dir): import sys, zipfile, os, os.path os.makedirs(dir, 0777) zfobj = zipfile.ZipFile(file) for name in zfobj.nameli...
Logical python question - handling directories and files in them
I'm using this function to extract files from .zip archive and store it on the server: def unzip_file_into_dir(file, dir): import sys, zipfile, os, os.path os.makedirs(dir, 0777) zfobj = zipfile.ZipFile(file) for name in zfobj.namelist(): if name.endswith('/'): os.mkdir(os.path.join...
[ "Use\noutfile = open(os.path.join(dir, os.path.basename(name)), 'wb')\n\nto strip the path from the name of the ZIP entry. This way, only the filename is left and you don't get any directories. You must also comment out the os.mkdir() or replace it with pass.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0002462078_python.txt
Q: Feedback on using Google App Engine? Looking to do a very small, quick 'n dirty side project. I like the fact that the Google App Engine is running on Python with Django built right in - gives me an excuse to try that platform... but my question is this: Has anyone made use of the app engine for anything other tha...
Feedback on using Google App Engine?
Looking to do a very small, quick 'n dirty side project. I like the fact that the Google App Engine is running on Python with Django built right in - gives me an excuse to try that platform... but my question is this: Has anyone made use of the app engine for anything other than a toy problem? I see some good example a...
[ "I have tried app engine for my small quake watch application\nhttp://quakewatch.appspot.com/\nMy purpose was to see the capabilities of app engine, so here are the main points:\n\nit doesn't come by default with Django, it has its own web framework which is pythonic has URL dispatcher like Django and it uses Djang...
[ 63, 36, 23, 12, 7, 7, 6, 4, 4, 4, 3 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0000110186_django_google_app_engine_python.txt
Q: Running a python script in background from a CGI I have a python CGI which runs some script in the background and shows the stdout in the html page. I run the script when the user clicks some button in the page. My problem is when the script starts running the page becomes busy and the user can't use the other cli...
Running a python script in background from a CGI
I have a python CGI which runs some script in the background and shows the stdout in the html page. I run the script when the user clicks some button in the page. My problem is when the script starts running the page becomes busy and the user can't use the other client side features in the page. What I want is: The scr...
[ "well, short answer: you can't.\nmedium answer: CGI sucks.\nlong answer: CGI works by running your script and returning whatever your script prints to the browser. If your script is still running, the browser will be waiting. If your script launches a background job and returns data to the browser, then the backgro...
[ 2 ]
[]
[]
[ "backgroundworker", "cgi", "python" ]
stackoverflow_0002461964_backgroundworker_cgi_python.txt
Q: How do I create a python module from a fortran program with f2py? I am trying to read some smps files with python, and found a fortran implementation, so I thought I would give f2py a shot. The problem is that I have no experience with fortran. I have successfully installed gfortran and f2py on my Linux box and ra...
How do I create a python module from a fortran program with f2py?
I am trying to read some smps files with python, and found a fortran implementation, so I thought I would give f2py a shot. The problem is that I have no experience with fortran. I have successfully installed gfortran and f2py on my Linux box and ran the example on thew f2py page, but I have some trouble compiling and ...
[ "I would suggest skipping the fortran business altogether.\nhttp://myweb.dal.ca/gassmann/smps2.htm\nThe MPS record layout is described here, and looks relatively simple to pick apart in Python.\nhttp://myweb.dal.ca/gassmann/smps2.htm#CoreMPSline\nYou'll have to define appropriate Python classes (or namedtuples) for...
[ 0 ]
[]
[]
[ "f2py", "fortran", "python" ]
stackoverflow_0002462354_f2py_fortran_python.txt
Q: How to implement full text search in Django? I would like to implement a search function in a django blogging application. The status quo is that I have a list of strings supplied by the user and the queryset is narrowed down by each string to include only those objects that match the string. See: if request.meth...
How to implement full text search in Django?
I would like to implement a search function in a django blogging application. The status quo is that I have a list of strings supplied by the user and the queryset is narrowed down by each string to include only those objects that match the string. See: if request.method == "POST": form = SearchForm(request.POST) ...
[ "I suggest you to adopt a search engine.\nWe've used Haystack search, a modular search application for django supporting many search engines (Solr, Xapian, Whoosh, etc...)\nAdvantages:\n\nFaster\nperform search queries even without querying the database.\nHighlight searched terms\n\"More like this\" functionality\n...
[ 16, 5, 4, 4, 2, 2 ]
[]
[]
[ "django", "django_queryset", "full_text_search", "python" ]
stackoverflow_0002461322_django_django_queryset_full_text_search_python.txt
Q: Python rounding issue I have come across a very strange issue in python. (Using python 2.4.x) In windows: >>> a = 2292.5 >>> print '%.0f' % a 2293 But in Solaris: >>> a = 2292.5 >>> print '%.0f' % a 2292 But this is the same in both windows and solaris: >>> a = 1.5 >>> print '%.0f' % a 2 Can someone explain thi...
Python rounding issue
I have come across a very strange issue in python. (Using python 2.4.x) In windows: >>> a = 2292.5 >>> print '%.0f' % a 2293 But in Solaris: >>> a = 2292.5 >>> print '%.0f' % a 2292 But this is the same in both windows and solaris: >>> a = 1.5 >>> print '%.0f' % a 2 Can someone explain this behavior? I'm guessing it...
[ "The function ultimately in charge of performing that formatting is PyOS_snprintf \n(see the sources). As you surmise, that's unfortunately system-dependent, i.e., it relies on vsprintf, vsnprintf or other similar functions that are ultimately supplied by the platform's C runtime library (I don't recall if the C s...
[ 10, 2, 0 ]
[]
[]
[ "python", "rounding" ]
stackoverflow_0002174081_python_rounding.txt
Q: Python: using a regular expression to match one line of HTML This simple Python method I put together just checks to see if Tomcat is running on one of our servers. import urllib2 import re import sys def tomcat_check(): tomcat_status = urllib2.urlopen('http://10.1.1.20:7880') results = tomcat_status.rea...
Python: using a regular expression to match one line of HTML
This simple Python method I put together just checks to see if Tomcat is running on one of our servers. import urllib2 import re import sys def tomcat_check(): tomcat_status = urllib2.urlopen('http://10.1.1.20:7880') results = tomcat_status.read() pattern = re.compile('<body>Tomcat is running...</body>',r...
[ "Why use regex here at all? Why not just a simple string search?:\nif not '<body>Tomcat is running...</body>' in results:\n notify_us()\n\n", "if not 'Tomcat is running' in results:\n notify_us()\n\n", "There are lots of different methods:\nstr.find()\nif results.find(\"Tomcat is running...\") != -1:\n ...
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0002463188_html_python_regex.txt
Q: Is there some good Twisted cheat sheets or reference cards? I'm recently started to learn Twisted framework and now looking for some cheat sheets/reference cards with basic Twisted stuff. Such as deferreds, callbacks, reactor, protocols, factories, transports, so on. At the moment found nothing neither on http://r...
Is there some good Twisted cheat sheets or reference cards?
I'm recently started to learn Twisted framework and now looking for some cheat sheets/reference cards with basic Twisted stuff. Such as deferreds, callbacks, reactor, protocols, factories, transports, so on. At the moment found nothing neither on http://refcardz.dzone.com/ nor on http://www.cheat-sheets.org/ Any help a...
[ "The closest thing I know of is Everything You Always Wanted to Know About Twisted\nIt's not really a \"cheat-sheet\", but it is a concise introduction to most of the basic concepts.\n" ]
[ 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002431932_python_twisted.txt
Q: Good Sound processing/Analysis/Capturing Modules We are working on Sound processing and Analysis where we need to extract frequencies, pitches, octaves and other parameters of sound including dBPowerSpectrum Analysis. We also need to do this irrespective of the file formats or do the conversion between quite a fi...
Good Sound processing/Analysis/Capturing Modules
We are working on Sound processing and Analysis where we need to extract frequencies, pitches, octaves and other parameters of sound including dBPowerSpectrum Analysis. We also need to do this irrespective of the file formats or do the conversion between quite a file format(though conversion is not a very critical req...
[ "See http://www.csounds.com/node/188 for a package that does much of this.\n", "For audio capture and playback I've liked PyAudio. It's cross-platform and pretty easy to use.\n", "You can use scikits audiolab to read in any file supported by libsndfile, and then use PyLab (NumPy and SciPy) to do the processing....
[ 2, 2, 1 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0000519851_audio_python.txt
Q: matplotlib: how to refresh figure.canvas I can't understand how to refresh FigureCanvasWxAgg instance. Here is the example: import wx import matplotlib from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.figure import Figure class MainFrame(wx.Frame): def __init__...
matplotlib: how to refresh figure.canvas
I can't understand how to refresh FigureCanvasWxAgg instance. Here is the example: import wx import matplotlib from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.figure import Figure class MainFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None,...
[ "As I said in the comments, I don't think that the figure canvas refresh is your problem, in fact I think it's doing exactly what it's supposed to (redrawing itself based on it's last state [ie as it was in your subplot]). I think your problem is more that the wxFrame is not refreshing.\nThe easiest way to fix tha...
[ 16 ]
[]
[]
[ "matplotlib", "python", "wxpython" ]
stackoverflow_0002441906_matplotlib_python_wxpython.txt
Q: How can we change a wx.MenuBar background and foreground colour using wxpython? I want to change the wxpython menubar colours. How can I do it? A: There are two ways Hard way , write your own custom menu bar from PyControl, position it at top of window, and create popup windows for submenus. Easier way: you can...
How can we change a wx.MenuBar background and foreground colour using wxpython?
I want to change the wxpython menubar colours. How can I do it?
[ "There are two ways\n\nHard way , write your own custom menu bar from PyControl, position it at top of window, and create popup windows for submenus.\nEasier way: you can use win32api to change system menu colors for your app. Here is an example showing that http://code.activestate.com/recipes/440507-changing-the-b...
[ 4 ]
[ "don't think it's doable -- it defaults to the platform's native look\n" ]
[ -1 ]
[ "python", "wxpython" ]
stackoverflow_0002439708_python_wxpython.txt
Q: Is it possible to put a wx.window (frame/panel) over a wx.MenuBar? I want to know if it's possible to put a frame or a panel over a menubar using wxpython? Thanks in advance! A: Your only chance is to write some Custom Menu, which could be bit difficult but doable. So basically instead of using system menu etc, ...
Is it possible to put a wx.window (frame/panel) over a wx.MenuBar?
I want to know if it's possible to put a frame or a panel over a menubar using wxpython? Thanks in advance!
[ "Your only chance is to write some Custom Menu, which could be bit difficult but doable. So basically instead of using system menu etc, you create windows inside your main frame which look like menu.\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002439677_python_wxpython.txt
Q: python FancyURLopener timeout is there a way to set connection timeout for FancyURLopener()? I'm using FancyURLopener.retrieve() to download a file, but sometimes it just stucks and that's all... I think this is because it's still trying to connect and it's not possible. So is there a way to set that timeout? Than...
python FancyURLopener timeout
is there a way to set connection timeout for FancyURLopener()? I'm using FancyURLopener.retrieve() to download a file, but sometimes it just stucks and that's all... I think this is because it's still trying to connect and it's not possible. So is there a way to set that timeout? Thanks for every reply
[ "If you want to use retrieve() with a timeout, you can set it in the socket module.\nimport socket\nsocket.setdefaulttimeout(5)\n\nSource: http://docs.python.org/py3k/howto/urllib2.html#sockets-and-layers\n", "Sorry, solved.\nI didn't realize that I could use something like this...\nfileName = string.split(url, '...
[ 4, 1 ]
[]
[]
[ "python", "timeout", "urllib" ]
stackoverflow_0002464020_python_timeout_urllib.txt
Q: Absolute path of a file object This has been discussed on StackOverflow before - I am trying to find a good way to find the absolute path of a file object, but I need it to be robust to os.chdir(), so cannot use f = file('test') os.path.abspath(f.name) Instead, I was wondering whether the following is a good sol...
Absolute path of a file object
This has been discussed on StackOverflow before - I am trying to find a good way to find the absolute path of a file object, but I need it to be robust to os.chdir(), so cannot use f = file('test') os.path.abspath(f.name) Instead, I was wondering whether the following is a good solution - basically extending the file...
[ "One significant risk is that, once the file is open, the process is dealing with that file by its file descriptor, not its path. On many operating systems, the file's path can be changed by some other process (by a mv operation in an unrelated process, say) and the file descriptor is still valid and refers to the ...
[ 14, 1 ]
[]
[]
[ "file", "filesystems", "python" ]
stackoverflow_0002458676_file_filesystems_python.txt
Q: Extract strings in python Basically, I want to extract the strings "AAA", "BBB", "CCC", "DDD" from a text file... ...... (other text goes here)..... <TD align="left" class=texttd><font class='textfont'>AAA</font></TD> ..... (useless text here)..... <TD align="left" class=texttd><font class='textfont'>BBB</font></T...
Extract strings in python
Basically, I want to extract the strings "AAA", "BBB", "CCC", "DDD" from a text file... ...... (other text goes here)..... <TD align="left" class=texttd><font class='textfont'>AAA</font></TD> ..... (useless text here)..... <TD align="left" class=texttd><font class='textfont'>BBB</font></TD> ....(more text)..... <TD ali...
[ "You could write a REGEX but it would be \"parsing\" the HTML to some extent. The problem with writing regular expressions for HTML is HTML is a mess. It's rarely perfect and this causes problems when you rely on it for data.\nI would personally use BeautifulSoup. It does do more than you're asking but also at supe...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "string", "text_extraction" ]
stackoverflow_0002464482_python_string_text_extraction.txt
Q: Print Tuple Index in Python This question falls into the "yes - this works, yes - this is ugly, yes - there is probably a better way" category. I want to use a regular expression to pull groups out of a match and then print the group number and the group value. It is to show someone how regular expressions work an...
Print Tuple Index in Python
This question falls into the "yes - this works, yes - this is ugly, yes - there is probably a better way" category. I want to use a regular expression to pull groups out of a match and then print the group number and the group value. It is to show someone how regular expressions work and to keep track of the values of ...
[ " for index, group in enumerate(FundTypeGroups):\n print \"%s: %s\" % (index, group)\n\n(and the variables should not start with a capital letter...)\n" ]
[ 3 ]
[]
[]
[ "indexing", "python", "tuples" ]
stackoverflow_0002464808_indexing_python_tuples.txt
Q: How to implement a master/watchdog script in python? I need it to open 10 processes, and each time one of them finishes I want to wait few seconds and start another one. It seems pretty simple, but somehow I can't get it to work. A: I'm not 100% clear on what you're trying to accomplish, but have you looked at t...
How to implement a master/watchdog script in python?
I need it to open 10 processes, and each time one of them finishes I want to wait few seconds and start another one. It seems pretty simple, but somehow I can't get it to work.
[ "I'm not 100% clear on what you're trying to accomplish, but have you looked at the multiprocessing module, specifically using a pool of workers?\n", "I've done this same thing to process web statistics using a semaphore. Essentially, as processes are created, the semaphore is incremented. When they exit, it's d...
[ 2, 1 ]
[]
[]
[ "python", "subprocess", "watchdog" ]
stackoverflow_0002464704_python_subprocess_watchdog.txt
Q: Python or matplotlib limitation error I wrote an algorithm using python and matplotlib that generates histograms from some text input data. When the number of data input is approx. greater than 15000, I get in the (append) line of my code: mydata = [] for i in range(len(data)): mydata.append(string.atof(data[i...
Python or matplotlib limitation error
I wrote an algorithm using python and matplotlib that generates histograms from some text input data. When the number of data input is approx. greater than 15000, I get in the (append) line of my code: mydata = [] for i in range(len(data)): mydata.append(string.atof(data[i])) the error: Traceback (most recent call...
[ "That's a data parsing error:\n>>> float(\"-a\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: invalid literal for float(): -a\n\nPython data structure size if only limited by the available memory.\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002464863_matplotlib_python.txt
Q: Python: Matching & Stripping port number from socket data I have data coming in to a python server via a socket. Within this data is the string '<port>80</port>' or which ever port is being used. I wish to extract the port number into a variable. The data coming in is not XML, I just used the tag approach to ident...
Python: Matching & Stripping port number from socket data
I have data coming in to a python server via a socket. Within this data is the string '<port>80</port>' or which ever port is being used. I wish to extract the port number into a variable. The data coming in is not XML, I just used the tag approach to identifying data for future XML use if needed. I do not wish to use ...
[ "Regex can't parse XML and shouldn't be used to parse fake XML. You should do one of\n\nUse a serialization method that is nicer to work with to start with, such as JSON or an ini file with the ConfigParser module.\nReally use XML and not something that just sort of looks like XML and really parse it with something...
[ 1, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002464670_python_sockets.txt
Q: Working with multiple input and output files in Python I need to open multiple files (2 input and 2 output files), do complex manipulations on the lines from input files and then append results at the end of 2 output files. I am currently using the following approach: in_1 = open(input_1) in_2 = open(input_2) out_...
Working with multiple input and output files in Python
I need to open multiple files (2 input and 2 output files), do complex manipulations on the lines from input files and then append results at the end of 2 output files. I am currently using the following approach: in_1 = open(input_1) in_2 = open(input_2) out_1 = open(output_1, "w") out_2 = open(output_2, "w") # Read ...
[ "contextlib.nested() allows you to chain multiple context managers in a single statement:\nwith contextlib.nested(open(...), open(...), ...) as (in_1, in_2, ...):\n ....\n\n" ]
[ 5 ]
[]
[]
[ "file", "python" ]
stackoverflow_0002465130_file_python.txt
Q: Verify key is correct using pyCrypto AES decryption How do I verify the correct key is being used to decrypt AES encrypted data using pyCrypto AES? cipher = AES.new(key, AES.MODE_CFB) cipher.decrypt(s) If an incorrect key is used, it still attempts to decrypt the data, obfuscating it more. Is there any test I can...
Verify key is correct using pyCrypto AES decryption
How do I verify the correct key is being used to decrypt AES encrypted data using pyCrypto AES? cipher = AES.new(key, AES.MODE_CFB) cipher.decrypt(s) If an incorrect key is used, it still attempts to decrypt the data, obfuscating it more. Is there any test I can do to prove the data is being decrypted to the original ...
[ "You could use Cipher-based Message Authentication Code (CMAC) or maybe an HMAC (Hash-based Message Authentication Code) (if you have a hash function available).\nThere are defined ways to combine encryption and authentication. See Authenticated Encryption (AE).\n", "I don't believe you can [tell if the key is co...
[ 8, 2, 0 ]
[]
[]
[ "aes", "cryptography", "encryption", "python" ]
stackoverflow_0001652127_aes_cryptography_encryption_python.txt
Q: Capture output from a mysql select statement using python Using Python2.4 I want to capture output from a mysql command. One caveat is that I need to pipe the SQL statement using an echo. echo 'SELECT user FROM mysql.user;' | mysql I see example using call, os.system, popen but what is best to use for my version ...
Capture output from a mysql select statement using python
Using Python2.4 I want to capture output from a mysql command. One caveat is that I need to pipe the SQL statement using an echo. echo 'SELECT user FROM mysql.user;' | mysql I see example using call, os.system, popen but what is best to use for my version of python and capturing the output in a tuple. Thanks
[ "The subprocess module is the most flexible tool for running commands and controlling the input and output. The following runs a command and captures the output as a list of lines:\nimport subprocess\n\np = subprocess.Popen(['/bin/bash', '-c', \"echo 'select user from mysql.user;' | mysql\" ],\n stdout=subproce...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002464792_python.txt
Q: python on usb stick Is there any free and open-source option to run python from an usb-stick on Windows system (i.e. python installed on an usb-stick ) and can run on any Windows system just by pluging-in the usb-stick? A: Try Portable Python.
python on usb stick
Is there any free and open-source option to run python from an usb-stick on Windows system (i.e. python installed on an usb-stick ) and can run on any Windows system just by pluging-in the usb-stick?
[ "Try Portable Python.\n" ]
[ 13 ]
[]
[]
[ "portable_applications", "python" ]
stackoverflow_0002465593_portable_applications_python.txt
Q: Django file upload failing occasionally I am trying to port my first Django 1.0.2 application to run on OSX/Leopard with Apache + mod_python 3.3.1 + python 2.6.1 (all running in 64-bit mode) and I am experiencing an occasional error when uploading a file that was not present when testing with the Django developmen...
Django file upload failing occasionally
I am trying to port my first Django 1.0.2 application to run on OSX/Leopard with Apache + mod_python 3.3.1 + python 2.6.1 (all running in 64-bit mode) and I am experiencing an occasional error when uploading a file that was not present when testing with the Django development server. The code for the upload is similar...
[ "Using mod_wsgi made the problem go away for Firefox. \nLimiting my research to an interaction problem between Apache and Safari, I stumbled upon this bug report for Apache https://bugs.webkit.org/show_bug.cgi?id=5760 that describes something very similar to what is happening and it is apparently still open. Readin...
[ 8, 1, 0, 0 ]
[]
[]
[ "apache", "django", "python" ]
stackoverflow_0000411902_apache_django_python.txt
Q: Stani's python editor- change syntax coloring Looking at Stani's Python IDE, it definitely comes bundled with tons of useful features. Except it doesn't let me do custom syntax coloring. From the Q&A on the author's site: "- changing colors is not supported unless you edit manually sm/wxp/stc.py" So I've attempte...
Stani's python editor- change syntax coloring
Looking at Stani's Python IDE, it definitely comes bundled with tons of useful features. Except it doesn't let me do custom syntax coloring. From the Q&A on the author's site: "- changing colors is not supported unless you edit manually sm/wxp/stc.py" So I've attempted to check out that code myself in my quest for the...
[ "The code I referred to above basically solves the issue, so I'll close the issue.\n" ]
[ 0 ]
[]
[]
[ "customization", "editor", "python", "syntax_highlighting" ]
stackoverflow_0002421793_customization_editor_python_syntax_highlighting.txt
Q: Custom keys for Google App Engine models (Python) First off, I'm relatively new to Google App Engine, so I'm probably doing something silly. Say I've got a model Foo: class Foo(db.Model): name = db.StringProperty() I want to use name as a unique key for every Foo object. How is this done? When I want to get a ...
Custom keys for Google App Engine models (Python)
First off, I'm relatively new to Google App Engine, so I'm probably doing something silly. Say I've got a model Foo: class Foo(db.Model): name = db.StringProperty() I want to use name as a unique key for every Foo object. How is this done? When I want to get a specific Foo object, I currently query the datastore fo...
[ "I've used the code below in a project before. It will work as long as the field on which you're basing your key name on is required.\nclass NamedModel(db.Model):\n \"\"\"A Model subclass for entities which automatically generate their own key\n names on creation. See documentation for _generate_key function...
[ 13, 2 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "primary_key", "python" ]
stackoverflow_0002465675_google_app_engine_google_cloud_datastore_primary_key_python.txt
Q: Call macro from Python script? One of our page templates is made up of a bunch of macros. These items are a bunch of html tables. Now, I want a couple of these tables in a Python script to create a PDF. Is there a way call a macro from a Python script and get back the HTML that is produced? If so, can you explain?...
Call macro from Python script?
One of our page templates is made up of a bunch of macros. These items are a bunch of html tables. Now, I want a couple of these tables in a Python script to create a PDF. Is there a way call a macro from a Python script and get back the HTML that is produced? If so, can you explain? Thanks Eric
[ "I'd probably use urllib.urlopen(url), pull the data from the page back to python and use BeautifulSoup to pull the table(s) out of the HTML... And then render that to PDF with XHTML2PDF (pisa.ho).\nThere might be a simpler way but for me, this would be the least stressful approach.\n", "Maybe you could create a ...
[ 0, 0 ]
[]
[]
[ "python", "zope" ]
stackoverflow_0002464442_python_zope.txt
Q: Will pywin32 extensions work on Windows 7? Will the pywin32 extensions work on Windows 7? If not, are there plans for Windows 7 extensions for Python? A: pywin32 extensions works fine on Windows 7.
Will pywin32 extensions work on Windows 7?
Will the pywin32 extensions work on Windows 7? If not, are there plans for Windows 7 extensions for Python?
[ "pywin32 extensions works fine on Windows 7.\n" ]
[ 1 ]
[]
[]
[ "python", "windows_7" ]
stackoverflow_0002466639_python_windows_7.txt
Q: RotatingFileHandler throws an exception when delay parameter is set When I run the following code under Python 2.6 import logging from logging.handlers import RotatingFileHandler rfh = RotatingFileHandler("testing.log", delay=True) logging.getLogger().addHandler(rfh) logging.warning("Boo!") then the last line th...
RotatingFileHandler throws an exception when delay parameter is set
When I run the following code under Python 2.6 import logging from logging.handlers import RotatingFileHandler rfh = RotatingFileHandler("testing.log", delay=True) logging.getLogger().addHandler(rfh) logging.warning("Boo!") then the last line throws AttributeError: RotatingFileHandler instance has no attribute 'level...
[ "I've investigated this issue: it was fixed in Python SVN r68829 dated 20 Jan, 2009. This was after the release of 2.6.1 but before the release of 2.6.2.\nPlease upgrade to Python 2.6.2, or a later version.\nI've updated the bug you filed. BTW the original bug report filed was #5013, which you could have found by s...
[ 5, 0 ]
[]
[]
[ "handlers", "logging", "python" ]
stackoverflow_0002465073_handlers_logging_python.txt
Q: Best way to get back to using the power of lxml after having to use a regex to find something in an html document I am trying to rip some text out of a large number of html documents (numbers in the hundreds of thousands). The documents are really forms but they are prepared by a very large group of different org...
Best way to get back to using the power of lxml after having to use a regex to find something in an html document
I am trying to rip some text out of a large number of html documents (numbers in the hundreds of thousands). The documents are really forms but they are prepared by a very large group of different organizations so there is significant variation in how they create the document. For example, the documents are divided i...
[ "Sometimes there is not a straight path to getting the content when dealing with poorly or inconsistently written HTML. \nYou might want to look at using lynx or one of the text-based browsers to dump the page content, either into a file, or to pipe it into your code, and then process it. Or, you can use lxml to lo...
[ 2, 1, 1 ]
[]
[]
[ "html_parsing", "lxml", "python", "regex" ]
stackoverflow_0002421396_html_parsing_lxml_python_regex.txt
Q: How to create a custom admin configuration panel in Django? I would like to create a configuration panel for the homepage of the web-app I'm designing with Django. This configuration panel should let me choose some basic options like highlighting some news, setting a showcase banner, and so on. Basically I don't n...
How to create a custom admin configuration panel in Django?
I would like to create a configuration panel for the homepage of the web-app I'm designing with Django. This configuration panel should let me choose some basic options like highlighting some news, setting a showcase banner, and so on. Basically I don't need an app with different rows, but just a panel page with some c...
[ "The admin area of Django features views and templates just like the rest of your Django site, so it's just a matter of customizing the relevant files.\nThis should be a helpful read for you.\nIn particular, the method that renders the index page can be found in django/contrib/admin/sites.py, and the actual index p...
[ 2, 2, 0 ]
[]
[]
[ "admin", "django", "panel", "python" ]
stackoverflow_0002455018_admin_django_panel_python.txt
Q: How to upload 6000 record to Google Datastore from csv file http://code.google.com/appengine/docs/python/tools/uploadingdata.html is not clearly understand. Where i should call the bulkloader.py or appcfg.py? Should i import the csv file to local Google App Engine SDK first? How to keep the upload and download dat...
How to upload 6000 record to Google Datastore from csv file
http://code.google.com/appengine/docs/python/tools/uploadingdata.html is not clearly understand. Where i should call the bulkloader.py or appcfg.py? Should i import the csv file to local Google App Engine SDK first? How to keep the upload and download data process in existing application for datastore synchronization?
[ "Set Up remote_api, the docs have instructions for both java and python and then run bulkloader.py locally :\nbulkloader.py --dump --app_id=<app-id> --url=http://<appname>.appspot.com/remote_api --filename=<data-filename>\n\nif you are using the java sdk, you will need to install the python sdk.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002466742_google_app_engine_google_cloud_datastore_python.txt
Q: What are some good ways to do intermachine locking? Our server cluster consists of 20 machines, each with 10 pids of 5 threads. We'd like some way to prevent any two threads, in any pid, on any machine, from modifying the same object at the same time. Our code's written in Python and runs on Linux, if that helps n...
What are some good ways to do intermachine locking?
Our server cluster consists of 20 machines, each with 10 pids of 5 threads. We'd like some way to prevent any two threads, in any pid, on any machine, from modifying the same object at the same time. Our code's written in Python and runs on Linux, if that helps narrow things down. Also, it's a pretty rare case that two...
[ "If you want to synchronize across machines you need a Distributed Lock Manager.\nI did some quick googling and came up with: Stackoverflow.\nUnfortunately they only suggest Java version, but it's a start.\nIf you are trying to synchronize access to files: Your filesystem should already have some wort of locking se...
[ 5, 3, 1, 0 ]
[ "There may be a better way of doing this, but i would use the Lock class from the threading module to access the \"protected\" objects in a with statement, here would be an example:\nfrom __future__ import with_statement \nfrom threading import Lock\n\nmylock = Lock()\nwith mylock.acquire():\n [ 'do things wi...
[ -4 ]
[ "linux", "multithreading", "mutex", "python" ]
stackoverflow_0002448984_linux_multithreading_mutex_python.txt
Q: slicing behaviour question of a list of lists I got a function like def f(): ... ... return [list1, list2] this returns a list of lists [[list1.item1,list1.item2,...],[list2.item1,list2.item2,...]] now when I do the following: for i in range(0,2):print f()[i][0:10] it works and print the lists slice...
slicing behaviour question of a list of lists
I got a function like def f(): ... ... return [list1, list2] this returns a list of lists [[list1.item1,list1.item2,...],[list2.item1,list2.item2,...]] now when I do the following: for i in range(0,2):print f()[i][0:10] it works and print the lists sliced but if i do print f()[0:2][0:10] then it prints ...
[ "The second slice slices the sequence returned from the first slice, so yes, you will have to loop somehow in order to slice within:\n[x[0:10] for x in f()[0:2]]\n\n", "The reason why these two behave differently is because f()[0:2][0:10] works like this:\n\nf() gives you a list of lists.\n[0:2] gives you a list ...
[ 10, 7, 0 ]
[]
[]
[ "function", "python", "slice" ]
stackoverflow_0002466941_function_python_slice.txt
Q: Log errors to database with Django on Google App Engine Is there a project that can log errors in requests to Django on Google App Engine to the datastore (like django-db-log or django.crashlog)? Thanks! A: Use the built-in google.appengine.ext.ereporter module: A logging handler that records information abou...
Log errors to database with Django on Google App Engine
Is there a project that can log errors in requests to Django on Google App Engine to the datastore (like django-db-log or django.crashlog)? Thanks!
[ "Use the built-in google.appengine.ext.ereporter module:\n\nA logging handler that records\n information about unique exceptions.\n'Unique' in this case is defined as a\n given (exception class, location)\n tuple. Unique exceptions are logged to\n the datastore with an example\n stacktrace and an approximate c...
[ 3, 1, 0 ]
[]
[]
[ "django", "error_handling", "google_app_engine", "logging", "python" ]
stackoverflow_0002459246_django_error_handling_google_app_engine_logging_python.txt
Q: What does this code from AuthKit do? (where are these functions and methods defined?) I am trying to implement my own authentication method for AuthKit and am trying to figure out how some of the built-in methods work. In particular, I'm trying to figure out how to update the REMOTE_USER for environ correctly. Thi...
What does this code from AuthKit do? (where are these functions and methods defined?)
I am trying to implement my own authentication method for AuthKit and am trying to figure out how some of the built-in methods work. In particular, I'm trying to figure out how to update the REMOTE_USER for environ correctly. This is how it is handled inside of authkit.authenticate.basic but it is pretty confusing. I c...
[ "Looking at that source I see it has an (evil)\nfrom paste.httpheaders import *\n\nthat is one way otherwise-mysterious barenames could suddenly appear in the code (which is exactly why this idiom is a very, very bad practice). I can't be sure that's how those identifiers suddenly and inexplicably materialize, but...
[ 1 ]
[]
[]
[ "authkit", "python" ]
stackoverflow_0002467013_authkit_python.txt
Q: GAE - Getting TypeError requiring class instance be passed to class's own method I'm really new to programming... I set up a class to give supporting information for Google's User API user object. I store this info in the datastore using db.model. When I call the okstatus method of my user_info class using this c...
GAE - Getting TypeError requiring class instance be passed to class's own method
I'm really new to programming... I set up a class to give supporting information for Google's User API user object. I store this info in the datastore using db.model. When I call the okstatus method of my user_info class using this code: elif user_info.okstatus(user): self.response.out.write("user allowed") I get...
[ "self must be an instance of the class. Since you never actually use it, you can simply make all of these methods into functions (and changing the self.status cases to just status).\nIf you're a \"class fetishist\", and absolutely insist on keeping the functions as methods in a class (rather than the module top-le...
[ 1 ]
[]
[]
[ "class", "google_app_engine", "methods", "python", "typeerror" ]
stackoverflow_0002467201_class_google_app_engine_methods_python_typeerror.txt
Q: Looping Redirect with PyFacebook and Google App Engine I have a Python Facebook project hosted on Google App Engine and use the following code to handle initialization of the Facebook API using PyFacebook. # Facebook Initialization def initialize_facebook(f): # Redirection handler def redirect(self, url):...
Looping Redirect with PyFacebook and Google App Engine
I have a Python Facebook project hosted on Google App Engine and use the following code to handle initialization of the Facebook API using PyFacebook. # Facebook Initialization def initialize_facebook(f): # Redirection handler def redirect(self, url): logger.info('Redirecting the user to: ' + url) ...
[ "I was just having the exact same thing happen to me today! What I think is happening is that fbapi.check_session() is not setting fbapi.added correctly. I don't think the Post-Add URL contains 'installed' anymore, but still has 'fb_sig_added'. The following change (github-esque code) in pyfacebook stopped the i...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "pyfacebook", "python", "redirect" ]
stackoverflow_0002349368_google_app_engine_pyfacebook_python_redirect.txt
Q: How powerful is x3d for making animations? I want to make a rotating drillbit animation that shows the complete process of drilling. I am not really sure that it can be done using x3d. How good is x3d (along with python scripting, maybe) to make such animations? A: I am not really sure that it can be done usin...
How powerful is x3d for making animations?
I want to make a rotating drillbit animation that shows the complete process of drilling. I am not really sure that it can be done using x3d. How good is x3d (along with python scripting, maybe) to make such animations?
[ "\nI am not really sure that it can be\n done using x3d. How good is x3d (along\n with python scripting, maybe) to make\n such animations?\n\nIf you are running a modern - developer version browser, then you can visit my home page mid-awe.com to see what I did with X3DOM. The animation was very simple with the F...
[ 0 ]
[]
[]
[ "animation", "python", "x3d" ]
stackoverflow_0002021055_animation_python_x3d.txt
Q: I want to find the span tag beween the LI tag and its attributes but no luck I want to find the span tag beween the LI tag and its attributes. Trying with beautful soap but no luck. Details of my code. Is any one point me right methodlogy In this this code, my getId function should return me id = "0_False-2" Any o...
I want to find the span tag beween the LI tag and its attributes but no luck
I want to find the span tag beween the LI tag and its attributes. Trying with beautful soap but no luck. Details of my code. Is any one point me right methodlogy In this this code, my getId function should return me id = "0_False-2" Any one know right method? from BeautifulSoup import BeautifulSoup as bs import re ht...
[ "I am sure someone can show you the BS way, but here's my approach. Just plain old Python string manipulation.\nhtml = '<ul>\\\n<li class=\"line\">&nbsp;</li>\\\n<li class=\"folder-open-last\" id=\"0\">\\\n<img style=\"float: left;\" class=\"trigger\" src=\"/media/images/spacer.gif\" border=\"0\">\\\n<span class=\"...
[ 0 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0002468278_beautifulsoup_html_python.txt
Q: Generating a list of values a regex COULD match in Python I'm trying to use a regex as an input, and from there generate all the possible values that the regex would match. So, for example, if the regex is "three-letter words starting with a, and ending in c," then the code would generate a list with the values [a...
Generating a list of values a regex COULD match in Python
I'm trying to use a regex as an input, and from there generate all the possible values that the regex would match. So, for example, if the regex is "three-letter words starting with a, and ending in c," then the code would generate a list with the values [aac, abc, acc, adc, a1c....]. Is there an easy way to do this? I...
[ "Here's a brute force solution that should work. It has a running time of O(L^max_length) (where L is the size of the alphabet), so use it at your own risk.\ndef all_matching_strings(alphabet, max_length, regex):\n\"\"\"Find the list of all strings over 'alphabet' of length up to 'max_length' that match 'regex'\"\"...
[ 8, 4, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002465719_python_regex.txt
Q: I want to select the distinct value from models field and then update them (django) I have models... class Item(models.Model): name = models.CharField('Item Name', max_length = 30) item_code = models.CharField(max_length = 10) color = models.CharField(max_length = 150, null = True, blank = True) si...
I want to select the distinct value from models field and then update them (django)
I have models... class Item(models.Model): name = models.CharField('Item Name', max_length = 30) item_code = models.CharField(max_length = 10) color = models.CharField(max_length = 150, null = True, blank = True) size = models.CharField(max_length = 30, null = True, blank = True) fabric_code = model...
[ "I don't really understand your question. Do you want to select distinct values for name, as in\nItem.objects.values('name').distinct()\n\n", "if you want to change a widget choices items, use something like this :\nchoices_list = Item.objects.values_list('name','name').distinct()\nform_item = forms.ModelChoiceFi...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002462962_django_django_models_python.txt
Q: Remove linebreak at specific position in textfile I have a large textfile, which has linebreaks at column 80 due to console width. Many of the lines in the textfile are not 80 characters long, and are not affected by the linebreak. In pseudocode, this is what I want: Iterate through lines in file If line matches ...
Remove linebreak at specific position in textfile
I have a large textfile, which has linebreaks at column 80 due to console width. Many of the lines in the textfile are not 80 characters long, and are not affected by the linebreak. In pseudocode, this is what I want: Iterate through lines in file If line matches this regex pattern: ^(.{80})\n(.+) Replace this line ...
[ "Here's some code which should to the trick\ndef remove_linebreaks(textfile, position=81):\n \"\"\"\n textfile : an file opened in 'r' mode\n position : the index on a line at which \\n must be removed\n\n return a string with the \\n at position removed\n \"\"\"\n fixed_lines = []\n for line i...
[ 1, 1, 1, 0 ]
[]
[]
[ "line_breaks", "python", "regex" ]
stackoverflow_0002468460_line_breaks_python_regex.txt
Q: How do I run Javascript tests in Windmill when using test_windmill for Django? I'm using the Windmill test system and have it running using test_windmill for Django which works fine for the Python tests. I'd like this to run a suite of Javascript tests also whilst the Django test server is running. I've used the r...
How do I run Javascript tests in Windmill when using test_windmill for Django?
I'm using the Windmill test system and have it running using test_windmill for Django which works fine for the Python tests. I'd like this to run a suite of Javascript tests also whilst the Django test server is running. I've used the run_js_tests call from the Windmill shell which works fine but I can't find a way to ...
[ "Ok, so couldn't find out how to do this so I'm running the website under Apache and using the windmill standard jstests parameter to run the Javascript tests against this.\n" ]
[ 0 ]
[]
[]
[ "automated_tests", "django", "python", "unit_testing", "windmill" ]
stackoverflow_0002373446_automated_tests_django_python_unit_testing_windmill.txt
Q: Finding the version of an application from Python? Basically i am trying to find out what version of ArcGIS the user currently has installed, i looked through the registry and couldn't find anything related to a version string. However i know it is stored, within the .exe. I've done a fair bit of googling, and ca...
Finding the version of an application from Python?
Basically i am trying to find out what version of ArcGIS the user currently has installed, i looked through the registry and couldn't find anything related to a version string. However i know it is stored, within the .exe. I've done a fair bit of googling, and can't find anything really worth it. I tried using the Get...
[ "If you prefer not to do this using pywin32, you would be able to do this with ctypes, for sure.\nThe trick will be decoding that silly file version structure that comes back.\nThere's one old mailing list post that is doing what you're asking. Unfortunately, I don't have a windows box handy to test this myself, ri...
[ 2, 0 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0002270345_python_winapi.txt
Q: What are good Python and/or Django deployment solutions? For now I use some mix between virtual_env, pip and Fabric. This allows to: install required libs; generate dynamic content; isolate installation; push everything through ssh. It works well, I just want to know if there are other tools around. The only pro...
What are good Python and/or Django deployment solutions?
For now I use some mix between virtual_env, pip and Fabric. This allows to: install required libs; generate dynamic content; isolate installation; push everything through ssh. It works well, I just want to know if there are other tools around. The only problem I could think of is that it's a lot of to set up every ti...
[ "Fabric is the best solution for you. You can do everything you need using Fabric.\n" ]
[ 1 ]
[]
[]
[ "deployment", "python" ]
stackoverflow_0002441661_deployment_python.txt
Q: merge excel cells using pyExcelerator I want to merge two cells in excel using pyExcelerator , ws.write_merge(r1=0,r2=1,c1=0, c2=0, label='test1', style=style1) #merge cell1(row=0, column=0) with cell2(row=1, column=0) Why the errors happen? AssertionErrors,0 < 0 errors A: Because the package auth...
merge excel cells using pyExcelerator
I want to merge two cells in excel using pyExcelerator , ws.write_merge(r1=0,r2=1,c1=0, c2=0, label='test1', style=style1) #merge cell1(row=0, column=0) with cell2(row=1, column=0) Why the errors happen? AssertionErrors,0 < 0 errors
[ "Because the package author put an assertion in Cell.py that would blow up if he ever tried to write a MULBLANKS record with too few columns. Your one-column-wide merged cells block stepped on the mine.\nSuggestion: Instead of pyExcelerator, use xlwt. xlwt is a fork of pyExcelerator, with many bugs fixed (including...
[ 3 ]
[]
[]
[ "pyexcelerator", "python", "xlwt" ]
stackoverflow_0002469167_pyexcelerator_python_xlwt.txt
Q: Default value for file path in function gives SyntaxError. Work around? for this, import os.path def f(data_file_path=os.path.join(os.getcwd(),'temp'),type): ... return data I get this, SyntaxError: non-default argument follows default argument Is there a way to make this work or do I have to define a v...
Default value for file path in function gives SyntaxError. Work around?
for this, import os.path def f(data_file_path=os.path.join(os.getcwd(),'temp'),type): ... return data I get this, SyntaxError: non-default argument follows default argument Is there a way to make this work or do I have to define a variable such as, rawdata_path = os.path.join(os.getcwd(),'temp') and then pl...
[ "Move type before data_file_path\ndef f(type,data_file_path=os.path.join(os.getcwd(),'temp')):\n\nAssigning values in the function parameter called default arguments, those should come afther non-default arguments\n", "You have to switch the order of the arguments. Mandatory arguments (without default values) mus...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "default_value", "function", "python" ]
stackoverflow_0002469538_default_value_function_python.txt
Q: Talking to printer from Python CGI I have a Python CGI. I want to print the data in the page. There will be a print button and when the user clicks teh button, I need to do some processing and send the data to the printer. I similarly want to implement 'Export to excel'. Please let me know how to do these A: Do ...
Talking to printer from Python CGI
I have a Python CGI. I want to print the data in the page. There will be a print button and when the user clicks teh button, I need to do some processing and send the data to the printer. I similarly want to implement 'Export to excel'. Please let me know how to do these
[ "Do you want to print to the user's printer, or the server's? If it's the user's, this is a job for client-side Javascript, not CGI.\n" ]
[ 1 ]
[]
[]
[ "cgi", "excel", "printing", "python" ]
stackoverflow_0002469368_cgi_excel_printing_python.txt
Q: Calculating a range of an exact number of values in Python I'm building a range between two numbers (floats) and I'd like this range to be of an exact fixed length (no more, no less). range and arange work with steps, instead. To put things into pseudo Python, this is what I'd like to achieve: start_value = -7.5 ...
Calculating a range of an exact number of values in Python
I'm building a range between two numbers (floats) and I'd like this range to be of an exact fixed length (no more, no less). range and arange work with steps, instead. To put things into pseudo Python, this is what I'd like to achieve: start_value = -7.5 end_value = 0.1 my_range = my_range_function(star_value, end_val...
[ "Use linspace() from NumPy.\n>>> from numpy import linspace\n>>> linspace(-7.5, 0.1, 6)\narray([-7.5 , -5.98, -4.46, -2.94, -1.42, 0.1])\n>>> linspace(-7.5, 0.1, 6).tolist()\n[-7.5, -5.9800000000000004, -4.46, -2.9399999999999995, -1.4199999999999999, 0.10000000000000001]\n\nIt should be the most efficient and acc...
[ 6, 4, 2, 1, 1 ]
[]
[]
[ "list", "python", "range" ]
stackoverflow_0002469461_list_python_range.txt
Q: Django store regular expression in DB which then gets evaluated on page I want to store a number of url patterns in my django model which a user can provide parameters to which will create a url. For example I might store these 3 urls in my db where %s is the variable parameter provided by the user: www.thisissom...
Django store regular expression in DB which then gets evaluated on page
I want to store a number of url patterns in my django model which a user can provide parameters to which will create a url. For example I might store these 3 urls in my db where %s is the variable parameter provided by the user: www.thisissomewebsite.com?param=%s www.anotherurl/%s/ www.lastexample.co.uk?param1=%s&fixe...
[ "ast.literal_eval() can be used to parse a string into a Python value or structure. If it's a list then just pass it to tuple() before using string interpolation.\n", ">>> param = [2, 6, 3]\n>>> pattern = 'www.url?param=%s&param2=%s&param3=%s'\n>>> url = pattern % tuple(param)\n>>> url\n'www.url?param=2&param2=6&...
[ 3, 1, 0 ]
[]
[]
[ "django", "python", "replace" ]
stackoverflow_0002469640_django_python_replace.txt
Q: How do I get javascript results using selenium? I have the following code: from selenium import selenium selenium = selenium("localhost", 4444, "*chrome", "http://some_site.com/") selenium.start() sel = selenium sel.open("/") sel.type("ctl00_ContentPlaceHolder1_SuburbTownTextBox", "Adelaide,SA,5000") sel.click("...
How do I get javascript results using selenium?
I have the following code: from selenium import selenium selenium = selenium("localhost", 4444, "*chrome", "http://some_site.com/") selenium.start() sel = selenium sel.open("/") sel.type("ctl00_ContentPlaceHolder1_SuburbTownTextBox", "Adelaide,SA,5000") sel.click("ctl00_ContentPlaceHolder1_SearchImageButton") #text ...
[ "try this to get the content of a html element with id=your-id :\nsel.get_eval(\"this.browserbot.getCurrentWindow().document.getElementById('your-id').innerHTML\"\n\n" ]
[ 4 ]
[]
[]
[ "javascript", "python", "selenium" ]
stackoverflow_0002469701_javascript_python_selenium.txt
Q: Python objects as userdata in ctypes callback functions The C function myfunc operates on a larger chunk of data. The results are returned in chunks to a callback function: int myfunc(const char *data, int (*callback)(char *result, void *userdata), void *userdata); Using ctypes, it's no big deal to call myfunc fr...
Python objects as userdata in ctypes callback functions
The C function myfunc operates on a larger chunk of data. The results are returned in chunks to a callback function: int myfunc(const char *data, int (*callback)(char *result, void *userdata), void *userdata); Using ctypes, it's no big deal to call myfunc from Python code, and to have the results being returned to a P...
[ "I guess you could use the Python C API to do that... maybe you could use a PyObject pointer.\nedit: As the op pointed out in the comments, there's already a py_object type readily available in ctypes, so the solution is to create first a ctypes.py_object object from the python list and then casting it to c_void_p ...
[ 4 ]
[]
[]
[ "callback", "ctypes", "python", "user_data" ]
stackoverflow_0002469975_callback_ctypes_python_user_data.txt
Q: How to check if two object are overlapping in a Canvas widget? Say I have objects within the Canvas with a tags 'stopped' and 'flying'. How do I check if any of this objects overlap each other? A: You can use the method find_overlapping find_overlapping(x1, y1, x2, y2) => tuple Returns a tuple of all items tha...
How to check if two object are overlapping in a Canvas widget?
Say I have objects within the Canvas with a tags 'stopped' and 'flying'. How do I check if any of this objects overlap each other?
[ "You can use the method find_overlapping\nfind_overlapping(x1, y1, x2, y2) => tuple\n\n\nReturns a tuple of all items that overlap the given rectangle, or that are \ncompletely enclosed by it.\n\n\nAnd then loop through the result list looking for your tag.\n" ]
[ 2 ]
[]
[]
[ "overlap", "python", "tkinter_canvas" ]
stackoverflow_0002470022_overlap_python_tkinter_canvas.txt
Q: Open-source implementation of Mersenne Twister in Python? Is there any good open-source implementation of Mersenne Twister and other good random number generators in Python available? I would like to use in for teaching math and comp sci majors? I am also looking for the corresponding theoretical support. Edit: S...
Open-source implementation of Mersenne Twister in Python?
Is there any good open-source implementation of Mersenne Twister and other good random number generators in Python available? I would like to use in for teaching math and comp sci majors? I am also looking for the corresponding theoretical support. Edit: Source code of Mersenne Twister is readily available in various ...
[ "Mersenne Twister is an implementation that is used by standard python library. You can see it in random.py file in your python distribution.\nOn my system (Ubuntu 9.10) it is in /usr/lib/python2.6, on Windows it should be in C:\\Python26\\Lib\n", "Found following port:\n#!/usr/bin/python\n\n## a C -> python tran...
[ 7, 5 ]
[]
[]
[ "mersenne_twister", "open_source", "python", "random" ]
stackoverflow_0002469031_mersenne_twister_open_source_python_random.txt
Q: OpenCV performance in different languages I'm doing some prototyping with OpenCV for a hobby project involving processing of real time camera data. I wonder if it is worth the effort to reimplement this in C or C++ when I have it all figured out or if no significant performance boost can be expected. The program b...
OpenCV performance in different languages
I'm doing some prototyping with OpenCV for a hobby project involving processing of real time camera data. I wonder if it is worth the effort to reimplement this in C or C++ when I have it all figured out or if no significant performance boost can be expected. The program basically chains OpenCV functions, so the main p...
[ "You've answered your own question pretty well. Most of the expensive computations should be within the OpenCV library, and thus independent of the language you use. \nIf you're really concerned about efficiency, you could profile your code and confirm that this is indeed the case. If need be, your custom processin...
[ 5, 0 ]
[]
[]
[ "c", "c++", "opencv", "performance", "python" ]
stackoverflow_0002432792_c_c++_opencv_performance_python.txt
Q: Error -3 while decompressing data: incorrect header check I have .zip file which contain csv data. I am reading .zip file using <input type = "file" name = "select_file"/> I want to decompress that .zip file and read csv data. file_data = self.request.get('select_file') file_str = zlib.decompress(file_data) #...
Error -3 while decompressing data: incorrect header check
I have .zip file which contain csv data. I am reading .zip file using <input type = "file" name = "select_file"/> I want to decompress that .zip file and read csv data. file_data = self.request.get('select_file') file_str = zlib.decompress(file_data) #file_data_list = file_str.split('\n') #file_Reader = csv.reader...
[ "Try making a zipfile.ZipFile object instead -- as the first argument, you need an open file-like object, so first make one out of your file_data bytes with cStringIO.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002470389_python.txt
Q: Can a python webapp be bundled into a single file for deployment? Is it possible for a python webapp to be bundled (gzipped?) into a single file, along with any required resources (js/css files) & modules (including modules like lxml which are mostly C-based), for easy deployment onto a linux webserver? A: Yes. ...
Can a python webapp be bundled into a single file for deployment?
Is it possible for a python webapp to be bundled (gzipped?) into a single file, along with any required resources (js/css files) & modules (including modules like lxml which are mostly C-based), for easy deployment onto a linux webserver?
[ "Yes. You can create a windows executable using py2exe. A better way to manage deployment is to package your app with a setup.py file, listing all needed dependencies, and listing non-python support files in the MANIFEST.in file. Then you can package it into a bundle using setup.py sdist, and install it with pip...
[ 1, 0, 0 ]
[]
[]
[ "deployment", "python" ]
stackoverflow_0002470182_deployment_python.txt
Q: python union of 2 nested lists with index I want to get the union of 2 nested lists plus an index to the common values. I have two lists like A = [[1,2,3],[4,5,6],[7,8,9]] and B = [[1,2,3,4],[3,3,5,7]] but the length of each list is about 100 000. To A belongs an index vector with len(A): I = [2,3,4] What I want i...
python union of 2 nested lists with index
I want to get the union of 2 nested lists plus an index to the common values. I have two lists like A = [[1,2,3],[4,5,6],[7,8,9]] and B = [[1,2,3,4],[3,3,5,7]] but the length of each list is about 100 000. To A belongs an index vector with len(A): I = [2,3,4] What I want is to find all sublists in B where the first 3 e...
[ "Create an auxiliary dict (work is O(len(A)) -- assuming the first three items of a sublist in A uniquely identify it (otherwise you need a dict of lists):\naud = dict((tuple(a[:3]), i) for i, a in enumerate(A))\n\nUse said dict to loop once on B (work is O(len(B))) to get B sublists and A indices:\nresult = [(b, a...
[ 1 ]
[]
[]
[ "dataset", "list", "nested", "python", "union" ]
stackoverflow_0002470764_dataset_list_nested_python_union.txt
Q: Artificial Intelligence in online game using Google App Engine I am currently in the planning stages of a game for google app engine, but cannot wrap my head around how I am going to handle AI. I intend to have persistant NPCs that will move about the map, but short of writing a program that generates the same XM...
Artificial Intelligence in online game using Google App Engine
I am currently in the planning stages of a game for google app engine, but cannot wrap my head around how I am going to handle AI. I intend to have persistant NPCs that will move about the map, but short of writing a program that generates the same XML requests I use to control player actions, than run it on another s...
[ "Will your game be turn based or real time?\nEither way, I think you have 2 options to look into. One is to use the Cron feature so you can schedule NPC updates at regular intervals, the other is to stick a \"update NPCs\" task into the Task Queue every time a human player moves.\n", "If the game is turn based t...
[ 3, 2, 2 ]
[]
[]
[ "artificial_intelligence", "google_app_engine", "python" ]
stackoverflow_0002465056_artificial_intelligence_google_app_engine_python.txt
Q: Problems with installing jcc and pylucene I'm trying to install pylucene on Windows XP. I installed JDK on C:\Programme\Java\jdk1.6.0_18 . I also installed Visual Studio C++ Express to have a C++ compiler. As first step I'm trying to integrate jcc into python2.6 through the command: C:\Python26\python.exe setup.py...
Problems with installing jcc and pylucene
I'm trying to install pylucene on Windows XP. I installed JDK on C:\Programme\Java\jdk1.6.0_18 . I also installed Visual Studio C++ Express to have a C++ compiler. As first step I'm trying to integrate jcc into python2.6 through the command: C:\Python26\python.exe setup.py build This gives me the following result: C:\I...
[ "Is there really a space in \"jav ac.exe\", as shown in the error message? Can setup.py just call javac.exe (is the java binaries directory in the PATH?)\nDisclaimer: I've built jcc and pylucene on mac os x and linux, but not on windows.\n" ]
[ 0 ]
[]
[]
[ "java", "jcc", "pylucene", "python" ]
stackoverflow_0002468872_java_jcc_pylucene_python.txt
Q: convert string of millisecond into datetime in python I am a newbie in Python. I want to subtract interval time from my log file, but the problem is I cannot convert millisecond string of log file into datetime format. For example, I have 15:55:05.12345 and I want to remove 5.12345 seconds from this string, and sh...
convert string of millisecond into datetime in python
I am a newbie in Python. I want to subtract interval time from my log file, but the problem is I cannot convert millisecond string of log file into datetime format. For example, I have 15:55:05.12345 and I want to remove 5.12345 seconds from this string, and show result of 15.55.00.00000 in Python. How can I do that? C...
[ ">>> import datetime\n>>> s = '15:55:05.12345'\n>>> datetime.datetime.strptime(s.rpartition('.')[0], '%H:%M:%S').strftime('%H.%M.00.00000')\n'15.55.00.00000'\n\nedit after clarification:\nthere is no way to do this with Python standard library, only working directly with strings:\n>>> s[:6]+ '00' + s[-6:]\n'15:55:0...
[ 1, 0 ]
[]
[]
[ "datetime", "python", "python_2.5" ]
stackoverflow_0002470784_datetime_python_python_2.5.txt
Q: How can I use python itertools.groupby() to group a list of strings by their first character? I have a list of strings similar to this list: tags = ('apples', 'apricots', 'oranges', 'pears', 'peaches') How should I go about grouping this list by the first character in each string using itertools.groupby()? How sh...
How can I use python itertools.groupby() to group a list of strings by their first character?
I have a list of strings similar to this list: tags = ('apples', 'apricots', 'oranges', 'pears', 'peaches') How should I go about grouping this list by the first character in each string using itertools.groupby()? How should I supply the 'key' argument required by itertools.groupby()?
[ "You might want to create dict afterwards:\nfrom itertools import groupby\n\nd = {k: list(v) for k, v in groupby(sorted(tags), key=lambda x: x[0])}\n\n", "groupby(sorted(tags), key=operator.itemgetter(0))\n\n", ">>> for i, j in itertools.groupby(tags, key=lambda x: x[0]):\n print(i, list(j))\n\n\na ['apples'...
[ 24, 16, 5, 1 ]
[]
[]
[ "python", "python_itertools", "string" ]
stackoverflow_0002472001_python_python_itertools_string.txt
Q: Producing a color map image using Python I have a working program in C++ that generates data for a Mandelbrot Set. I am able to get the color map image of the Mandelbrot set using gnuplot. In order to save the image, I just take a screenshot which doesn't give a very accurate image. how I can use a Python script i...
Producing a color map image using Python
I have a working program in C++ that generates data for a Mandelbrot Set. I am able to get the color map image of the Mandelbrot set using gnuplot. In order to save the image, I just take a screenshot which doesn't give a very accurate image. how I can use a Python script in order to produce and save the image.
[ "The Python Imaging Library is the standard means to produce 2D images and image files in Python.\n", "Source code Draw a Mandelbrot Set (Python)\nPIL and NumPy ofcourse ;)\n" ]
[ 0, 0 ]
[]
[]
[ "c", "image", "python" ]
stackoverflow_0002471899_c_image_python.txt
Q: Is there a functional way to do this? def flattenList(toFlatten): final=[] for el in toFlatten: if isinstance(el, list): final.extend(flattenList(el)) else: final.append(el) return final When I don't know how deeply the lists will nest, this is the only way I can think to do this. A: You should avo...
Is there a functional way to do this?
def flattenList(toFlatten): final=[] for el in toFlatten: if isinstance(el, list): final.extend(flattenList(el)) else: final.append(el) return final When I don't know how deeply the lists will nest, this is the only way I can think to do this.
[ "\nYou should avoid typechecking in Python. In this case, this means avoiding arbitrarily-nested structures where you distinguish by type. You can build your own node type which you can traverse by methods other than typechecking, like looking at a specific attribute.\nFor flattening one level or exactly n levels, ...
[ 7, 3, 2, 1 ]
[]
[]
[ "python", "sequences" ]
stackoverflow_0002471413_python_sequences.txt
Q: how can i edit and run the python nltk program how can i edit and run the python nltk program A: nltk is not a program (in the sense of something that you are intended to execute) but a library. You need to import the particular modules that you need and then call their functions, or construct their objects, or...
how can i edit and run the python nltk program
how can i edit and run the python nltk program
[ "nltk is not a program (in the sense of something that you are intended to execute) but a library. You need to import the particular modules that you need and then call their functions, or construct their objects, or whatever you want to do.\nThis article has some examples.\nNotice the first two lines of the first...
[ 4 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0002472313_nltk_python.txt
Q: How to get "paster request" to use config host value instead of localhost? I'm trying to access my pylons application via cron job to send notifications to my users. The way I'm doing this is by running the application using something like: paster request myconfig.ini /maintenance/do In the actual controller I ch...
How to get "paster request" to use config host value instead of localhost?
I'm trying to access my pylons application via cron job to send notifications to my users. The way I'm doing this is by running the application using something like: paster request myconfig.ini /maintenance/do In the actual controller I check for the "paste.command_request" to block public access. Everything works but...
[ "What I pretty much ended up doing was the following paster command:\npaster request myconfig.ini /maintenance/do --header=HOST:<USE_THIS_HOST>\n\nWhere is the domain name I wanted my users to see in their email. You can even add in the IP address if you are testing the application locally.\nI'm not sure if this i...
[ 1 ]
[]
[]
[ "paster", "pylons", "python", "routes" ]
stackoverflow_0002467021_paster_pylons_python_routes.txt
Q: subprocess isn't outputting anything I'm trying to use Python to run pdftotext, but for some reason, my code isn't working. If I run the below, I expect that the content variable would contain the contents of the PDF, but the result I am getting is just an empty string. Does anybody know what I'm missing? def get...
subprocess isn't outputting anything
I'm trying to use Python to run pdftotext, but for some reason, my code isn't working. If I run the below, I expect that the content variable would contain the contents of the PDF, but the result I am getting is just an empty string. Does anybody know what I'm missing? def getPDFContent(path): path = "/path/to/a v...
[ "By default pdftotext doesn't output anything on stdout, it instead creates a .txt file with the same base name as the pdf. To get the text on stdout, add - as a second parameter in the call to pdftotext:\nprocess = subprocess.Popen([\"pdftotext\", path, \"-\"], shell=False, \n stdout=subprocess.PIPE, stderr=sub...
[ 2 ]
[]
[]
[ "pdftotext", "python", "subprocess" ]
stackoverflow_0002472488_pdftotext_python_subprocess.txt
Q: Simple debugger, want work? i'm reading the Gray Hat Python,, i reach for this :: class debugger(): def __init__(self): self.h_process = None self.pid = None self.debugger_active = False def load(self,path_to_exe): creation_flags = DEBUG_PROCESS startupinfo = STARTU...
Simple debugger, want work?
i'm reading the Gray Hat Python,, i reach for this :: class debugger(): def __init__(self): self.h_process = None self.pid = None self.debugger_active = False def load(self,path_to_exe): creation_flags = DEBUG_PROCESS startupinfo = STARTUPINFO() process_informati...
[ "I suppose at a certain point, you changed name from attach to open_process (as it seems from the output of the traceback).\nIn this case, the error is here:\ndef open_process(self,pid): \n h_process = self.open_process(pid) \n\nAs you can see, it is recursively calling itself.\nIt seems to me that you have it f...
[ 1 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0002472409_debugging_python.txt
Q: Changing Element Value in Existing XML File Using DOM I am trying to find examples of how to change an existing xml files Element Value. Using the following xml example: <book> <title>My Book</title> <author>John Smith</author> </book> If I wanted to replace the author element value 'John Smith' with 'Jim Joh...
Changing Element Value in Existing XML File Using DOM
I am trying to find examples of how to change an existing xml files Element Value. Using the following xml example: <book> <title>My Book</title> <author>John Smith</author> </book> If I wanted to replace the author element value 'John Smith' with 'Jim Johnson' in a Python script using DOM, how would I go about do...
[ "Presuming\ns = '''\n<book>\n <title>My Book</title>\n <author>John Smith</author>\n</book>'''\n\nDOM would look like:\nfrom xml.dom import minidom\n\ndom = minidom.parseString(s) # or parse(filename_or_file)\nfor author in dom.getElementsByTagName('author'):\n author.childNodes = [dom.createTextNode(\"Jane Sm...
[ 5 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002472279_python_xml.txt
Q: In Sphinx, can I register a bunch of keywords that should always be translated into links? My doc strings have references to other python classes that I've defined. Every time Sphinx encounters one of these classes, I want it to insert a link to the documentation for that other class. Is this possible in Sphinx?...
In Sphinx, can I register a bunch of keywords that should always be translated into links?
My doc strings have references to other python classes that I've defined. Every time Sphinx encounters one of these classes, I want it to insert a link to the documentation for that other class. Is this possible in Sphinx? Specifically, I have a doc string like: '''This class contains a bunch of Foo objects''' I cou...
[ "You can use macros.\nIn my project, I have a header file that contains all \"important\" classes and global functions and their abbreviation. Two example lines:\n.. |PostItem| replace:: :class:`PostItem <hklib.PostItem>`\n.. |PostNotFoundError| replace:: :class:`PostNotFoundError <hklib.PostNotFoundError>`\n\nIn m...
[ 8, 2 ]
[]
[]
[ "python", "python_sphinx" ]
stackoverflow_0002472364_python_python_sphinx.txt
Q: "Bootstrap" python script in the Windows shell without .py / .pyw associations Sometimes (in customer's PCs) I need a python script to execute in the Windows shell like a .CMD or .BAT, but without having the .py or .pyw extensions associated with PYTHON / PYTHONW. I came out with a pair of 'quick'n dirty' solution...
"Bootstrap" python script in the Windows shell without .py / .pyw associations
Sometimes (in customer's PCs) I need a python script to execute in the Windows shell like a .CMD or .BAT, but without having the .py or .pyw extensions associated with PYTHON / PYTHONW. I came out with a pair of 'quick'n dirty' solutions: 1) """ e:\devtool\python\python.exe %0 :: or %PYTHONPATH%\python.exe goto eof: ""...
[ "You can try to create a script what is both python and windows shell script. In this case you can name you file my_flexible_script.bat and execute it either directly or via python ....\nSee a content of pylint.bat file from pylint:\n@echo off\nrem = \"\"\"-*-Python-*- script\nrem -------------------- DOS section -...
[ 10, 0 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0002472558_python_shell.txt
Q: paster errors after installing distribute 0.6.10 Been working on a Plone site for the last few weeks, it's the first time I've worked on one using buildout for recipes and paster for template generation, and it's been a learning curve. two days ago, everything was working fine. Yesterday, I started working from ...
paster errors after installing distribute 0.6.10
Been working on a Plone site for the last few weeks, it's the first time I've worked on one using buildout for recipes and paster for template generation, and it's been a learning curve. two days ago, everything was working fine. Yesterday, I started working from my known good source and used paster to generate boil...
[ "Turns out, the problem had to do with the new version of distribute apparently doesn't squash the old version correctly. I had to manually rename the old egg, delete teh new one, then re-install the new one.\n", "You're spot on to delete the distribute egg and reinstall.\nIf your easy_install produces a similar...
[ 3, 1, 0 ]
[]
[]
[ "distribute", "paster", "plone", "python" ]
stackoverflow_0001898055_distribute_paster_plone_python.txt
Q: python gui events out of order from Tkinter import * from tkMessageBox import * class Gui: def __init__(self, root): self.container = Frame(root) self.container.grid() self.inputText = Text(self.container, width=50, height=8) self.outputText = Text(self.container, width=50, height=8, bg='#E0E0E0', state=...
python gui events out of order
from Tkinter import * from tkMessageBox import * class Gui: def __init__(self, root): self.container = Frame(root) self.container.grid() self.inputText = Text(self.container, width=50, height=8) self.outputText = Text(self.container, width=50, height=8, bg='#E0E0E0', state=DISABLED) self.inputText.grid(row=...
[ "This is how bindings work (and that's a good thing), but your problem is easily solved. \nBindings are fired in the order specified by a widgets binding tags (also known as bind tags or bindtags). Unless you specify otherwise, the bindings happen in the following order:\n\nif there is a binding directly on the wid...
[ 4 ]
[]
[]
[ "events", "python", "tkinter", "user_interface" ]
stackoverflow_0002458026_events_python_tkinter_user_interface.txt
Q: Can generateDS be used like xsd.exe Can I use generateDS.py in python in a similar way that I would use xsd.exe to create C# classes from xsd? Basically, given an xsd schema I want to create a data structure, in python, fill its data in, and then render it into an xml string. perhaps pyXSD is better? oh, and yes, ...
Can generateDS be used like xsd.exe
Can I use generateDS.py in python in a similar way that I would use xsd.exe to create C# classes from xsd? Basically, given an xsd schema I want to create a data structure, in python, fill its data in, and then render it into an xml string. perhaps pyXSD is better? oh, and yes, I'm a python newbie
[ "generateDS did exactly what I wanted it to, a way to deal with a object graph of data, rather than a node graph\nran\npython generateDS.py -o MedicationDS.py medication.xsd\n\ngave me a python Class I could instantiate and populate with data, then render to a stream.\nmedObj = MedicationDS.Medication.factory()\nme...
[ 2 ]
[]
[]
[ "python", "xsd" ]
stackoverflow_0002368857_python_xsd.txt
Q: Cannot turn off autocommit in a script using the Django ORM I have a command line script that uses the Django ORM and MySQL backend. I want to turn off autocommit and commit manually. For the life of me, I cannot get this to work. Here is a pared down version of the script. A row is inserted into testtable eve...
Cannot turn off autocommit in a script using the Django ORM
I have a command line script that uses the Django ORM and MySQL backend. I want to turn off autocommit and commit manually. For the life of me, I cannot get this to work. Here is a pared down version of the script. A row is inserted into testtable every time I run this and I get this warning from MySQL: "Some non-t...
[ "Are your tables MyISAM or InnoDB? Remember that MyISAM isn't transactional, so can't be rolled back. See for example this page in the MySQL documentation:\n\nIn transactional terms, MyISAM tables effectively always operate in autocommit = 1 mode.\n\n" ]
[ 2 ]
[]
[]
[ "command_line", "django", "mysql", "python" ]
stackoverflow_0002473090_command_line_django_mysql_python.txt
Q: Python: write to file multiple times without open/close for each write How can i open file in python and write to it multiple times? I am using speech recognition, and i want one file to change its contents based on what i say. Other application needs to be able to read this file. Is there way to do this, or i nee...
Python: write to file multiple times without open/close for each write
How can i open file in python and write to it multiple times? I am using speech recognition, and i want one file to change its contents based on what i say. Other application needs to be able to read this file. Is there way to do this, or i need to open/close for each write?
[ "You can just keep the file object around and write to it whenever you want. You might need to flush it after each write to make things visible to the outside world.\nIf you do the writes from a different process, just open the file in append mode (\"a\").\n", "f = open('myfile.txt','w')\nf.write('Hi')\nf.write('...
[ 11, 7 ]
[]
[]
[ "file", "python" ]
stackoverflow_0002473202_file_python.txt
Q: How do I create self-relationships in polymorphic inheritance in Elixir and Pylons? I am new to programming and am following the example in the Pylons documentation on creating a Wiki. The database I want to link to the wiki was created with Elixir so I rewrote the Wiki database schema and have continued from ther...
How do I create self-relationships in polymorphic inheritance in Elixir and Pylons?
I am new to programming and am following the example in the Pylons documentation on creating a Wiki. The database I want to link to the wiki was created with Elixir so I rewrote the Wiki database schema and have continued from there. In the wiki there is a requirement for a Navigation table which is inherited by Pages ...
[ "I think that your model is mostly correct. The only thing I found is the link section from Nav->Page and back:\nclass Nav(Entity):\n section = OneToMany('Page', inverse='section')\nclass Page(Nav):\n section = ManyToOne('Nav', inverse='section')\n\nThe tutorial just that the Section (not Page) is the parent ...
[ 0 ]
[]
[]
[ "pylons", "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0002462049_pylons_python_python_elixir_sqlalchemy.txt
Q: Get the Model context of a Key object in Datastore (App Engine) I'd like to bypass some frequent queries by storing str(key) in memcache. When I get the encoded_key back from memcached, I can reconstruct the key with Key(encoded=encoded_key). But how can I query the actual object from the key? A possibility would ...
Get the Model context of a Key object in Datastore (App Engine)
I'd like to bypass some frequent queries by storing str(key) in memcache. When I get the encoded_key back from memcached, I can reconstruct the key with Key(encoded=encoded_key). But how can I query the actual object from the key? A possibility would be to use GqlQuery('SELECT * FROM ' + Key(encoded_key).kind() + \ ...
[ "Are you just storing the result of str(key) in memcached? If so, when you get it back, you should be able to just do db.get(key) to get the entity to which it points.\ndb.get() will take either a db.Key object or the string representation of a db.Key object (or a list of keys or key strings).\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002473632_google_app_engine_google_cloud_datastore_python.txt
Q: cpython: when PyDict_GetItem is called and when dict_subscript? I am reading cpython code for python 3k and I have noticed, that __missing__ is called only when dict_subscript is called, but not when PyDict_GetItem is used. What is the difference between those two methods and when each is called? If I pass an PyOb...
cpython: when PyDict_GetItem is called and when dict_subscript?
I am reading cpython code for python 3k and I have noticed, that __missing__ is called only when dict_subscript is called, but not when PyDict_GetItem is used. What is the difference between those two methods and when each is called? If I pass an PyObject that is a subclass of dict and has __missing__ method, how can I...
[ "Observations, guesses, etc:\nSame happens in Python 2.x.\ndict_subscript implements the equivalent of the high_level dict.__getitem__ method and thus will be called whenever adict[somekey] appears other than on the LHS of an assignment in Python code.\nPyDict_GetItem is part of the C API. Perhaps it's an oversight...
[ 1 ]
[]
[]
[ "cpython", "dictionary", "python" ]
stackoverflow_0002470928_cpython_dictionary_python.txt
Q: Python script web service timeout We have had a Python script running for many months now that simply scans through a directory of files, and posts each file to our web site via a web service call. The web site is also written in Python. For no apparent reason, this morning this script started throwing the followi...
Python script web service timeout
We have had a Python script running for many months now that simply scans through a directory of files, and posts each file to our web site via a web service call. The web site is also written in Python. For no apparent reason, this morning this script started throwing the following error: urllib2.URLError: <urlopen er...
[ "I think if it was working up until this point the suspect is not the code but the site. However, you may want to dig around in the code and write some debugging. The urllib2 module method urlopen throws the object URLError as you can see and has an attribute 'reason'. Beyond that I am not sure what you might do...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002473872_python.txt
Q: Ubuntu System Tray in Python How do I put a program in the system tray (I don't think it's called like that in Linux) in python TKINTER for UBUNTU 9.04. A: I don't believe you can do that using Tkinter. You will have to use the gtk libraries. An example, found on a Ubuntu forum: http://ubuntuforums.org/showpost....
Ubuntu System Tray in Python
How do I put a program in the system tray (I don't think it's called like that in Linux) in python TKINTER for UBUNTU 9.04.
[ "I don't believe you can do that using Tkinter. You will have to use the gtk libraries.\nAn example, found on a Ubuntu forum: http://ubuntuforums.org/showpost.php?s=bc369fc9343ae728577f1bdcd292caca&p=1053546&postcount=3\nHere's an example (in Perl) of combining gtk and Tk. Gtk handles the tray icon, and the rest of...
[ 8, 7, 3 ]
[]
[]
[ "linux", "python", "tkinter", "ubuntu" ]
stackoverflow_0002400432_linux_python_tkinter_ubuntu.txt
Q: How do I retrieve an automated report and save it to a database? I've got a web server that will take scripts in Python, PHP or Perl. I don't know much about any of those languages, but of the three, Python seems the least scary. It has a MySql database set up, and I know enough SQL to manage it and write querie...
How do I retrieve an automated report and save it to a database?
I've got a web server that will take scripts in Python, PHP or Perl. I don't know much about any of those languages, but of the three, Python seems the least scary. It has a MySql database set up, and I know enough SQL to manage it and write queries for it. I also have a program that I want to add automated error rep...
[ "I don't know python so I am showing you php.\nSo assuming your bug sending code posts to file.php?report=report+is+here\nThe following will work. \n<?\n\n # code to initialize the database here\n $rc = mysql_connect(...);\n\n if (!$rc)\n {\n die (\"Could not connect to the database.\");\n }\n\n // probably should...
[ 0, 0 ]
[]
[]
[ "error_reporting", "python" ]
stackoverflow_0002474062_error_reporting_python.txt
Q: Python to extract data from a file I am trying to extract the text between that has specific text file: ---- data1 data1 data1 extractme ---- data2 data2 data2 ---- data3 data3 extractme ---- and then dump it to text file so that ---- data1 data1 data1 extractme --- data3 data3 extractme --- Thanks for the hel...
Python to extract data from a file
I am trying to extract the text between that has specific text file: ---- data1 data1 data1 extractme ---- data2 data2 data2 ---- data3 data3 extractme ---- and then dump it to text file so that ---- data1 data1 data1 extractme --- data3 data3 extractme --- Thanks for the help.
[ "This works well enough for me. Your sample data is in a file called \"data.txt\" and the output goes to \"result.txt\"\ninFile = open(\"data.txt\")\noutFile = open(\"result.txt\", \"w\")\nbuffer = []\nkeepCurrentSet = True\nfor line in inFile:\n buffer.append(line)\n if line.startswith(\"----\"):\n #...
[ 6, 5, 2, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002474216_file_io_python.txt
Q: PyQt and unittest - how to handle signals and slots some small application I'm developing uses a module I have written to check certain web services via a REST API. I've been trying to add unit tests to it so I don't break stuff, and I stumbled upon a problem. I use a lot of signal-slot connections to perform oper...
PyQt and unittest - how to handle signals and slots
some small application I'm developing uses a module I have written to check certain web services via a REST API. I've been trying to add unit tests to it so I don't break stuff, and I stumbled upon a problem. I use a lot of signal-slot connections to perform operations asynchronously. For example a typical test would b...
[ "You need to avoid exiting the test method until the callback has been called. I believe the call is going to happen in a separate thread, so a threading.Event seems appropriate:\nimport threading\n\n...\n\ndef testConnection(self):\n \"Test connection and posts retrieved\"\n\n self.evt = threading.Event()\n...
[ 3 ]
[]
[]
[ "pyqt", "python", "unit_testing" ]
stackoverflow_0002473577_pyqt_python_unit_testing.txt
Q: Python 'datetime.datetime' object is unsubscriptable First, I am NOT a python developer. I am trying to fix an issue within a python script that is being executed from the command line. This script was written by someone who is no longer around, and no longer willing to help with issues. This is python 2.5, and f...
Python 'datetime.datetime' object is unsubscriptable
First, I am NOT a python developer. I am trying to fix an issue within a python script that is being executed from the command line. This script was written by someone who is no longer around, and no longer willing to help with issues. This is python 2.5, and for the moment it cannot be upgraded. Here are the lines of...
[ "It looks like you just want the time right? The datetime.strptime method returns a 'datetime' object and as such the following attributes contain the time: datetime.day, datetime.hour, datetime.year, etc.\n", "Its not the import fault. Its the *start_time[:6] *end_time[:6] that Python doesn't like. Replace it\...
[ 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002473760_python.txt
Q: Explicit disable MySQL query cache in some parts of program In a Django project, some cronjob programs are mainly used for administrative or analysis purposes, e.g. generating site usage stats, rotating user activities log, etc. We probably do not hope MySQL to cache queries in those programs to save memory usage...
Explicit disable MySQL query cache in some parts of program
In a Django project, some cronjob programs are mainly used for administrative or analysis purposes, e.g. generating site usage stats, rotating user activities log, etc. We probably do not hope MySQL to cache queries in those programs to save memory usage and improve query cache efficiency. Is it possible to turn off ...
[ "Per http://dev.mysql.com/doc/refman/5.1/en/query-cache-configuration.html\n\nIndividual clients can control cache behavior for their own connection by setting the SESSION query_cache_type value. For example, a client can disable use of the query cache for its own queries like this:\nmysql> SET SESSION query_cache...
[ 2 ]
[]
[]
[ "caching", "django", "mysql", "python" ]
stackoverflow_0002474609_caching_django_mysql_python.txt
Q: Python: speed up removal of every n-th element from list I'm trying to solve this programming riddle and although the solution (see code below) works correctly, it is too slow for succesful submission. Any pointers as how to make this run faster (removal of every n-th element from a list)? Or suggestions for a be...
Python: speed up removal of every n-th element from list
I'm trying to solve this programming riddle and although the solution (see code below) works correctly, it is too slow for succesful submission. Any pointers as how to make this run faster (removal of every n-th element from a list)? Or suggestions for a better algorithm to calculate the same; seems I can't think of a...
[ "This series is called ludic numbers\n__delslice__ should be faster than __setslice__+filter\n>>> L=[2,3,4,5,6,7,8,9,10,11,12]\n>>> lucky=[]\n>>> lucky.append(L[0])\n>>> del L[::L[0]]\n>>> L\n[3, 5, 7, 9, 11]\n>>> lucky.append(L[0])\n>>> del L[::L[0]]\n>>> L\n[5, 7, 11]\n\nSo the loop becomes.\nwhile len(luckynumbe...
[ 7, 4, 2, 1, 0 ]
[]
[]
[ "algorithm", "performance", "python" ]
stackoverflow_0002473710_algorithm_performance_python.txt