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: Django: sending GET messages I'm using Django 1.1 on a project, and I ran into a problem. I need to send a GET request to an external URL. I want to create a method that would act like this: def Send_msg(object): converted_url = "http://example.com/some/link/?title=" + object.title + "&bod...
Django: sending GET messages
I'm using Django 1.1 on a project, and I ran into a problem. I need to send a GET request to an external URL. I want to create a method that would act like this: def Send_msg(object): converted_url = "http://example.com/some/link/?title=" + object.title + "&body=" + object.body LoadURL(conv...
[ "def Send_msg(request, object):\n import urllib2, urllib\n base_url = \"http://example.com/some/link\"\n values = { 'title': object.title, 'body': object.body }\n data = urllib.urlencode(values)\n urllib2.urlopen(base_url+\"?\"+data).read() \n return HttpResponse()\n\nSomething like...
[ 3 ]
[]
[]
[ "django", "get", "python", "url" ]
stackoverflow_0006277459_django_get_python_url.txt
Q: Using nltk library to extract keywords I am working on an application that requires me to extract keywords (and finally generate a tag cloud of these words) from a stream of conversations. I am considering the following steps: Tokenize each raw conversation (output stored as List of List of strings) Remove stop w...
Using nltk library to extract keywords
I am working on an application that requires me to extract keywords (and finally generate a tag cloud of these words) from a stream of conversations. I am considering the following steps: Tokenize each raw conversation (output stored as List of List of strings) Remove stop words Use stemmer (Porter stemming algorithm)...
[ "I guess it depends on your definition of \"important\".\nIf you are talking about frequency, then you can just build a dictionary using words (or stems) as keys, and then counts as values. Afterwards, you can sort the keys in the dictionary based on their count.\nSomething like (not tested):\nfrom collections impo...
[ 3 ]
[]
[]
[ "cloud", "nltk", "python", "tags" ]
stackoverflow_0006277350_cloud_nltk_python_tags.txt
Q: How to get right HTML code from a concrete URL (python) Im trying to write a code, that will be able to verify domain through whois.domaintools.com. But theres a little problem with reading the html, that do not match with whois.domaintools.com/notregistereddomain.com source code. Whats wrong? Its problem with req...
How to get right HTML code from a concrete URL (python)
Im trying to write a code, that will be able to verify domain through whois.domaintools.com. But theres a little problem with reading the html, that do not match with whois.domaintools.com/notregistereddomain.com source code. Whats wrong? Its problem with requsting or what? I really dont know how to solve it. import ur...
[ "If you use print error instead of print error.read(), you'll see that you're getting a HTTP 403 \"Forbidden\" answer from the server.\nApparently this server doesn't like requests without a user-agent header (or it doesn't like Python's one because it doesn't want to be queried from a script). Here's a workaround:...
[ 2 ]
[]
[]
[ "html", "python", "url", "urllib" ]
stackoverflow_0006277816_html_python_url_urllib.txt
Q: Execute Unittest in Django I have written a small unit test for my django view .My project structure is like Project_name/ apps/ module1/ tests.py module2/ tests.py this is my dir structure i am executing the tests by using the com...
Execute Unittest in Django
I have written a small unit test for my django view .My project structure is like Project_name/ apps/ module1/ tests.py module2/ tests.py this is my dir structure i am executing the tests by using the command : $python manage.py test_co...
[ "The simplest solution is to add __init__.py file to tests/ package containing following lines:\nfrom .test_basic import *\nfrom .test_detail import *\n\nAnd then run all the tests with:\n$ python manage.py test module1\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_unittest", "python", "unit_testing" ]
stackoverflow_0006277761_django_django_unittest_python_unit_testing.txt
Q: How to make a python program path independent? from django.shortcuts import render_to_response from django.template import RequestContext from shapes.forms import UploadForm import os # TODO convert this to using ModelForm with a custom Django FileField # For now we just stick an uploaded shapefile into a project...
How to make a python program path independent?
from django.shortcuts import render_to_response from django.template import RequestContext from shapes.forms import UploadForm import os # TODO convert this to using ModelForm with a custom Django FileField # For now we just stick an uploaded shapefile into a project directory def upload(request): if request.meth...
[ "\nInstead of calling your unzip.py module in command line, call it directly as a python module (import unzip etc) to get the results of the unzip method. That should nedd only basic adaptations.\nYou can get the directory of a module via its __file__ parameter, as this other SO question shows. Note that this only ...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006277665_django_python.txt
Q: How to solve Python TypeError? This is my code below and I try to load data from one database to another. I believe everything works fine but an error occurs and I don't know what this means. import pymssql, psycopg2 class Datenbankabfrage: def __init__(self): self.conn1 = pymssql.connect(host='***', use...
How to solve Python TypeError?
This is my code below and I try to load data from one database to another. I believe everything works fine but an error occurs and I don't know what this means. import pymssql, psycopg2 class Datenbankabfrage: def __init__(self): self.conn1 = pymssql.connect(host='***', user='***', password='***', database='*...
[ "According to the documentation, executemany() takes two parameters. You have provided but one (query).\n\nexecutemany(operation, seq_of_parameters)\nPrepare a database operation (query or\n command) and then execute it against\n all parameter tuples or mappings found\n in the sequence seq_of_parameters.\nThe fu...
[ 8, 1 ]
[]
[]
[ "psycopg2", "python", "typeerror" ]
stackoverflow_0006278531_psycopg2_python_typeerror.txt
Q: are generators supported in RPython? Are generators supported in RPython, because I just read something in PyPy's documentation that says they are not PyPy Doc - Coding Guide They seem easy to be translated to a statically typed language like C because every generation step is generated in function call. Can someo...
are generators supported in RPython?
Are generators supported in RPython, because I just read something in PyPy's documentation that says they are not PyPy Doc - Coding Guide They seem easy to be translated to a statically typed language like C because every generation step is generated in function call. Can someone explain why ? Or shed some more light o...
[ "Generators are not supported simply because they were not needed at the time. The problem is not really having a roughly equivalent functionality in C, but needing to keep a frame of generator alive. Since RPython frames are translated to C frames, to support full python generators you would need some support for ...
[ 22 ]
[]
[]
[ "generator", "pypy", "python", "rpython" ]
stackoverflow_0006277174_generator_pypy_python_rpython.txt
Q: Changing the color of a QProgressbar() I was wondering whether it's possible to change the color of a PyQt Progressbar? I have the following code: from PyQt4 import QtGui, QtCore Pbar1 = QtGui.QProgressBar() Pbar1.setParent(Frame1) Pbar1.setGeometry(0, 0, 306, 30) Pbar1.setValue(Frame1Value) if Pbar1.value == 100 ...
Changing the color of a QProgressbar()
I was wondering whether it's possible to change the color of a PyQt Progressbar? I have the following code: from PyQt4 import QtGui, QtCore Pbar1 = QtGui.QProgressBar() Pbar1.setParent(Frame1) Pbar1.setGeometry(0, 0, 306, 30) Pbar1.setValue(Frame1Value) if Pbar1.value == 100 ......Pbar1.setColor(Red) Frame1Value is de...
[ "You can sublass QProgressBar and use some style sheet\nsee Customizing Qt Widgets Using Style Sheets and Customizing QProgressBar:\nfrom PyQt4 import QtGui, QtCore\n\nDEFAULT_STYLE = \"\"\"\nQProgressBar{\n border: 2px solid grey;\n border-radius: 5px;\n text-align: center\n}\n\nQProgressBar::chunk {\n ...
[ 9 ]
[]
[]
[ "progress_bar", "pyqt", "pyqt4", "python", "qprogressbar" ]
stackoverflow_0006277369_progress_bar_pyqt_pyqt4_python_qprogressbar.txt
Q: What could cause a UnicodeEncodeError exception to creep into a working Python environment? I have a method in my script that pulls a Twitter RSS feed, parses it with FeedPharser, wraps it in TwiML (Twilio-flavored XML) using the twilio module, and returns the resulting response in a CherryPy method via str(). Thi...
What could cause a UnicodeEncodeError exception to creep into a working Python environment?
I have a method in my script that pulls a Twitter RSS feed, parses it with FeedPharser, wraps it in TwiML (Twilio-flavored XML) using the twilio module, and returns the resulting response in a CherryPy method via str(). This works my fine in development environment (Kubuntu 10.10); I have had mixed results on my server...
[ "XML data cannot contain certain characters. An easy workaround is to wrap the data inside your XML tag that is giving you the error with CDATA. For example:\n<xmltag><![CDATA[Your content]]></xmltag>\n\nOr you can use numerical reference values ex &amp; for &\nMore information on this is available here:\nhttp://en...
[ 1, 0 ]
[]
[]
[ "cherrypy", "feedparser", "python" ]
stackoverflow_0006246850_cherrypy_feedparser_python.txt
Q: In Python, how do you conserve grouping when you sort by one value and then another? Data looks like this: Idx     score     group 5        0.85     Europe 8        0.77     Australia 12      0.70     S.America 13      0.71     Australia 42      0.82     Europe 45      0.90     Asia 65      0.91     Asia 73      0...
In Python, how do you conserve grouping when you sort by one value and then another?
Data looks like this: Idx     score     group 5        0.85     Europe 8        0.77     Australia 12      0.70     S.America 13      0.71     Australia 42      0.82     Europe 45      0.90     Asia 65      0.91     Asia 73      0.72     S.America 77      0.84     Asia Needs to look like this: Idx     score     group 6...
[ "I would just populate a dictionary with the maximum per group, and then sort on group maximum followed by individual score. Like this:\ndata = [\n (5 , 0.85, \"Europe\"),\n (8 , 0.77, \"Australia\"),\n (12, 0.70, \"S.America\"),\n (13, 0.71, \"Australia\"),\n (42, 0.82, \"Europe\"),\n (45, 0.90, \"Asia\"),\n...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "python", "sorteddictionary", "sortedlist", "sorting" ]
stackoverflow_0006274760_python_sorteddictionary_sortedlist_sorting.txt
Q: Have a server run a command every night, like a cron job in python I have run into a problem while writing my server program. I need to set a timeout for a socket that will increase every single day depending on when the socket checks in. The program will +1 to a variable that represents the dates passed since whe...
Have a server run a command every night, like a cron job in python
I have run into a problem while writing my server program. I need to set a timeout for a socket that will increase every single day depending on when the socket checks in. The program will +1 to a variable that represents the dates passed since when the server is first run. This variable will than be multiplied by 86,4...
[ "You need to create a seperate thread of execution for your socket communication to be handled in.\nhttp://www.devshed.com/c/a/Python/Basic-Threading-in-Python/\n" ]
[ 0 ]
[]
[]
[ "cron", "datetime", "python" ]
stackoverflow_0006279170_cron_datetime_python.txt
Q: Python beautiful Soup code not working I am trying this code in linux and its giving empty output. I have just coped and paste for BS docs import urllib2 from BeautifulSoup import BeautifulSoup soup = BeautifulSoup("""Bob's <b>Bold</b> Barbeque Sauce now available in <b class="hickory">Hi...
Python beautiful Soup code not working
I am trying this code in linux and its giving empty output. I have just coped and paste for BS docs import urllib2 from BeautifulSoup import BeautifulSoup soup = BeautifulSoup("""Bob's <b>Bold</b> Barbeque Sauce now available in <b class="hickory">Hickory</b> and <b class="lime">Lime</a>""") ...
[ "Your script won't output anything unless you print it. You need...\nprint soup.find(\"b\", { \"class\" : \"lime\" })\n\n(This is working here.)\n", "It works for me on Python 2.6 or 2.7 and BeautifulSoup 3.2.0.\n" ]
[ 4, 0 ]
[]
[]
[ "beautifulsoup", "linux", "python" ]
stackoverflow_0006279409_beautifulsoup_linux_python.txt
Q: Django ModelField for an object that is the target of ForgeinKeys on other objects I have some Django objects like this: class Award(Model): name = CharField(...) date = DateTimeField(...) class Book(Model): name = CharField(...) award = ForgeinKey(Award, blank=True) (i.e. each Book may or may not have o...
Django ModelField for an object that is the target of ForgeinKeys on other objects
I have some Django objects like this: class Award(Model): name = CharField(...) date = DateTimeField(...) class Book(Model): name = CharField(...) award = ForgeinKey(Award, blank=True) (i.e. each Book may or may not have one award) I want to make a form for adding/editing Awards. Assume lots of Books have al...
[ "I was just going to suggest using Inline's but upon re-reading your question the hard part is selecting objects that already exist and linking them to the Award that you are editing.\nThe way that you have suggested is the first way that I would do it, and the only other way I can think of would involve hacking aw...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_orm", "python" ]
stackoverflow_0006278111_django_django_forms_django_orm_python.txt
Q: How to install Python's flup on Windows for Apache? (to make web.py work) I recently began my work using web.py, but I'm stuck with a problem since web.py needs to have flup installed. I downloaded flup from http://www.saddi.com (download Link) and then extracted it to a folder on my desktop. I then navigate to ...
How to install Python's flup on Windows for Apache? (to make web.py work)
I recently began my work using web.py, but I'm stuck with a problem since web.py needs to have flup installed. I downloaded flup from http://www.saddi.com (download Link) and then extracted it to a folder on my desktop. I then navigate to the folder and run setup.py install. On success, I get an egg file in my C:\Pyt...
[ "You need to specify the address and port that you've configured apache to forward to. For example, if you configured Apache's FCGI to forward to 127.0.0.1:8080 you would do:\nweb.wsgi.runwsgi = lambda func, addr=('127.0.0.1', 8080): web.wsgi.runfcgi(func, addr)\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005133762_python.txt
Q: Creating "Comment" instances in Django for migration? I currently have a bunch of old comments, that I need to migrate to django.contrib.comment and the plan was to manually create instances of Comment and then save it as follows: # assume some_content is NOT a django Comment instance, but in some proprietary for...
Creating "Comment" instances in Django for migration?
I currently have a bunch of old comments, that I need to migrate to django.contrib.comment and the plan was to manually create instances of Comment and then save it as follows: # assume some_content is NOT a django Comment instance, but in some proprietary format # assume the model I'm attaching the comment to is call...
[ "From the documentation:\n\n\nset the content_type to an instance of ContentType of your model (the one you're attaching the comment to):\ncontent_type = ContentType.objects.get_for_model(Blog)\nset object_pk to the primary key of your object:\nobject_pk = myBlog_instance.pk\ncontent_object will point to these 2 fi...
[ 1 ]
[]
[]
[ "comments", "django", "django_comments", "python" ]
stackoverflow_0006279725_comments_django_django_comments_python.txt
Q: Volume level indicator in wxPython I'm writing a simple sound player, and I'd like have a volume level indicator that would show the current signal level of played sound. I'm able to feed the widget with the number from some range or percentage or anything. Actually as I have the information from the decoding pro...
Volume level indicator in wxPython
I'm writing a simple sound player, and I'd like have a volume level indicator that would show the current signal level of played sound. I'm able to feed the widget with the number from some range or percentage or anything. Actually as I have the information from the decoding process, I just need the widget to visualiz...
[ "You could use the PeakMeter for that. There's an example in the wxPython demo. Or you can find it in wx.lib.agw.peakmeter. Here's a page of documentation too: http://xoomer.virgilio.it/infinity77/AGW_Docs/peakmeter_module.html#peakmeter\nEDIT: I think I may have mis-read this. You can use a slider for a volume con...
[ 3 ]
[]
[]
[ "python", "volume", "widget", "wxpython" ]
stackoverflow_0006279691_python_volume_widget_wxpython.txt
Q: Problem with exiting a Word doc using Python This is my first time using this so be kind :) basically my question is I am making a program that opens many Microsoft Word 2007 docs and reads from a certain table in that document and writes that info to an excel file there is well in excess of 1000 word docs. I have...
Problem with exiting a Word doc using Python
This is my first time using this so be kind :) basically my question is I am making a program that opens many Microsoft Word 2007 docs and reads from a certain table in that document and writes that info to an excel file there is well in excess of 1000 word docs. I have all of this working but the only problem when I r...
[ "Before your MSWord.Quit did you try using:\nMSWord.ActiveWindow.Close\n\nOr even more simpley just doing\nMSWord.Quit\n\nI dont really understand if you are trying to close a document or the application.\n", "Basically, Python is not VBA, so this:\nMSWord.Documents.Close\n\nis equivalent to:\ngetattr(MSWord.Doc...
[ 1, 1, 0 ]
[]
[]
[ "excel", "ms_office", "ms_word", "python" ]
stackoverflow_0006278973_excel_ms_office_ms_word_python.txt
Q: Are there Python 2.4 bindings for WebDriver? Are there Python 2.4 bindings for WebDriver? My team is stuck using Python 2.4. Currently we're using Selenium's WebDriver to do web testing, but we use JPype to interface with Java bindings. This has resulted in us being unable to wait for pages to load, which means ...
Are there Python 2.4 bindings for WebDriver?
Are there Python 2.4 bindings for WebDriver? My team is stuck using Python 2.4. Currently we're using Selenium's WebDriver to do web testing, but we use JPype to interface with Java bindings. This has resulted in us being unable to wait for pages to load, which means we use sleeps instead, which dramatically increase...
[ "Seemingly no, but there is a version of JPype for Python 2.4, and JPype can be used to access the Java bindings to webdriver, so in that manner python 2.4 can be used with webdriver.\n" ]
[ 0 ]
[]
[]
[ "python", "webdriver" ]
stackoverflow_0006232338_python_webdriver.txt
Q: Controlling Selenium using Python - unable to use 'waits' We maintain a library used by test scripts which do system level testing. Part of the system under test is a website, and to navigate and interact with the website we use JPype to control Selenium 2.0's webdriver. Selenium 2.0 has a Java and C# interface,...
Controlling Selenium using Python - unable to use 'waits'
We maintain a library used by test scripts which do system level testing. Part of the system under test is a website, and to navigate and interact with the website we use JPype to control Selenium 2.0's webdriver. Selenium 2.0 has a Java and C# interface, and for the time being we can't rewrite out test library using...
[ "Maybe http://wiki.openqa.org/display/SEL/waitForCondition can satisfy your criteria?\n", "ImplicitlyWait through JPype and the Java bindings works, and can fulfill the required need here.\n" ]
[ 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0006208617_python_selenium.txt
Q: Suitable file format and tool for 3d modeling pipeline I'm working on a modeling/reconstruction algorithm for point cloud data. So far I've been developing in Python, and been relatively happy with VPython for my visualization needs. One problem I have is that VPython becomes quite slow when rendering a great many...
Suitable file format and tool for 3d modeling pipeline
I'm working on a modeling/reconstruction algorithm for point cloud data. So far I've been developing in Python, and been relatively happy with VPython for my visualization needs. One problem I have is that VPython becomes quite slow when rendering a great many objects (at least on my non-3d accelerated Linux laptop), m...
[ "I finally settled for Geomview: the viewer itself is powerful enough, and the many OOGL file formats that it implements answer my needs. I use the .off format for point cloud data, and .skel for my other modeling primitives. These file formats are also human-readable, which makes writing import/export functions ea...
[ 2, 1 ]
[]
[]
[ "3d", "file_format", "point_clouds", "python" ]
stackoverflow_0006269403_3d_file_format_point_clouds_python.txt
Q: How to capture all characters in binary string without python interpreting it Here is how I reproduce the problem: Create a log file called 'temp.log' and paste this line into it DEBUG: packetReceived '\x61\x62\x63' I want to have a script which will read the line from the log file and decode the binary string p...
How to capture all characters in binary string without python interpreting it
Here is how I reproduce the problem: Create a log file called 'temp.log' and paste this line into it DEBUG: packetReceived '\x61\x62\x63' I want to have a script which will read the line from the log file and decode the binary string part ('\x61\x62\x63'). For the decoding, I am using struct, so: struct.unpack('BBB...
[ "Python doesn't interpret strings that you pass to regular expressions. The escape sequences were most likely interpreted earlier, when you defined variable line. This works correctly for example:\nline = r\"DEBUG: packetReceived '\\x61\\x62\\x63'\"\nprint re.compile(r\"packetReceived '(.*)'\").search(line).group(1...
[ 5, 2, 1, 1 ]
[]
[]
[ "python", "regex", "struct" ]
stackoverflow_0006277762_python_regex_struct.txt
Q: Integrating cmd.cmdloop and gobject.MainLoop() So I have written a small console application based on cmd.Cmd. The application has a command loop triggered by cmd.cmdloop On the other hand, my console application uses dbus to launch remote processes. I'm trying to make the laumch asyncronous, but I get RuntimeErr...
Integrating cmd.cmdloop and gobject.MainLoop()
So I have written a small console application based on cmd.Cmd. The application has a command loop triggered by cmd.cmdloop On the other hand, my console application uses dbus to launch remote processes. I'm trying to make the laumch asyncronous, but I get RuntimeError: To make asynchronous calls, receive signals or e...
[ "It looks like cmd.cmdloop isn't a main loop, just a way to get input from a user over-and-over. Your best bet here, if you want to make this as asynchronous as possible, and you're already using dbus may be to have a client process which uses cmd.cmdloop and sends signals to another process that uses the gobject ...
[ 0 ]
[]
[]
[ "dbus", "python" ]
stackoverflow_0006271733_dbus_python.txt
Q: The view django_bookmarks.bookmarks.views.register_page didn't return an HttpResponse object The view django_bookmarks.bookmarks.views.register_page didn't return an HttpResponse object. How can I fix this problem? The code def register_page(request): if request.method =='POST': form = RegistrationForm...
The view django_bookmarks.bookmarks.views.register_page didn't return an HttpResponse object
The view django_bookmarks.bookmarks.views.register_page didn't return an HttpResponse object. How can I fix this problem? The code def register_page(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user( ...
[ "You should add an alternative for your \"if\" condition. What if request.method is not POST?:\ndef register_page(request):\n if request.method =='POST':\n ...\n else:\n form = RegistrationForm()\n return render_to_response(...)\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006279827_python.txt
Q: Inserting Line at Specified Position of a Text File I have a text file which looks like this: blah blah foo1 bar1 foo1 bar2 foo1 bar3 foo2 bar4 foo2 bar5 blah blah Now I want to insert 'foo bar' between 'foo1 bar3' and 'foo2 bar4'. This is how I did it: import shutil txt = '1.txt' tmptxt = '1.txt.tmp' with open...
Inserting Line at Specified Position of a Text File
I have a text file which looks like this: blah blah foo1 bar1 foo1 bar2 foo1 bar3 foo2 bar4 foo2 bar5 blah blah Now I want to insert 'foo bar' between 'foo1 bar3' and 'foo2 bar4'. This is how I did it: import shutil txt = '1.txt' tmptxt = '1.txt.tmp' with open(tmptxt, 'w') as outfile: with open(txt, 'r') as infi...
[ "The best way to make \"pseudo-inplace\" changes to a file in Python is with the fileinput module from the standard library:\nimport fileinput\n\nprocessing_foo1s = False\n\nfor line in fileinput.input('1.txt', inplace=1):\n if line.startswith('foo1'):\n processing_foo1s = True\n else:\n if processing_foo1s...
[ 60, 13, 9 ]
[]
[]
[ "insert", "python", "text" ]
stackoverflow_0001325905_insert_python_text.txt
Q: Cannot prettify scraped html in BeautifulSoup I have a small script that use urllib2 to get contents of a site, find all the link tags, appends a small piece of HTML in on the top and bottom, and then I try to prettify it. It keeps returning TypeError: sequence item 1: expected string, Tag found. I have looked aro...
Cannot prettify scraped html in BeautifulSoup
I have a small script that use urllib2 to get contents of a site, find all the link tags, appends a small piece of HTML in on the top and bottom, and then I try to prettify it. It keeps returning TypeError: sequence item 1: expected string, Tag found. I have looked around,i can't really find the issue. As always, any h...
[ "This works for me:\nsoup1 = BeautifulSoup(''.join(str(t) for t in tags)) \n\nThis pyparsing solution gives some decent output, too:\nfrom pyparsing import makeHTMLTags, originalTextFor, SkipTo, Combine\n\n# makeHTMLTags defines HTML tag patterns for given tag string\naTag,aEnd = makeHTMLTags(\"A\")\n\n# makeHTMLTa...
[ 2, 0, 0 ]
[]
[]
[ "beautifulsoup", "html", "parsing", "python" ]
stackoverflow_0002022014_beautifulsoup_html_parsing_python.txt
Q: New To Python (Programming) and Data Storage I have a question about data storage. I have a program that is creating a list of objects. What is the best way to store these on file so that the program can reload them later? I've tried to use Pickle, but I think I might be heading down the wrong alley and I keep ...
New To Python (Programming) and Data Storage
I have a question about data storage. I have a program that is creating a list of objects. What is the best way to store these on file so that the program can reload them later? I've tried to use Pickle, but I think I might be heading down the wrong alley and I keep getting this error when I try to read back the dat...
[ "I think the problem is that the line\nknowledge = pickle.load(open(\"data.txt\"))\n\ndoesn't open the file in binary mode. Python 3.2:\n>>> import pickle\n>>> \n>>> knowledge = {1:2, \"fred\": 19.3}\n>>> \n>>> with open(\"data.txt\", 'wb') as FILE:\n... pickle.dump(knowledge, FILE)\n... \n>>> knowledge2 = pic...
[ 9, 1, 0 ]
[ "You can use cPickle, or Picke it doesn't matter. Open in binary mode (rb) , and try setting the protocol to -1.\nTry something like this:\nimport cPickle\n\nmy_file= open('wohoo.file', 'wb')\n\nlargeObject= Magic() #insert your logic here\ncPickle.dump(largeObject, my_file, -1)\nmy_file.close()\n\nother_file = o...
[ -1 ]
[ "python", "python_3.x" ]
stackoverflow_0006280727_python_python_3.x.txt
Q: How to compare a Unicode string to an lxml element and a simple string? This is my code: for name in doc_preparate.cssselect('.dbl1:first-child'): if name.text != u"Продукция": print name.text I don't know why it doesn't work. Here is the result: Артрозан Продукция Пенталгин Продукция Пент...
How to compare a Unicode string to an lxml element and a simple string?
This is my code: for name in doc_preparate.cssselect('.dbl1:first-child'): if name.text != u"Продукция": print name.text I don't know why it doesn't work. Here is the result: Артрозан Продукция Пенталгин Продукция Пенталгин Продукция Пенталгин Продукция Пенталгин Продукция ... P.S. I tried thi...
[ "Probably because you are trying to do a string comparison with the equals sign. This has hidden issues, namely strings are lists of characters. This is more obvious in c, where if you compare to strings, you get bad results because you are comparing the pointer of your first string to the pointer of your second st...
[ 2, 0 ]
[]
[]
[ "compare", "python", "string" ]
stackoverflow_0006281484_compare_python_string.txt
Q: Efficient way to timeout waiting for a state change (variable change)? I'm sure this is somewhat common, so I am curious what are the accepted/efficient ways of doing this in Python. Put simply, I am just busy-waiting for a variable to be updated. At the same time I need a timeout scheme, but I feel there must be ...
Efficient way to timeout waiting for a state change (variable change)?
I'm sure this is somewhat common, so I am curious what are the accepted/efficient ways of doing this in Python. Put simply, I am just busy-waiting for a variable to be updated. At the same time I need a timeout scheme, but I feel there must be a better way of doing this. Currently I do something like this: wait_start =...
[ "Condition variables and events are often used for this type of thing. Both require cooperation from the side that's changing the variable.\n" ]
[ 1 ]
[]
[]
[ "performance", "python", "timeout" ]
stackoverflow_0006281670_performance_python_timeout.txt
Q: How to append and uniqify a tuple d1 = ({'x':1, 'y':2}, {'x':3, 'y':4}) d2 = ({'x':1, 'y':2}, {'x':5, 'y':6}, {'x':1, 'y':6, 'z':7}) I have two tuple d1 and d2. I know tuples are immutable. So I have to append another tuple using list. Is there any better solution. Next question is How to uniqify a tuple on keys ...
How to append and uniqify a tuple
d1 = ({'x':1, 'y':2}, {'x':3, 'y':4}) d2 = ({'x':1, 'y':2}, {'x':5, 'y':6}, {'x':1, 'y':6, 'z':7}) I have two tuple d1 and d2. I know tuples are immutable. So I have to append another tuple using list. Is there any better solution. Next question is How to uniqify a tuple on keys say 'x'. if 'x':1 in keys comes twice i...
[ "\nThere is no better way to extend a tuple. I would say if you are constantly doing this, you need to migrate away from a tuple, or change your design.\nYet again it sounds like you are using the wrong type of collection. But you could remove the duplicated keys from the dictionary using the existing SO answer Ho...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006281633_python.txt
Q: When running a python script from command line, PythonWin also runs. How can I avoid this? I'm trying to run a script from the command line (command prompt). I type: python.exe full_script_path.py parameters And for some reason, PythonWin opens up. I have to close it for execution to finish. Unfortunately, this k...
When running a python script from command line, PythonWin also runs. How can I avoid this?
I'm trying to run a script from the command line (command prompt). I type: python.exe full_script_path.py parameters And for some reason, PythonWin opens up. I have to close it for execution to finish. Unfortunately, this keeps me from being able to do multiple executions in a batch file. What can I do to avoid Python...
[ "I think you should launch pythonw.exe instead of plain python.exe, but I am not on a windows box right now, so I cannot test it.\n" ]
[ 1 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0006281886_command_line_python.txt
Q: Elements not visible in HTML? I'm trying to write a python web scraper that takes a pandora account and gets all the stations from it. However, the stations do not immediately all show up, and i need to click the show all button to view all of the stations. Moreover, even after i click the show all, the source cod...
Elements not visible in HTML?
I'm trying to write a python web scraper that takes a pandora account and gets all the stations from it. However, the stations do not immediately all show up, and i need to click the show all button to view all of the stations. Moreover, even after i click the show all, the source code remains unchanged! My question is...
[ "If you view the source from Firebug (if you use Firefox) or Inspector (if you use Safari or Chrome) you can see that the data is there. It's most likely being pulled in via ajax (JavaScript). \nYou would either need a scraper that understands JavaScript or to find the http ajax calls its making and call them yours...
[ 0 ]
[]
[]
[ "html", "javascript", "python", "web_scraping" ]
stackoverflow_0006281745_html_javascript_python_web_scraping.txt
Q: I want to rename a file that has a random part (in its filename) to a specific one I have some builds generating files, and they all have a random part in them (checksum number). How do I rename them to a unique name and execute them in Python? A: If you are sure there are never any underscores in the piece of t...
I want to rename a file that has a random part (in its filename) to a specific one
I have some builds generating files, and they all have a random part in them (checksum number). How do I rename them to a unique name and execute them in Python?
[ "If you are sure there are never any underscores in the piece of the name you would like to keep, you can split it. name = name.split('_')[0]. This won't of course preserve the file extension, but if all the output files are exes, you can just name += '.exe'\nEdit:\n\nfile_list = os.listdir('.')\nfor each in file_l...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006282123_python.txt
Q: API or library to get a snippet or summary from a webpage I want to give a URL and get a summary. Is there a library or an API to do this? I am working with Python, but I can port from other languages. A: Perhaps you're looking for something like urllib or urllib2? Both of those libraries allow you to retrieve i...
API or library to get a snippet or summary from a webpage
I want to give a URL and get a summary. Is there a library or an API to do this? I am working with Python, but I can port from other languages.
[ "Perhaps you're looking for something like urllib or urllib2?\nBoth of those libraries allow you to retrieve information from a specified URL. Here's a (slightly dated) introduction I found with a quick search.\nhttp://www.codercaste.com/2009/11/28/how-to-use-the-urllib-python-library-to-fetch-url-data-and-more/\n...
[ -1 ]
[]
[]
[ "data_extraction", "python", "summary" ]
stackoverflow_0006282108_data_extraction_python_summary.txt
Q: How to package a python program for distribution on a network I'm not sure if I'm even asking this question correctly. I just built my first real program and I want to make it available to people in my office. I'm not sure if I will have access to the shared server, but I was hoping I could simply package the prog...
How to package a python program for distribution on a network
I'm not sure if I'm even asking this question correctly. I just built my first real program and I want to make it available to people in my office. I'm not sure if I will have access to the shared server, but I was hoping I could simply package the program (I hope I'm using this term correctly) and upload it to a websi...
[ "PyInstaller or py2exe can package your Python program. \nBoth are actively maintained. PyInstaller is actively maintained. py2exe has not been updated for at least a year. I've used each with success. \nAlso there is cx_Freeze which I have not used.\n", "Take a look at http://www.py2exe.org/\n" ]
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006282519_python.txt
Q: Proper way to establish database connection in python I have a script with several functions that all need to make database calls. I'm trying to get better at writing clean code rather than just throwing together scripts with horrible style. What is generally considered the best way to establish a global database ...
Proper way to establish database connection in python
I have a script with several functions that all need to make database calls. I'm trying to get better at writing clean code rather than just throwing together scripts with horrible style. What is generally considered the best way to establish a global database connection that can be accessed anywhere in the script but ...
[ "If you are working with Python and databases, you cannot afford not to look at SQLAlchemy:\n\nSQLAlchemy is the Python SQL toolkit\n and Object Relational Mapper that\n gives application developers the full\n power and flexibility of SQL.\nIt provides a full suite of well known\n enterprise-level persistence p...
[ 3, 0 ]
[]
[]
[ "coding_style", "database", "mysql_python", "python" ]
stackoverflow_0006281732_coding_style_database_mysql_python_python.txt
Q: Using PHP/Python to access data from a remote telnet server over SSH I have a CentOS 5.5 server running a local telnet daemon (which is only accessible from localhost) which prints out a list of active users on our accounting system when sent the correct commands through telnet. I need to make this information ava...
Using PHP/Python to access data from a remote telnet server over SSH
I have a CentOS 5.5 server running a local telnet daemon (which is only accessible from localhost) which prints out a list of active users on our accounting system when sent the correct commands through telnet. I need to make this information available on our intranet website which uses PHP. I've written a Python scri...
[ "Why don't you redirect your stdout to a file. Then use your php website framework to read the file and display the results\n" ]
[ 0 ]
[]
[]
[ "php", "python", "ssh", "telnet" ]
stackoverflow_0006282891_php_python_ssh_telnet.txt
Q: wxPython - Getting attribute from another class? I want to update the self.CreateStatusBar() in MainWindow from MainPanel. And update the self.textOutput in MainPanel from MainWindow. Been reading alot, but still cant grasp it. Please help me. =) import wx ID_EXIT = 110 class MainPanel(wx.Panel): def __init...
wxPython - Getting attribute from another class?
I want to update the self.CreateStatusBar() in MainWindow from MainPanel. And update the self.textOutput in MainPanel from MainWindow. Been reading alot, but still cant grasp it. Please help me. =) import wx ID_EXIT = 110 class MainPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, pare...
[ "Generally speaking, UI elements shouldn't directly modify one another. In an event-driven application, UI elements can listen for events, and then perform some action following the event. Example: if the user does something to element B, element A can be notified of the event and then take an action.\nRead more ...
[ 2, 1, 0 ]
[]
[]
[ "attributes", "class", "get", "python", "wxpython" ]
stackoverflow_0006282654_attributes_class_get_python_wxpython.txt
Q: what's the best way to disguise a urllib2 query as a human request (beyond user-agent)? What's the best way to disguise a Python program using urllib2? I know how to set the user-agent which is a good start. But what about other items like the referring URL? Any way to set that? Any other suggestions? Here's w...
what's the best way to disguise a urllib2 query as a human request (beyond user-agent)?
What's the best way to disguise a Python program using urllib2? I know how to set the user-agent which is a good start. But what about other items like the referring URL? Any way to set that? Any other suggestions? Here's what I'm using to add the user-agent: opener = urllib2.build_opener() opener.addheaders = [('U...
[ "There are a lot of specifics that you haven't mentioned. To find your answers, simply go to www.domain.com in your favorite browser (with good dev tools), and examine the network traffic. \nChrome has built in tools. Firebug is for firefox.\nLook at all of the headers that were sent, and replicate as per your s...
[ 3, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0006283477_python_urllib2.txt
Q: Download / Parse Email with Python I am working on an email client and have run into a small problem. I am unsure of how to download the email messages and save them to the local HDD. I am able to connect to the server using IMAP4 SSL (with the code below). import imaplib server = imaplib.IMAP4_SSL('imap.gmail.com...
Download / Parse Email with Python
I am working on an email client and have run into a small problem. I am unsure of how to download the email messages and save them to the local HDD. I am able to connect to the server using IMAP4 SSL (with the code below). import imaplib server = imaplib.IMAP4_SSL('imap.gmail.com') server.login('USER', 'PASS')
[ "You can list directories in your mailbox with IMAP4.list. To actually get messages out of a directory use IMAP4.select, and then use IMAP4.search, and iterate over the list of id's it returns. In your case you could do something like this:\nserver.select('[Gmail]/All Mail')\nresp, items = server.search(None, \"(UN...
[ 8, 4 ]
[]
[]
[ "download", "email", "email_client", "gmail_imap", "python" ]
stackoverflow_0006282976_download_email_email_client_gmail_imap_python.txt
Q: How do you delete a lines within a file where range is determined using regular expressions in python? I am trying to clean up a series of text files by deleting unneeded lines. I want to delete lines starting with the line that matches Regex1 and keep deleting until the line with Regex2 is found. I need to do t...
How do you delete a lines within a file where range is determined using regular expressions in python?
I am trying to clean up a series of text files by deleting unneeded lines. I want to delete lines starting with the line that matches Regex1 and keep deleting until the line with Regex2 is found. I need to do this using python. I have already done this using a sed command something like sed -r '/regex1/,/regex2/d' ...
[ "You can do this by using re.DOTALL to make . match newlines:\nimport re\n\npattern = re.compile(r\"regex1.*?regex2\", re.DOTALL)\n\nYou can then use pattern.sub(\"\", data) to delete the lines.\n", "import sys,re\n\nreg_start = 'reg1'\nreg_end = 'reg2'\n\nto_print = 1\n\nfor line in sys.stdin.readlines():\n i...
[ 2, 2, 0 ]
[]
[]
[ "lines", "python", "regex" ]
stackoverflow_0006283299_lines_python_regex.txt
Q: Where is there a good discussion of using python packages? Is there a good discussion of setup.py and python packages from the package user perspective? Then maybe also from the package developer viewpoint too? A: The Hitchhiker's Guide to Packaging is a good read. Covers everything from creating your own packag...
Where is there a good discussion of using python packages?
Is there a good discussion of setup.py and python packages from the package user perspective? Then maybe also from the package developer viewpoint too?
[ "The Hitchhiker's Guide to Packaging is a good read. Covers everything from creating your own packaging to finding packages, installation, virtualenvs, etc.\n", "Strictly speaking, the valid (though subjective) answer for your question would be \"yes\".\nBut I think you need the links. Well, from the package deve...
[ 3, 1 ]
[]
[]
[ "installation", "package", "python" ]
stackoverflow_0006283251_installation_package_python.txt
Q: How do I use scipy.weave.inline together with external C libraries? I am trying to understand weave.inline to wrap C code in my Python programs. The code below simply takes the Numpy array and multiplicates all of its elements by 2. inl.py import numpy import scipy.weave a = numpy.array([1.0, 2.0, 3.0]) N = a.sh...
How do I use scipy.weave.inline together with external C libraries?
I am trying to understand weave.inline to wrap C code in my Python programs. The code below simply takes the Numpy array and multiplicates all of its elements by 2. inl.py import numpy import scipy.weave a = numpy.array([1.0, 2.0, 3.0]) N = a.shape[0] print a code = \ """ int i; for(i = 0; i < N; i++) { ...
[ "I have successfully done this, calling math functions from R via weave.inline() code (under Ubuntu Linux).\nFirst, compile your C functions as a shared library. In my case, I grabbed a recent release of R from CRAN, and did\n./configure --enable-R-static-lib --enable-static --with-readline=no\ncd src/nmath/standa...
[ 6, 1 ]
[]
[]
[ "c", "inline", "python", "scipy" ]
stackoverflow_0004260528_c_inline_python_scipy.txt
Q: Python and Exceptions Coming from a Java background, I like it when I was warned that I was not catching an exception, without having to read the documentation. And if I did read the documentation about a method, the exception thrown was shown right in the documentation's method signature. With Python I have to of...
Python and Exceptions
Coming from a Java background, I like it when I was warned that I was not catching an exception, without having to read the documentation. And if I did read the documentation about a method, the exception thrown was shown right in the documentation's method signature. With Python I have to often read through a paragrap...
[ "We love exceptions. They're a pretty important language feature. Good documentation will generally state what exceptions will be thrown in which cases, and personally I found most documentation to be good in this regard. Of course there's always some percentage of documentation that isn't good. Either way, if you'...
[ 14, 6, 5, 0, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0006283757_exception_python.txt
Q: Getting rid of artifacts/grid-lines when plotting 3d surfaces When plotting surfaces using mpl_toolkits.mplot3d.Axes3D.plot_surface(), lines appear that seem to follow the curve of the surfaces being plotted. For example: X, Y = numpy.meshgrid(numpy.arange(some_range), numpy.arange(some_other_range)) Z1, Z2 = nump...
Getting rid of artifacts/grid-lines when plotting 3d surfaces
When plotting surfaces using mpl_toolkits.mplot3d.Axes3D.plot_surface(), lines appear that seem to follow the curve of the surfaces being plotted. For example: X, Y = numpy.meshgrid(numpy.arange(some_range), numpy.arange(some_other_range)) Z1, Z2 = numpy.array(getRate()) #getRate is a function that returns an array of...
[ "Try\nax.plot_surface(X, Y, Z1, color='w', alpha=0.2, linewidth=0)\nax.plot_surface(X, Y, Z2, color='b', alpha=0.2, linewidth=0)\n\nYou may want to increase your alpha values a bit, though, if taking away the lines makes parts of the surfaces too hard to see.\n" ]
[ 7 ]
[]
[]
[ "matplotlib", "mplot3d", "python" ]
stackoverflow_0006283061_matplotlib_mplot3d_python.txt
Q: Get Attribute Name in For Loop How do I get the attribute names and values of an object? I'm attempting to cast it to a dictionary so that I can easily JSON serialize the object. Code: class User: ... def to_dict( self ): dict = {} for key, value in filter( lambda aname: not aname.startswit...
Get Attribute Name in For Loop
How do I get the attribute names and values of an object? I'm attempting to cast it to a dictionary so that I can easily JSON serialize the object. Code: class User: ... def to_dict( self ): dict = {} for key, value in filter( lambda aname: not aname.startswith('_'), dir(self) ): dic...
[ "You get that error because filter( lambda aname: not aname.startswith('_'), dir(u) ) returns a list of single items, and you are trying to unpack two values (for key, value). One potential reason to use dir instead of __dict__ might be that you care about class attrs, or inherited attrs. Since __dict__ only contai...
[ 3, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006283809_django_python.txt
Q: How to reference Python elixir object items I am trying to swap in the key name from a request.param for an Elixir object attribute. Below, the Elixir object bk is a Book() which has an attribute PrintTitle. PrintTitle also comes in from a form as a request.param. Rather than manually map all the parameters to t...
How to reference Python elixir object items
I am trying to swap in the key name from a request.param for an Elixir object attribute. Below, the Elixir object bk is a Book() which has an attribute PrintTitle. PrintTitle also comes in from a form as a request.param. Rather than manually map all the parameters to the Book attributes, I would like to map them base...
[ "Unfortunately you can't just set the attribute of a Python object with a variable in this way. One way to do this is to use the setattr method to accomplish this, for example here is a crude example:\nfrom elixir import *\n\nmetadata.bind = 'sqlite://'\nmetadata.bind.echo = False\n\nclass Book(Entity):\n Print...
[ 0 ]
[]
[]
[ "python", "python_elixir" ]
stackoverflow_0006281937_python_python_elixir.txt
Q: How to create and assign a Python variable in C? I've initialized the Python environment by Py_Initialize(); I have no external Python module imported into the environment and everything works well. But when I need to pass a C string into this environment, I am lost... I was thinking to add a function in the envi...
How to create and assign a Python variable in C?
I've initialized the Python environment by Py_Initialize(); I have no external Python module imported into the environment and everything works well. But when I need to pass a C string into this environment, I am lost... I was thinking to add a function in the environment to assign the variable like the following code...
[ "This should do what you want:\nchar *cStr = \"Some text here.\";\n\nPyObject *pyStr = Py_BuildValue(\"s\", cStr);\n\nhttp://docs.python.org/c-api/arg.html#Py_BuildValue\nOf course if you're using Python 3 (or use it in the future), there may be situations where you'd want to use \"y\" instead of \"s\" and get a by...
[ 2 ]
[]
[]
[ "c", "embed", "python" ]
stackoverflow_0006281781_c_embed_python.txt
Q: Using Windows API or WMI to determine if a process is displayed in the taskbar So, I'm writing a dock/taskbar like application. What I want to do is pretty simple, display a list of running programs. I've found lots of ways to enumerate all running processes, but after hours of google searching, I can't find a way...
Using Windows API or WMI to determine if a process is displayed in the taskbar
So, I'm writing a dock/taskbar like application. What I want to do is pretty simple, display a list of running programs. I've found lots of ways to enumerate all running processes, but after hours of google searching, I can't find a way to determine which of those should be displayed in a taskbar. Take for example the ...
[ "The rules for which top level windows appear in the taskbar are documented here. In summary:\n\nThe Shell creates a button on the\n taskbar whenever an application\n creates a window that isn't owned. To\n ensure that the window button is\n placed on the taskbar, create an\n unowned window with the WS_EX_ APP...
[ 6 ]
[]
[]
[ "python", "taskbar", "winapi", "windows" ]
stackoverflow_0006284197_python_taskbar_winapi_windows.txt
Q: Change newline character .readline() seeks Is it possible to change the newline character the .readline() method looks for while reading lines? I might have the need to read a stream from a file object that will be delimited in something other than newlines and it could be handy to get a chunk at a time. file ob...
Change newline character .readline() seeks
Is it possible to change the newline character the .readline() method looks for while reading lines? I might have the need to read a stream from a file object that will be delimited in something other than newlines and it could be handy to get a chunk at a time. file objects don't have a readuntil which I wouldn't ha...
[ "No. \nConsider creating a generator using file.read() and yielding chunks delimited by given character.\nEdit:\nThe sample you provided should work just fine. I would prefer to use a generator though:\ndef chunks(file, delim='\\n'):\n buf = bytearray(), \n while True:\n c = self.read(1)\n if c ...
[ 6 ]
[]
[]
[ "input", "python", "readline" ]
stackoverflow_0006284468_input_python_readline.txt
Q: RabbitMQ serializing messages from queue with multiple consumers I'm having a problem where I have a queue set up in shared mode and multiple consumers bound to it. The issue is that it appears that rabbitmq is serializing the messages, that is, only one consumer at a time is able to run. I need this to be paral...
RabbitMQ serializing messages from queue with multiple consumers
I'm having a problem where I have a queue set up in shared mode and multiple consumers bound to it. The issue is that it appears that rabbitmq is serializing the messages, that is, only one consumer at a time is able to run. I need this to be parallel, however, I can't seem to figure out how. Each consumer is running...
[ "what about prefetching (QOS)? on small queueus I give the appearance of parallelism by declaring the queue, getting the number of messages currently available, attaching a consumer, consuming the messages and then closing it once the number of messages has been consumed. Closing the channel without acknowledging t...
[ 0, 0 ]
[]
[]
[ "parallel_processing", "python", "rabbitmq" ]
stackoverflow_0002794994_parallel_processing_python_rabbitmq.txt
Q: Write unicode content and unicode file name in Windows #source file is encoded in utf8 import urllib2 import re req = urllib2.urlopen('http://people.w3.org/rishida/scripts/samples/hungarian.html') c = req.read()#.decode('utf-8') p = r'title="This is Latin script \(Hungarian language\)">(.+)' text = re.search(p, ...
Write unicode content and unicode file name in Windows
#source file is encoded in utf8 import urllib2 import re req = urllib2.urlopen('http://people.w3.org/rishida/scripts/samples/hungarian.html') c = req.read()#.decode('utf-8') p = r'title="This is Latin script \(Hungarian language\)">(.+)' text = re.search(p, c).group(1) name = text[:10]+'.txt' #file name will have s...
[ "The only problem for you seems to be just \"unreadable\" file name from your original source file. This can solve your problem:\nf = open(name.decode('utf-8').encode( sys.getfilesystemencoding() ) , 'wb')\n\n", "While winterTTR's answer does work.. I've realized that this approach is convoluted.\nRather, all you...
[ 4, 4 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0006274670_python_windows.txt
Q: show images on the templates of django using google app engine i am using google app engine with django to make a small application that it has these features upload images , show images , minipulate images (rotate) well after finishing part 1 , now i am somewhere stuck in part 2 where i need to show images....
show images on the templates of django using google app engine
i am using google app engine with django to make a small application that it has these features upload images , show images , minipulate images (rotate) well after finishing part 1 , now i am somewhere stuck in part 2 where i need to show images. i did everything i retrieved the image keys, but the images are not...
[ "Assuming\n\nYou uploaded the images to the blobstore\nimage.key is the blobstore key\nYou have a handler named BlobstoreImageHandler for /pictures/models\\.(.*)/\n\nThen you'd do something like\nclass BlobstoreImageHandler(blobstore.handler.BlobstoreDownloadHandler):\n def get(self, resource):\n resourse = str...
[ 1 ]
[]
[]
[ "django", "google_app_engine", "image", "python" ]
stackoverflow_0006284413_django_google_app_engine_image_python.txt
Q: Virtual Network Interface in Python Background: I have to set up some Epson receipt printers. The printers are configured by pointing your web browser to http://192.168.192.168/ and submitting a form. I wrote a Python script that can simulate a form POST, and the printers can now be configured without using the ...
Virtual Network Interface in Python
Background: I have to set up some Epson receipt printers. The printers are configured by pointing your web browser to http://192.168.192.168/ and submitting a form. I wrote a Python script that can simulate a form POST, and the printers can now be configured without using the web interface. The one drawback is that ...
[ "You have a problem that python cannot solve.\nIt sounds like your network has been administratively compartmentalized for some reason. If there is a firewall or a bastion-host machine connected to both administrative domains, you might be able to leverage Port Address Translation to keep this server on one networ...
[ 3 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0006284904_networking_python.txt
Q: Delete INI section in Python In python, I'm using win32api to read and write INI settings as and when they are required into specific sections based on IDs. Once I have finished with the section, I want to be able to delete the entire section from the INI file. How would I go about doing this using the win32api p...
Delete INI section in Python
In python, I'm using win32api to read and write INI settings as and when they are required into specific sections based on IDs. Once I have finished with the section, I want to be able to delete the entire section from the INI file. How would I go about doing this using the win32api python library?
[ "This is not a Python specific answer, but look into calling WritePrivateProfileString with the lpKeyName parameter set to NULL. With this parameter set to NULL the entire section named in lpAppName, including all entries within the section, is deleted.\n", "My proposal is to use native Python module for handling...
[ 1, 1 ]
[]
[]
[ "ini", "python", "winapi" ]
stackoverflow_0006281628_ini_python_winapi.txt
Q: Parse an email message to readable form Python Thanks to several users on here, I now am able to connect to the server via IMAP and download all of the unread messages. The problem, however, is that themessages are not in a readable form. Do I need to figure out a way to render the HTML in my application? Here is...
Parse an email message to readable form Python
Thanks to several users on here, I now am able to connect to the server via IMAP and download all of the unread messages. The problem, however, is that themessages are not in a readable form. Do I need to figure out a way to render the HTML in my application? Here is my code: import imaplib server = imaplib.IMAP4_SSL...
[ "Have a look at the email module. It can help you extract the data you want from the message body.\n" ]
[ 1 ]
[]
[]
[ "email", "gmail", "imap", "python" ]
stackoverflow_0006283938_email_gmail_imap_python.txt
Q: Python 2.5: IO module I would like to use Python's IO module. It was only introduced in Python 2.6 and I'm stuck with 2.5 for now. Is the particular IO module provided with Python 2.6 available as a separate module that can be used with 2.5? A: The IO module has undergone a number of significant revisions since ...
Python 2.5: IO module
I would like to use Python's IO module. It was only introduced in Python 2.6 and I'm stuck with 2.5 for now. Is the particular IO module provided with Python 2.6 available as a separate module that can be used with 2.5?
[ "The IO module has undergone a number of significant revisions since it was introduced. For Python 2.7 and 3.1, it was supplemented by a much faster C version and many bugs have been fixed. As far as I know, no one has attempted to back port the current version to 2.5. Unfortunately, your best bet is to use 2.7....
[ 2 ]
[]
[]
[ "io", "python" ]
stackoverflow_0006285525_io_python.txt
Q: Successful use of pidbox.Mailbox? Has anyone used pidbox.Mailbox ? I am attempting to do something similar to that example, but that documentation is way out of date. I have managed to get something that pubishes messages to a django transport but from there they never are successfuly received. I was hoping that ...
Successful use of pidbox.Mailbox?
Has anyone used pidbox.Mailbox ? I am attempting to do something similar to that example, but that documentation is way out of date. I have managed to get something that pubishes messages to a django transport but from there they never are successfuly received. I was hoping that someone knows how to use this, and coul...
[ "The answer to this is apparently no. If you come across this post I highly recommend writing your own. There is too little documentation for pidbox, and the documentation that is there is out of date.\n" ]
[ 0 ]
[]
[]
[ "django", "kombu", "python" ]
stackoverflow_0005424219_django_kombu_python.txt
Q: How can I use a cookie to enter and download a web page in Python How do I download a webpage using a cookie in Python. I am successfully using curl to do the job, but I would like to use a Python equivalent. I think pycurl should do it but I cant find an example that allows the user to input just a cookie. The cu...
How can I use a cookie to enter and download a web page in Python
How do I download a webpage using a cookie in Python. I am successfully using curl to do the job, but I would like to use a Python equivalent. I think pycurl should do it but I cant find an example that allows the user to input just a cookie. The curl bash line I am using is:- curl -b "*cookie*" http://www.example.com/...
[ "Use cookielib and Cookie modules in the standard library to create/store cookies, to actually make requests I recommend requests over urllib2 in the standard library.\nimport Cookie, cookielib, requests\n# create cookiejar\ncj = cookielib.CookieJar()\n# create cookie\nck = Cookie.SimpleCookie()\nck.name = 'value'\...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006285378_python.txt
Q: Why are the load averages for python threads varying for different linux cloud provider setups although the spec is the same? We have a Python application that polls directories using threads and inotify watchers. We have always run this application in a cloud server provided by Voxel (http://www.voxel.net). We ar...
Why are the load averages for python threads varying for different linux cloud provider setups although the spec is the same?
We have a Python application that polls directories using threads and inotify watchers. We have always run this application in a cloud server provided by Voxel (http://www.voxel.net). We are currently testing a different cloud server provider StormOnDemand (http://stormondemand.com) and when we ran our application, our...
[ "In general, trying to evaluate the multi-threading capabilities of a machine in a single Python interpreter is not a very good idea becasue of the GIL: at any time, only one of the threads of the interpreter is ready to run.\nNow load average on Linux is the exponential average of the number of runnable threads wi...
[ 1 ]
[]
[]
[ "multithreading", "performance", "python" ]
stackoverflow_0006186957_multithreading_performance_python.txt
Q: Reading 32 bit signed ieee 754 floating points from a binary file with python? I have a binary file which is simple a list of signed 32 bit ieee754 floating point numbers. They are not separated by anything, and simply appear one after another until EOF. How would I read from this file and interpret them correctl...
Reading 32 bit signed ieee 754 floating points from a binary file with python?
I have a binary file which is simple a list of signed 32 bit ieee754 floating point numbers. They are not separated by anything, and simply appear one after another until EOF. How would I read from this file and interpret them correctly as floating point numbers? I tried using read(4), but it automatically converts th...
[ "struct.unpack('f', file.read(4))\n\nYou can also unpack several at once, which will be faster:\nstruct.unpack('f'*n, file.read(4*n))\n\n", "Take a peek at struct.unpack. Something like the following might work...\nf = struct.unpack('f', data_read)\n\n", "import struct\n(num,) = struct.unpack('f', f.read(4))\n\...
[ 34, 5, 3 ]
[]
[]
[ "binaryfiles", "floating_point", "ieee_754", "parsing", "python" ]
stackoverflow_0006286033_binaryfiles_floating_point_ieee_754_parsing_python.txt
Q: AJAX uploads issue in Django app I have followed the tutorial posted here in order to get AJAX file uploads on my Django app. The thing is that it doesn't work, and the closest I could get to the issue is finding out that the save_upload() method raises the following exception: 'WSGIRequest' object has no attribut...
AJAX uploads issue in Django app
I have followed the tutorial posted here in order to get AJAX file uploads on my Django app. The thing is that it doesn't work, and the closest I could get to the issue is finding out that the save_upload() method raises the following exception: 'WSGIRequest' object has no attribute 'read'. Any ideas on what I am doing...
[ "I think I have gotten to the bottom of your problem.\n1) You are trying to run .read() on a request object, which is not allowed. Instead, you need to run it on request.raw_post_data.\n2) Before you can run .read(), which takes a file-like object, you need to convert it from a str to a file-like object.\nTry this...
[ 3 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0005050396_ajax_django_python.txt
Q: How does extending classes (Monkey Patching) work in Python? class Foo(object): pass foo = Foo() def bar(self): print 'bar' Foo.bar = bar foo.bar() #bar Coming from JavaScript, if a "class" prototype was augmented with a certain attribute. It is known that all instances of that "class" would have that attri...
How does extending classes (Monkey Patching) work in Python?
class Foo(object): pass foo = Foo() def bar(self): print 'bar' Foo.bar = bar foo.bar() #bar Coming from JavaScript, if a "class" prototype was augmented with a certain attribute. It is known that all instances of that "class" would have that attribute in its prototype chain, hence no modifications has to be done...
[ "The real question is, how can it not? In Python, classes are first-class objects in their own right. Attribute access on instances of a class is resolved by looking up attributes on the instance, and then the class, and then the parent classes (in the method resolution order.) These lookups are all done at runtime...
[ 11, 10 ]
[]
[]
[ "monkeypatching", "object", "oop", "python" ]
stackoverflow_0006286006_monkeypatching_object_oop_python.txt
Q: Installing Swampy on a Mac (OSX) using preinstalled Python version 2.6 I have the same exact problem outlined in this question: Mac Swampy (Python learning module) install But I still can't seem to finds simple enough instructions to install and run Swampy on my mac. I have absolutely no background in computer sci...
Installing Swampy on a Mac (OSX) using preinstalled Python version 2.6
I have the same exact problem outlined in this question: Mac Swampy (Python learning module) install But I still can't seem to finds simple enough instructions to install and run Swampy on my mac. I have absolutely no background in computer science/programming and am teaching myself Python from Allen Downey's book "Thi...
[ "TO future programmers lost in the dark on this path, simply check out this wonderfully simple set of intructions by a prof at UCSB:http://www.cs.ucsb.edu/~pconrad/cs5nm/08F/ex10.html\n\nI was once blind, but now I see.\n\n" ]
[ 0 ]
[]
[]
[ "installation", "macos", "python", "swampy" ]
stackoverflow_0006259309_installation_macos_python_swampy.txt
Q: Python subprocess + scp - can't read all output I'm trying to SCP a file between machines and I need to fail when the user hasn't set up a private/public certificate to do passwordless logins. Unfortunatly, using subprocess.Popen I can't figure out how to capture the following output: The authenticity of host '***...
Python subprocess + scp - can't read all output
I'm trying to SCP a file between machines and I need to fail when the user hasn't set up a private/public certificate to do passwordless logins. Unfortunatly, using subprocess.Popen I can't figure out how to capture the following output: The authenticity of host '***' can't be established. RSA key fingerprint is ***. A...
[ "I've run into something similar before, though in my case it was actually helpful. I believe ssh and friends don't actually read stdin and print on stdout or stderr, they do funky things to hook up with the terminal you're running in directly.\nI believe the reasoning is they they're supposed to be able to talk to...
[ 3, 3 ]
[]
[]
[ "linux", "python", "scp", "ssh" ]
stackoverflow_0006286147_linux_python_scp_ssh.txt
Q: Implement time-based quotas in python I need to implement a time-based quota in my python (twisted) application. Is there an existing module, or other implementation that I should use as a reference? Specifically, my application needs to ratelimit connections from clients, using rules like '10 connections per minu...
Implement time-based quotas in python
I need to implement a time-based quota in my python (twisted) application. Is there an existing module, or other implementation that I should use as a reference? Specifically, my application needs to ratelimit connections from clients, using rules like '10 connections per minute'. There is a Google App Engine module na...
[ "I'm not aware of any ready-made component, but it should be fairly simple to do this.\nI would probably use a database table, containing two columns: user ID and timestamp. Each time a user (IP address?) wants a connection, you find all the entries with that user ID with a timestamp between now and 60 seconds ago....
[ 1 ]
[]
[]
[ "python", "quota" ]
stackoverflow_0006286838_python_quota.txt
Q: Quick Python Syntax Error allData is a hash table. key values are product numbers. the value is a list of tuples. The first value in the tuple is either 0,1,2,3 and the second value of the tuple is a list of errors for that number. print len(allData[modelNumber][0][1]) #compiles fine File "burninprocessor.py", li...
Quick Python Syntax Error
allData is a hash table. key values are product numbers. the value is a list of tuples. The first value in the tuple is either 0,1,2,3 and the second value of the tuple is a list of errors for that number. print len(allData[modelNumber][0][1]) #compiles fine File "burninprocessor.py", line 467 bars = [len(allData[m...
[ "You have no closing parentheses on the second and third term in your 4-tuple. Try (split across lines for readability here but you probably want to keep it on one line in your code):\nbars = [len(allData[modelNumber][0][1]), len(allData[modelNumber][1][1]),\n len(allData[modelNumber][2][1]), len(allData[mod...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0006286946_python.txt
Q: Django: class views, generic views, etc I'm coming back to Django after a brief encounter with version 1.2, and now in version 1.3 the favored approach to views seems to be using classes. Keeping in mind code style, maintainability and modularity: when should I use classes, and when functions? Should I always exte...
Django: class views, generic views, etc
I'm coming back to Django after a brief encounter with version 1.2, and now in version 1.3 the favored approach to views seems to be using classes. Keeping in mind code style, maintainability and modularity: when should I use classes, and when functions? Should I always extend from generic class views (there seems to b...
[ "I find that class-based views help keep my code readable and streamlined.\nTake, for example, the sample (function-based) view from the form documentation:\ndef contact(request):\n if request.method == 'POST': # If the form has been submitted...\n form = ContactForm(request.POST) # A form bound to the PO...
[ 7, 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006286826_django_python.txt
Q: sqlalchemy pagination I'm building a REST app with flask and sqlalchemy and I came across an issue. I want to query all users with their number of books. Each user has many books so my query should return the number of books each user has in the resultset. // Models class User( object ): __tablename__ = '...
sqlalchemy pagination
I'm building a REST app with flask and sqlalchemy and I came across an issue. I want to query all users with their number of books. Each user has many books so my query should return the number of books each user has in the resultset. // Models class User( object ): __tablename__ = 'user' class Book( object )...
[ "This is actually an sql syntax error. having clause is used only when you have group by clause included as well, and only filtering the aggregate results. What you need is a simple where clause achieved with :\nrows = User.query.filter(User.booksCount > 4)\n\nas a side note: please do your code by the python stand...
[ 2, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006282534_python_sqlalchemy.txt
Q: Is there a better way to assign a default value for next() url_params = {} for i in t: try: url_params[i] = t.next() except: url_params[i] = None Because this just looks silly to me. I'm converting a list to a dict by pairing up neighboring elements. There are cases, however, where I won't...
Is there a better way to assign a default value for next()
url_params = {} for i in t: try: url_params[i] = t.next() except: url_params[i] = None Because this just looks silly to me. I'm converting a list to a dict by pairing up neighboring elements. There are cases, however, where I won't always have a pair. The tailing element is still important but ...
[ "This is more easily done like this:\nfrom itertools import izip_longest\nurl_params = dict(izip_longest(*[iter(t)] * 2))\n\nExample: For t = range(11), this produces\n{0: 1, 2: 3, 4: 5, 6: 7, 8: 9, 10: None}\n\n", "Also works:\n>>> dict(zip(t[::2], t[1::2]+[None]))\n{0: 1, 2: 3, 4: 5, 6: 7, 8: 9, 10: None}\n\n" ...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006286597_python.txt
Q: Is it possible to embed Python in PHP? I work for a small tech start-up, and our main site is built on the CMS Drupal, which is a PHP-based CMS. However, I know some Python and would like to develop web applications to integrate with the website and allow users to interact with them. How would I go about doing thi...
Is it possible to embed Python in PHP?
I work for a small tech start-up, and our main site is built on the CMS Drupal, which is a PHP-based CMS. However, I know some Python and would like to develop web applications to integrate with the website and allow users to interact with them. How would I go about doing this? Does anyone have any experience or knowle...
[ "If you are developing a web application nothing stops you from using Python and making it accessible from a subdomain or path not used by drupal, just have the web server point to it. Ex:\nhttp://mainsite.com/ <- drupal\nhttp://app.mainsite.com <- python web app\nhttp://mainsite.com/python/ <- python web app\n\nTh...
[ 4, 2 ]
[]
[]
[ "drupal", "php", "python" ]
stackoverflow_0006287134_drupal_php_python.txt
Q: Populating a Django DateTimeField with feedparser I'm attempting to read my school's athletics/activities calendar, available in iCal or RSS format, into a Django Events model using feedparser. Everything works, except the dates. Feedparser populates item.updated_parsed with a "9-tuple" but I can't figure out how ...
Populating a Django DateTimeField with feedparser
I'm attempting to read my school's athletics/activities calendar, available in iCal or RSS format, into a Django Events model using feedparser. Everything works, except the dates. Feedparser populates item.updated_parsed with a "9-tuple" but I can't figure out how to make this into something Django will accept in a Dat...
[ "Covert the time.struct_time object into a datetime.datetime object:\nfrom time import mktime\nfrom datetime import datetime\ndt = datetime.fromtimestamp(mktime(item['updated_parsed']))\n\n", "Well the Django DateTime field accepts python datetime.datetime objects so you have to convert from what Feedparser is pr...
[ 9, 2 ]
[]
[]
[ "date", "django", "feedparser", "python", "rss" ]
stackoverflow_0006287268_date_django_feedparser_python_rss.txt
Q: Calculating plugin dependencies I have the need to create a plugin system that will have dependency support and I'm not sure the best way to account for dependencies. The plugins will all be subclassed from a base class, each with its own execute() method. In each plugin class, I'd planned to create a dependenc...
Calculating plugin dependencies
I have the need to create a plugin system that will have dependency support and I'm not sure the best way to account for dependencies. The plugins will all be subclassed from a base class, each with its own execute() method. In each plugin class, I'd planned to create a dependencies attribute as a list of all the ot...
[ "The algorithm you described sounds like it would work but would have a hard time detecting circular dependencies.\nWhat you're looking for is a Topological sort of your dependencies. If you create a graph of your dependencies where an edge from A to B means A depends on B then you can do a Depth-first search to de...
[ 5, 2 ]
[]
[]
[ "algorithm", "logic", "python" ]
stackoverflow_0006287160_algorithm_logic_python.txt
Q: Python textbox program I want to write a Python program that will be able to read from a dictionary into any (or most) textboxes. Will this be possible and how would I approach it? Here is an example of what I mean with the first line being an example of a command I'd like to be able type to receive the 2nd line...
Python textbox program
I want to write a Python program that will be able to read from a dictionary into any (or most) textboxes. Will this be possible and how would I approach it? Here is an example of what I mean with the first line being an example of a command I'd like to be able type to receive the 2nd line which would be the message ...
[ "Store the dictionary as key,value pair in the form {key:value}. In the key part write your commands like 'hello' and in the value part give your corresponding message like ' HELLO! THIS IS AN AUTOMATED REPLY! :D'. You can access your value from its key. For eg:\n abc = {\"hello\" : \"HELLO! THIS IS AN AUTOMAT...
[ 0 ]
[]
[]
[ "alias", "python", "reply", "textbox" ]
stackoverflow_0006287379_alias_python_reply_textbox.txt
Q: Python date object for MongoDB I'm needing to prepare a date for insertion into MongoDB based on user input (string). Code: from datetime import datetime import time ... self.d_birthdate = time.strptime('6/8/1980', '%m/%d/%Y') self.d_created = dict.get('d_created', datetime.now()) ... The d_created attribute work...
Python date object for MongoDB
I'm needing to prepare a date for insertion into MongoDB based on user input (string). Code: from datetime import datetime import time ... self.d_birthdate = time.strptime('6/8/1980', '%m/%d/%Y') self.d_created = dict.get('d_created', datetime.now()) ... The d_created attribute works fine, but b_birthdate doesn't sinc...
[ "You can convert the time.time_struct object to a datetime.datetime object:\nfrom datetime import datetime\nfrom time import mktime\n\nbirthdate = time.strptime('6/8/1980', '%m/%d/%Y')\nself.d_birthdate = datetime.fromtimestamp(mktime(birthdate))\n\nIn newer versions of Python (I'm fairly sure you can't in 2.4) you...
[ 3 ]
[]
[]
[ "django", "mongodb", "python" ]
stackoverflow_0006287456_django_mongodb_python.txt
Q: Running a loop alongside a Tkinter application I am a high school programming student and I have a small question. I have been tasked with writing a simple game in Tkinter where an icicle falls from the ceiling and you have to avoid it with your mouse. Simple enough. However, I have hit an issue. Whenever I run a ...
Running a loop alongside a Tkinter application
I am a high school programming student and I have a small question. I have been tasked with writing a simple game in Tkinter where an icicle falls from the ceiling and you have to avoid it with your mouse. Simple enough. However, I have hit an issue. Whenever I run a loop in a Tkinter application, it won't open. I've t...
[ "Writing an event based program is not the same as writing traditional programs. There is already an infinite loop running, and like any infinite loop, if you place another loop inside, the outer loop can't continue until the inner loop finishes. Since the outer loop is what causes the screen to refresh and events ...
[ 6 ]
[]
[]
[ "loops", "python", "python_2.7", "tkinter" ]
stackoverflow_0006284532_loops_python_python_2.7_tkinter.txt
Q: python function of a default argument How can I access qux inside methods? Do I really have to define it again inside the body of foo(), or is there a way to import it from self? class Baz(object): qux = lambda x : x + '_quux' def foo(self, bar=qux('fred')): print bar print qux('waldo')...
python function of a default argument
How can I access qux inside methods? Do I really have to define it again inside the body of foo(), or is there a way to import it from self? class Baz(object): qux = lambda x : x + '_quux' def foo(self, bar=qux('fred')): print bar print qux('waldo') # NameError: global name 'qux' is ...
[ "If you want to be able to access a method off the class then you must use classmethod or staticmethod.\nclass Baz(object):\n qux = staticmethod(lambda x : x + '_quux')\n\nBut don't do that.\n", "One solution is to use\nqux = staticmethod(lambda x : x + '_quux')\n\nand accessing it as\nBaz.qux('waldo')\n\nI woul...
[ 7, 1, 1 ]
[]
[]
[ "arguments", "function", "lambda", "python" ]
stackoverflow_0006287459_arguments_function_lambda_python.txt
Q: Python Button Bind two functions and send arguments with the binding I am somewhat new to python still, and am working on a project including a GUI. I using with Tkinter and buttons a lot, and am curious if there was a way to run a function with a bind because I want one thing to happen when it is presses and some...
Python Button Bind two functions and send arguments with the binding
I am somewhat new to python still, and am working on a project including a GUI. I using with Tkinter and buttons a lot, and am curious if there was a way to run a function with a bind because I want one thing to happen when it is presses and something else when it is released. s = str(x+1) + ":" + str(y+1) ...
[ "The only way to use bind is to have it call a function. When you use lambda you are just creating an anonymous function. You can easily do:\nb.bind(\"<ButtonPress-1>\", self.SomeOtherFunction)\n\nlambda is useful when you want to pass additional arguments to the function. Unlike when using the command option, with...
[ 1 ]
[]
[]
[ "bind", "button", "events", "python", "tkinter" ]
stackoverflow_0006286412_bind_button_events_python_tkinter.txt
Q: How can I configure a Tkinter widget from a separate class? I am writing a Tkinter program that requires a loop. I can't run the loop from the same class that Tkinter is in, I'm fairly certain of that much. To run said loop, I believe that I have to use a separate thread, therefore a separate class, to keep Tkinte...
How can I configure a Tkinter widget from a separate class?
I am writing a Tkinter program that requires a loop. I can't run the loop from the same class that Tkinter is in, I'm fairly certain of that much. To run said loop, I believe that I have to use a separate thread, therefore a separate class, to keep Tkinter from freezing. I have gotten Tkinter to run while a loop in the...
[ "You don't necessarily need another thread, because you don't necessarily need to create a loop (see my answer to your other question about using a nested loop). \nHowever, to answer your specific question, you have to implement a queue. The worker thread will place messages of some sort on the queue, and the main ...
[ 0 ]
[]
[]
[ "class", "configure", "multithreading", "python", "tkinter" ]
stackoverflow_0006286942_class_configure_multithreading_python_tkinter.txt
Q: Is there something you can put in your code which starts an interactive interperter (in python) The idea is to be able to run the code normally, except it will start an interactive interpreter in the given scope when it gets to a particular method call. Sort of like stopping at a breakpoint to run code. Ideally, i...
Is there something you can put in your code which starts an interactive interperter (in python)
The idea is to be able to run the code normally, except it will start an interactive interpreter in the given scope when it gets to a particular method call. Sort of like stopping at a breakpoint to run code. Ideally, if you are already in an interpreter like ipython, it would return to that interpreter, except with ac...
[ "Check out the code module.\nHere's an example:\nimport code\na = 1\nb = 2\ncode.interact(local=locals())\n\nOutput:\nPython 2.7 (r27:82500, Nov 10 2010, 22:46:43) \n[GCC 4.2.1 (Apple Inc. build 5664)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n(InteractiveConsole)\n>...
[ 5, 2, 1 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0006287433_debugging_python.txt
Q: Get all commits when pushing to server I am making a git post-commit hook to post my commit messages to Twitter. I have set up the hook on the server, which means it only runs when I call git push. To interface with git from python, I am using GitPython. In my code, I am using repo.head.commit.message to get the...
Get all commits when pushing to server
I am making a git post-commit hook to post my commit messages to Twitter. I have set up the hook on the server, which means it only runs when I call git push. To interface with git from python, I am using GitPython. In my code, I am using repo.head.commit.message to get the latest commit message. Which means if I pu...
[ "The githooks docs say:\nThe hook executes once for each ref to be updated, and takes three parameters:\n - the name of the ref being updated,\n - the old object name stored in the ref,\n - and the new objectname to be stored in the ref.\n\nSo, check the arguments your script gets, you should also get the new re...
[ 3 ]
[]
[]
[ "git", "gitpython", "python" ]
stackoverflow_0006287631_git_gitpython_python.txt
Q: Slow webservice problem I create a Python webservice on Linux machine (ubuntu): import soaplib import os from soaplib.core.service import rpc, DefinitionBase, soap from soaplib.core.model.primitive import String, Integer from soaplib.core.server import wsgi from soaplib.core.model.clazz import Array def runcmd(c...
Slow webservice problem
I create a Python webservice on Linux machine (ubuntu): import soaplib import os from soaplib.core.service import rpc, DefinitionBase, soap from soaplib.core.model.primitive import String, Integer from soaplib.core.server import wsgi from soaplib.core.model.clazz import Array def runcmd(cmd): fout = os.popen(cmd)...
[ "I'd recommend using wireshark http://www.wireshark.org/ to 'listen' in on the conversation that is occurring over the network by recording ('capturing') copies of the network traffic that the device can see.\nWhen you start a capture, the amount of data can seem overwhelming, but if you can spot any fragments that...
[ 3, 1 ]
[]
[]
[ "linux", "python", "silverlight_4.0", "web_services", "windows" ]
stackoverflow_0006213224_linux_python_silverlight_4.0_web_services_windows.txt
Q: How to detect online users in a web application in Google App Engine I am currently working on an application for Google App Engine, and I need some advice to detect the number of online users in the application. How can I do this? I am using a session library. Do I need to overwrite the session methods (create_s...
How to detect online users in a web application in Google App Engine
I am currently working on an application for Google App Engine, and I need some advice to detect the number of online users in the application. How can I do this? I am using a session library. Do I need to overwrite the session methods (create_session, destroy_session increment/and decrement a value in datastore) or i...
[ "HTTP is stateless, so there's no inherent definition of \"online user\". You could count the number of non-destroyed sessions you've created, but unless you've got a cron job that destroys old sessions, this won't give an accurate picture.\nYou basically need to decide how much time without a new page request coun...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python", "session" ]
stackoverflow_0006262601_google_app_engine_python_session.txt
Q: Python programming .....Basics Thank you, I have some doubt in python programming like Difference in between module,library,package. What is difference in between built in and keyword. Eg: None,True is Builtins not keywords. What is the use of writing the code(to call main method) if __name__=__main__:main rath...
Python programming .....Basics
Thank you, I have some doubt in python programming like Difference in between module,library,package. What is difference in between built in and keyword. Eg: None,True is Builtins not keywords. What is the use of writing the code(to call main method) if __name__=__main__:main rather than simple call main() Can I ac...
[ "\nA module is a Python file. A package is a directory that has an __init__.py file. It behaves almost like it's a module, although it's a directory. A library is a reusable module or package.\nA keyword is a reserved word which you can't assign to. A builtin is a variable that is available \"by default\" so to spe...
[ 4 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006288352_python_python_3.x.txt
Q: How to generate an URL with Pyramid and Akhet? I'm creating an Akhet (Pyramid) web application. How can one generate in a mako template the URL for a given Handler/view ? I'm looking for the equivalent of Pylons' ${url(controller="users", view="list") A: You need to use route_url. It's available in the templat...
How to generate an URL with Pyramid and Akhet?
I'm creating an Akhet (Pyramid) web application. How can one generate in a mako template the URL for a given Handler/view ? I'm looking for the equivalent of Pylons' ${url(controller="users", view="list")
[ "You need to use route_url. It's available in the templates in request.route_url. \n<a href=\"${request.route_url('import')}\">Import</a>\n\nfor example\n", "Akhet exposes the URLGenerator object as a renderer global, so you can just use url('users', action='list'), assuming config.add_handler('users', '/users/{a...
[ 7, 2 ]
[]
[]
[ "akhet", "pylons", "pyramid", "python", "url" ]
stackoverflow_0006285071_akhet_pylons_pyramid_python_url.txt
Q: What does the symbol "#!" mean in Python? What does this line of code mean? Without it, my python3 http server can't understand and let the browser download an empty .py file (depend on the link to the .py file) #! /usr/local/bin/python3 A: It's not a Python thing, it a hashbang (or shebang) line which indicates...
What does the symbol "#!" mean in Python?
What does this line of code mean? Without it, my python3 http server can't understand and let the browser download an empty .py file (depend on the link to the .py file) #! /usr/local/bin/python3
[ "It's not a Python thing, it a hashbang (or shebang) line which indicates which interpreter should process the file.\nThe rules vary but, in its simplest form, a file with the name xyz (containing that as the first line), when run from the command line with xyz, will run it using that interpreter, similar to:\n/usr...
[ 18, 8, 7, 2, 2 ]
[]
[]
[ "python", "shebang" ]
stackoverflow_0006288855_python_shebang.txt
Q: Python: How to convert datetime format? Possible Duplicate: How to convert a time to a string I have a variable as shown in the below code. a = "2011-06-09" Using python, how to convert it to the following format? "Jun 09,2011" A: >>> import datetime >>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d'...
Python: How to convert datetime format?
Possible Duplicate: How to convert a time to a string I have a variable as shown in the below code. a = "2011-06-09" Using python, how to convert it to the following format? "Jun 09,2011"
[ ">>> import datetime\n>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')\n>>> d.strftime('%b %d,%Y')\n'Jun 09,2011'\n\nIn pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))\n", "@Tim's answer only d...
[ 71, 5 ]
[]
[]
[ "date", "python" ]
stackoverflow_0006288892_date_python.txt
Q: Syntax of Lists in Python I am learning python, now, i came across a code snippet which looks like this: my_name={'sujit','amit','ajit','arijit'} for i, names in enumerate(my_name): print "%s" %(names[i]) OUTPUT s m i t But when I modify the code as: my_name=['sujit','amit','ajit','arijit'] for i, names in e...
Syntax of Lists in Python
I am learning python, now, i came across a code snippet which looks like this: my_name={'sujit','amit','ajit','arijit'} for i, names in enumerate(my_name): print "%s" %(names[i]) OUTPUT s m i t But when I modify the code as: my_name=['sujit','amit','ajit','arijit'] for i, names in enumerate(my_name): print "%...
[ "{} creates a set, whereas [] creates a list. The key differences are:\n\nthe list preserves the order, whereas the set does not;\nthe list preserves duplicates, whereas the set does not;\nthe list can be accessed through indexing (i.e. l[5]), whereas the set can not.\n\nThe first point holds the key to your puzzle...
[ 4, 3, 0, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0006288935_python_syntax.txt
Q: FreqDist using NLTK I'm trying to get a frequency distribution of a set of documents using Python. My code isn't working for some reason and is producing this error: Traceback (most recent call last): File "C:\Documents and Settings\aschein\Desktop\freqdist", line 32, in <module> fd = FreqDist(corpus_text) ...
FreqDist using NLTK
I'm trying to get a frequency distribution of a set of documents using Python. My code isn't working for some reason and is producing this error: Traceback (most recent call last): File "C:\Documents and Settings\aschein\Desktop\freqdist", line 32, in <module> fd = FreqDist(corpus_text) File "C:\Python26\lib\s...
[ "Two thoughts that I hope at least contribute to an answer.\nFirst, the documentation for the nltk.text.Text() method states (emphasis mine):\n\nA wrapper around a sequence of simple (string) tokens, which is intended to support initial exploration of texts (via the interactive console). Its methods perform a varie...
[ 2, 1 ]
[]
[]
[ "frequency", "frequency_distribution", "nltk", "python" ]
stackoverflow_0006284855_frequency_frequency_distribution_nltk_python.txt
Q: Python short url generator I'm using this code to generate short url. http://code.activestate.com/recipes/576918/ The idea is to encode an integer id using base62 and function enbase just works fine. class UrlEncoder(object): ... def enbase(self, x, min_length=0): result = self._enbase(x) p...
Python short url generator
I'm using this code to generate short url. http://code.activestate.com/recipes/576918/ The idea is to encode an integer id using base62 and function enbase just works fine. class UrlEncoder(object): ... def enbase(self, x, min_length=0): result = self._enbase(x) padding = self.alphabet[0] * (min...
[ "Looking at the whole code: The net effect of encode() is to apply _encode() to the least-significant self.block_size-many bits of the value. _encode() appears to reverse those bits. It seems to be just a bit of additional scrambling. The documentation below the code explains why they are doing all these extra shuf...
[ 0 ]
[]
[]
[ "python", "short_url" ]
stackoverflow_0006288523_python_short_url.txt
Q: Numpy index out of range error I'm using this code : r = mlab.csv2rec(datafile, delimiter=';') fig = plt.figure() fig.subplots_adjust(bottom=0.2) ax = fig.add_subplot(111) ax.plot(r.date, r.close) but it's returning this : ax.plot(r.date, r.close) IndexError: index out of range for array How do I make sure tha...
Numpy index out of range error
I'm using this code : r = mlab.csv2rec(datafile, delimiter=';') fig = plt.figure() fig.subplots_adjust(bottom=0.2) ax = fig.add_subplot(111) ax.plot(r.date, r.close) but it's returning this : ax.plot(r.date, r.close) IndexError: index out of range for array How do I make sure that I`m staying inside the array range...
[ "Okay, I can plot the original dataset without errors -- but I think it's misinterpreting the date information as MM/DD/YYYY when it's really DD/MM/YYYY.\nHere's what I get for the original code:\n\nAnd here's what I get when I fix the date:\nimport datetime\nfixdate = lambda d: datetime.datetime.strptime(d, '%d/%m...
[ 4, 1 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0006288222_matplotlib_numpy_python.txt
Q: What is the Python counterpart to an Ada record / C++ struct type? Suppose I am recording data and want to associate some number of data elements, such that each recorded set always has a fixed composition, i.e. no missing fields. Most of my experience as a programmer is with Ada or C/C++ variants. In Ada, I wo...
What is the Python counterpart to an Ada record / C++ struct type?
Suppose I am recording data and want to associate some number of data elements, such that each recorded set always has a fixed composition, i.e. no missing fields. Most of my experience as a programmer is with Ada or C/C++ variants. In Ada, I would use a record type and aggregate assignment, so that when the record ...
[ "A namedtuple (from the collections library) may suit your purposes. It is basically a tuple which allows reference to fields by name as well as index position. So it's a fixed structure of ordered named fields. It's also lightweight in that it uses slots to define field names thus eliminating the need to carry a d...
[ 5, 3 ]
[]
[]
[ "ada", "c++", "python", "record" ]
stackoverflow_0006288285_ada_c++_python_record.txt
Q: Type annotations of objects to the correct class in Python/Eclipse I'm using Eclipse for developing some Python based application. Very often I pass some class object to methods. So how can I say to the eclipse that this particular variable is of type Class A. For ex. def foo(var1,var2): ''' var1 is of type C...
Type annotations of objects to the correct class in Python/Eclipse
I'm using Eclipse for developing some Python based application. Very often I pass some class object to methods. So how can I say to the eclipse that this particular variable is of type Class A. For ex. def foo(var1,var2): ''' var1 is of type Class A, and var2 is of type Class B''' var1.a = 10 var2.b = 'xyz...
[ "There exists no such thing as type casting in Python. There's type coercion that happens in arithmetic expressions, e.g., but that's something different. As I explained here, there's no sensible way for Eclipse to do what you want it do do. Since Python 3 there are type annotations in function definitions, as prop...
[ 1, 0 ]
[]
[]
[ "casting", "eclipse", "python", "types" ]
stackoverflow_0006288528_casting_eclipse_python_types.txt
Q: including script doesn't work in web.py everyone.I wanna include javascript in the html(webpy templates),but it doesn't work.the javascript code in the html works very well... following is the main python file(main.py): urls = ('/main','main') render = web.template.render('templates/') class main: def GET(self)...
including script doesn't work in web.py
everyone.I wanna include javascript in the html(webpy templates),but it doesn't work.the javascript code in the html works very well... following is the main python file(main.py): urls = ('/main','main') render = web.template.render('templates/') class main: def GET(self): return render.main() app = web.applica...
[ "You must put the include.js file in a \"static/js\" directory at the root of your project and src should be \"static/js/include.js\".\n" ]
[ 3 ]
[]
[]
[ "javascript", "python", "web.py" ]
stackoverflow_0006289446_javascript_python_web.py.txt
Q: Installed Tornado and Python but Apache is still handling .py files How do I get Tornado (or in general another server) to handle the .py files on my host, while Apache still handles the php files? A: I've always configured my python scripts inside apache with mod_wsgi. I believe there's no way to relegate to a ...
Installed Tornado and Python but Apache is still handling .py files
How do I get Tornado (or in general another server) to handle the .py files on my host, while Apache still handles the php files?
[ "I've always configured my python scripts inside apache with mod_wsgi. I believe there's no way to relegate to a different server the execution of some domain/filetype. Still, you can make a script to execute whenever an url is called. \nYou can do it in python an call it with mod_wsgi -> wsgi docs\n", "You can u...
[ 0, 0, 0 ]
[]
[]
[ "apache", "python", "tornado", "webserver" ]
stackoverflow_0006276805_apache_python_tornado_webserver.txt
Q: python mysql dictionary I have been using the dictcursor in MySQL with Python, the problem is how I can retrieve an specific record without having to iterate in all the dictionary, actually I am using this: data=cursor.fechall for item in data: if item["article"]==articledesc: do something ...
python mysql dictionary
I have been using the dictcursor in MySQL with Python, the problem is how I can retrieve an specific record without having to iterate in all the dictionary, actually I am using this: data=cursor.fechall for item in data: if item["article"]==articledesc: do something break is there a way to ac...
[ "If you only require a single article, then change your query to add a where clause:\nSELECT ...\nFROM ...\nWHERE article = %s\n\nFiltering a result set having retrieved more than you need is not a good idea from an efficiency point of view.\nIf you're retrieving a larger resultset and picking multiple articles out...
[ 2, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0006288866_mysql_python.txt
Q: storing python function in distributed computer finally I a little understand about tornadoweb asynchronous the key of asynchronous response is def new_messages(self, messages): cls = MessageMixin logging.info("Sending new message to %r listeners", len(cls.waiters)) for callback in cls.waiters: ...
storing python function in distributed computer
finally I a little understand about tornadoweb asynchronous the key of asynchronous response is def new_messages(self, messages): cls = MessageMixin logging.info("Sending new message to %r listeners", len(cls.waiters)) for callback in cls.waiters: try: callback(messages) except:...
[ "What?! You can only do callbacks with a message queue that has a data store. Look into something pika or Carrot. There's no way to \"store\" the callback but you can define a way to make other computers execute functions for you and have the results fed back to the original computer. \n" ]
[ 0 ]
[]
[]
[ "python", "tornado" ]
stackoverflow_0006255693_python_tornado.txt
Q: what is the best and general way to refer a function's __name__ in a function? Possible Duplicate: How do I get the name of a function or method from within a Python function or method? The below code function return it's name. It works but I still have to specify the 'test.' in front of of the __name__. Is ther...
what is the best and general way to refer a function's __name__ in a function?
Possible Duplicate: How do I get the name of a function or method from within a Python function or method? The below code function return it's name. It works but I still have to specify the 'test.' in front of of the __name__. Is there any general way to refer the __name__ ? def test(): print test.__name__
[ "If I understand correctly - Inspect is what you are looking for.\nimport inspect\ndef test():\n print inspect.stack()[0][3]\n\n", "There is no way to access the function name in a python function without using a backtrace.\nIn [1]: import inspect\n\nIn [2]: def test():\n ...: print inspect.stack()[0][3]...
[ 2, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006289699_python_python_3.x.txt
Q: best method and data structure for sorting a list of tuples into multiple lists? Let's say I have a list of tuples like this: l = [('music','300','url'),('movie','400','url'), ('clothing','250','url'),('music','350','url'), ('music','400','url'),('movie','1000','url')] and that I want to sort these tuples into mu...
best method and data structure for sorting a list of tuples into multiple lists?
Let's say I have a list of tuples like this: l = [('music','300','url'),('movie','400','url'), ('clothing','250','url'),('music','350','url'), ('music','400','url'),('movie','1000','url')] and that I want to sort these tuples into multiple lists, each grouped by the first element in the tuples. Further, once grouped ...
[ "Well, you can get your lists easily with a list comprehension:\nmusic = [x for x in l if x[0] == 'music']\nmovie = [x for x in l if x[0] == 'movie']\nclothing = [x for x in l if x[0] == 'clothing']\n\nYou can even sort them in place\n>>> music.sort(key=lambda x: x[1], reverse=True)\n<<< [('music', '400', 'url'), (...
[ 3, 2, 0 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0006289600_list_python_sorting.txt
Q: Why does "import module" and then "from package import module" load the module again? I have a package in my PYTHONPATH that looks something like this: package/ __init__.py module.py print 'Loading module' If I'm running Python from the package/ directory (or writing another module in this directo...
Why does "import module" and then "from package import module" load the module again?
I have a package in my PYTHONPATH that looks something like this: package/ __init__.py module.py print 'Loading module' If I'm running Python from the package/ directory (or writing another module in this directory) and type import module it loads module.py and prints out "Loading module" as expected....
[ "Effectively, by running code from the package directory, you've misconfigured Python. You shouldn't have put that directory on sys.path, since it's inside a package.\nPython doesn't use the filename as the key because it's not importing a file, it's importing a module. Allowing people to do 'import c:\\jim\\my f...
[ 2, 2 ]
[]
[]
[ "module", "package", "python", "python_import" ]
stackoverflow_0006282368_module_package_python_python_import.txt
Q: Python remove spaces and append I am currently writing a growl notification plugin for emesene messenger on OS X. It is nearly working except to when it comes to displaying a message snippet. The message is passed to growlnotify as a variable, however growl does not accept spaces in the displayed message. So what ...
Python remove spaces and append
I am currently writing a growl notification plugin for emesene messenger on OS X. It is nearly working except to when it comes to displaying a message snippet. The message is passed to growlnotify as a variable, however growl does not accept spaces in the displayed message. So what i need help with is a script to remov...
[ "Instead of trying to do this with os.system(), use subprocess instead, passing the program and arguments as a list.\n", "Just use the replace method of the string class:\nmessage_string = \"This is a message\"\nprint message_string.replace(\" \", \"\\ \")\n\nreturns:\n$ python test.py\nThis\\ is\\ a\\ message\n\...
[ 7, 5, 3, 2, 1 ]
[]
[]
[ "growlnotify", "python", "string", "text" ]
stackoverflow_0006289915_growlnotify_python_string_text.txt