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: Ideas on how to uniquely identify a computer? I have been thinking of ways I could uniquely identify a computer in python. First, I thought about checking the user's mac address and hard disk space, then I tried to compute some sort of rating from many of these variables. However, this solution doesn't feel right....
Ideas on how to uniquely identify a computer?
I have been thinking of ways I could uniquely identify a computer in python. First, I thought about checking the user's mac address and hard disk space, then I tried to compute some sort of rating from many of these variables. However, this solution doesn't feel right. It takes a long time to run and I had to change it...
[ "First you need to define \"computer.\" Is a computer the same computer if you change the case? The hard drive? The network card? Increase the RAM? Upgrade the kernel?\n(It brings to mind the saying about \"my grandfather's hammer\" — sure, I've replaced the head five times and the handle twice, but it's still the ...
[ 9 ]
[]
[]
[ "hash", "python", "uniqueidentifier" ]
stackoverflow_0003873105_hash_python_uniqueidentifier.txt
Q: Keeping imported modules out of python package namespaces I've noticed sometimes if you call dir() on a package/module, you'll see other modules in the namespace that were imported as part of the implementation and aren't meant for you to use. For instance, if I install the fish package from PyPI and import it, I ...
Keeping imported modules out of python package namespaces
I've noticed sometimes if you call dir() on a package/module, you'll see other modules in the namespace that were imported as part of the implementation and aren't meant for you to use. For instance, if I install the fish package from PyPI and import it, I see fish.sys, which just refers to the built-in sys module. My ...
[ "\nMy question is whether that's sane\n\nIt's sane. Doing import fish adds just one name to your namespace, that is not \"namespace clutter\". It's pretty much the big idea behind modules, grouping many things under one name!\nWhen you want to know what a module does, look at the documentation or call help, don't d...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003873115_python.txt
Q: Send an E-mail to an internationalized E-mail address with Python / SMTPlib In my Python application, I would like to be able to send mail to addresses like っていった@example.jp, démo@example.fr, or even عرض@وزارة-الأتصالات.مصر, which are perfectly valid. When passing the address as UTF-8, I get an UnicodeDecodeExcept...
Send an E-mail to an internationalized E-mail address with Python / SMTPlib
In my Python application, I would like to be able to send mail to addresses like っていった@example.jp, démo@example.fr, or even عرض@وزارة-الأتصالات.مصر, which are perfectly valid. When passing the address as UTF-8, I get an UnicodeDecodeException. If I encode the address with address.encode('utf-8'), no Python error but I ...
[ "Make sure the server you're talking to includes UTF8SMTP in its EHLO response. Otherwise it doesn't support rfc5336. You can tell by using telnet or netcat to connect to the server and pretending to be an SMTP client.\n" ]
[ 2 ]
[]
[]
[ "python", "smtp" ]
stackoverflow_0003873582_python_smtp.txt
Q: Pixel by pixel operation on image in Google App Engine using Python I would like to go over an image and do some pixel by pixel operation. The image API provided by Google App Engine seems to be incapable to do this. And it doesn't include Python Imaging Library. So, how should I proceed with it. Thanks.. A: You...
Pixel by pixel operation on image in Google App Engine using Python
I would like to go over an image and do some pixel by pixel operation. The image API provided by Google App Engine seems to be incapable to do this. And it doesn't include Python Imaging Library. So, how should I proceed with it. Thanks..
[ "You could maybe use the image API to convert to PNG, then use the png module (which is pure python, so should hopefully run on app engine) to load the PNG and modify the pixels. Then convert back to PNG using the png module, and back to whatever format you need using the image API.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python", "python_imaging_library" ]
stackoverflow_0003872694_google_app_engine_python_python_imaging_library.txt
Q: Numpy - why value error for NaN when trying to delete rows I have a numpy array: A = array([['id1', '1', '2', 'NaN'], ['id2', '2', '0', 'NaN']]) I also have a list: li = ['id1', 'id3', 'id6'] I wish to iterate over the array and the list and where the first element in each row of the array is not in t...
Numpy - why value error for NaN when trying to delete rows
I have a numpy array: A = array([['id1', '1', '2', 'NaN'], ['id2', '2', '0', 'NaN']]) I also have a list: li = ['id1', 'id3', 'id6'] I wish to iterate over the array and the list and where the first element in each row of the array is not in the list, then delete that entire row from the array. My code to ...
[ "Just generating a new array is no option?\nnumpy.array([x for x in A if x[0] in li])\n\n", "It appears you want to delete a row of your array in-place, however, this is not possible using the np.delete function, as such an operation goes against the way that Python and Numpy manage memory.\nI found an interestin...
[ 5, 2 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0003873314_arrays_numpy_python.txt
Q: Why do C programs require decompilers but python programs dont? If I write a python script, anyone can simply point an editor to it and read it. But for programming written in C, one would have to use decompilers and hex tables and such. Why is that? I mean I simply can't open up the Safari web browser and look at...
Why do C programs require decompilers but python programs dont?
If I write a python script, anyone can simply point an editor to it and read it. But for programming written in C, one would have to use decompilers and hex tables and such. Why is that? I mean I simply can't open up the Safari web browser and look at its code.
[ "Note: The author disavows a deep expertise in this subject. Some assertions may be incorrect.\nPython actually is compiled into bytecode, which is what gets run by the python interpreter. Whenever you use a Python module, Python will generate a .pyc file with a name corresponding to the module. This is the equiv...
[ 12, 10, 5, 3, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "c", "decompiling", "python" ]
stackoverflow_0003869435_c_decompiling_python.txt
Q: Can I change an an existing virtualenv to ignore global site packages? (like --no-site-package on a new one) I can create a new virtualenv that ignores global site-packages with "--no-site-package". Is it possible to change an existing virtualenv (which was created without "--no-site-package") to also ignore the g...
Can I change an an existing virtualenv to ignore global site packages? (like --no-site-package on a new one)
I can create a new virtualenv that ignores global site-packages with "--no-site-package". Is it possible to change an existing virtualenv (which was created without "--no-site-package") to also ignore the global site-packages? (So that it workes like it was created with "--no-site-package" in the first place.) thanks i...
[ "I think all you have to do is create an empty file called no-global-site-packages.txt and put it into the virtualenv's python2.x folder (eg, lib/python2.6/, the one with all the modules). Then the normal site.py generated by virtualenv detects the difference and handles everything from there.\n", "Can you just c...
[ 20, 9 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0003873294_python_virtualenv.txt
Q: Javascript Execution Through Python I am attempting to create an html document parser with Python. I am very familiar with jQuery and I would like to use its traversing functionality to parse these html files and return the data gathered with jQuery back to my Python program. Is there any way to use javascript scr...
Javascript Execution Through Python
I am attempting to create an html document parser with Python. I am very familiar with jQuery and I would like to use its traversing functionality to parse these html files and return the data gathered with jQuery back to my Python program. Is there any way to use javascript scripts through Python? Or is this just a pi...
[ "You might not need to do this. There is a Python module called PyQuery that directly emulates the API for jQuery. It works exactly as you would expect it to in almost every way. Give it a shot!\n", "jQuery itself does not contain an HTML/XML parser at all. It uses the browser to do all its parsing. Thus, even i...
[ 6, 1, 1, 0 ]
[]
[]
[ "html", "javascript", "jquery", "parsing", "python" ]
stackoverflow_0003874280_html_javascript_jquery_parsing_python.txt
Q: Getting html stripped of script and style tags with BeautifulSoup? I have a simple script where I am fetching an HTML page, passing it to BeautifulSoup to remove all script and style tags, then I want to pass the HTML result to another method. Is there an easy way to do this? Skimming the BeautifulSoup.py, I haven...
Getting html stripped of script and style tags with BeautifulSoup?
I have a simple script where I am fetching an HTML page, passing it to BeautifulSoup to remove all script and style tags, then I want to pass the HTML result to another method. Is there an easy way to do this? Skimming the BeautifulSoup.py, I haven't seen it yet. soup = BeautifulSoup(html) for script in soup("script"):...
[ "unicode( soup ) gives you the html.\nAlso what you want is this:\nfor elem in soup.findAll(['script', 'style']):\n elem.extract()\n\n" ]
[ 9 ]
[]
[]
[ "beautifulsoup", "html_parsing", "python", "python_2.6" ]
stackoverflow_0003874442_beautifulsoup_html_parsing_python_python_2.6.txt
Q: How to use python for a webservice I am really new to python, just played around with the scrapy framework that is used to crawl websites and extract data. My question is, how to I pass parameters to a python script that is hosted somewhere online. E.g. I make following request mysite.net/rest/index.py Now I want ...
How to use python for a webservice
I am really new to python, just played around with the scrapy framework that is used to crawl websites and extract data. My question is, how to I pass parameters to a python script that is hosted somewhere online. E.g. I make following request mysite.net/rest/index.py Now I want to pass some parameters similar to php l...
[ "Yes that would work. Although you would need to write handlers for extracting the url parameters in index.py. Try import cgi module for this in python.\nPlease note that there are several robust python based web frameworks available (aka Django, Pylons etc.) which automatically parses your url & forms a dictionary...
[ 2 ]
[]
[]
[ "parameters", "python", "scrapy", "web_services" ]
stackoverflow_0003874477_parameters_python_scrapy_web_services.txt
Q: Is there a way to make every variable inside a definition or class to become global automatically? I am using a large list of variables inside some definitions and classes (mainly because I want to be able to use the code-folding feature of pydev). Is there any constructor I can use on a definition or class to mak...
Is there a way to make every variable inside a definition or class to become global automatically?
I am using a large list of variables inside some definitions and classes (mainly because I want to be able to use the code-folding feature of pydev). Is there any constructor I can use on a definition or class to make its variables automatically considered globals? This is an example of what I did after following some...
[ "Although you should not do this and the solution you are looking for is not as simple as you might think, here is a very simple example of how you might take the local variables from within a function and make them global:\ndef make_locals_globals():\n \"\"\"This is just bad\"\"\"\n foo = 1\n bar = 2\n\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003874613_python.txt
Q: Python - correct order of the application of decorators I'm decorating a function as such: def some_abstract_decorator(func): @another_lower_level_decorator def wrapper(*args, **kwargs): # ... details omitted return func(*args, **kwargs) return wrapper This does what you'd expect (appl...
Python - correct order of the application of decorators
I'm decorating a function as such: def some_abstract_decorator(func): @another_lower_level_decorator def wrapper(*args, **kwargs): # ... details omitted return func(*args, **kwargs) return wrapper This does what you'd expect (applies a low level decorator and then does some more stuff. My p...
[ "That's right. The way this works is\n\nwrapper is defined. It calls func with its arguments.\nanother_lower_level_decorator is called, with wrapper as its argument. The function it returns becomes the new value of wrapper.\nwraps(func) is called to create a wrapper that will apply the name/docstring/etc. of fun...
[ 2, 2, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0003874962_decorator_python.txt
Q: django gui for statistical analysis of data Im trying to setup situation where users of application can do statistical analysis of data. There are 3 tables, users, exams, polls I should have gui to build custom queries, like these: users born between 1930 and 1940, that have 3 exams taken; show name, surname, gr...
django gui for statistical analysis of data
Im trying to setup situation where users of application can do statistical analysis of data. There are 3 tables, users, exams, polls I should have gui to build custom queries, like these: users born between 1930 and 1940, that have 3 exams taken; show name, surname, group by age of person count of users born 1945 tha...
[ "I have developed django-cube for this very purpose.\nIt allows you to organize your django data as multi-dimensional data, declare an aggregation function (to calculate your statistics), and then you have several helpers to display a table, and ready-to-use Django templates for tables.\n", "I've had some pretty ...
[ 2, 1 ]
[]
[]
[ "django", "django_statistics", "python", "search" ]
stackoverflow_0003873671_django_django_statistics_python_search.txt
Q: Wake up from standby/hibernate programmatically in Windows in python? I'm thinking of making an alarm clock that can wake up some systems (depending on motherboard model) from hibernation/standby modes at a certain pre-determined time. I've seen similar software do this, I think in VB. I can't seem to find any doc...
Wake up from standby/hibernate programmatically in Windows in python?
I'm thinking of making an alarm clock that can wake up some systems (depending on motherboard model) from hibernation/standby modes at a certain pre-determined time. I've seen similar software do this, I think in VB. I can't seem to find any documentation anywhere on how to do this in Python. Does anyone have any hints...
[ "SetWaitableTimer can wake up a suspended machine.\n" ]
[ 2 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003875209_python_windows.txt
Q: Data type problem using scipy.spatial I want to use scipy.spatial's KDTree to find nearest neighbor pairs in a two dimensional array (essentially a list of lists where the dimension of the nested list is 2). I generate my list of lists, pipe it into numpy's array and then create the KDTree instance. However, whene...
Data type problem using scipy.spatial
I want to use scipy.spatial's KDTree to find nearest neighbor pairs in a two dimensional array (essentially a list of lists where the dimension of the nested list is 2). I generate my list of lists, pipe it into numpy's array and then create the KDTree instance. However, whenever I try to run "query" on it, I inevitabl...
[ "I have used scipy.spatial before, and it appears to be a nice improvement (especially wrt the interface) as compared to scikits.ann.\nIn this case I think you have confused the return from your tree.query(...) call. From the scipy.spatial.KDTree.query docs:\nReturns\n-------\n\nd : array of floats\n The distan...
[ 9 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0003875062_numpy_python_scipy.txt
Q: sqlite3 module for Jython I'm using Java Scripting API to execute some external Python scripts from my Java application. The python scripts use sqlite3 module. Execution of the application is resulting in error ImportError: No module named sqlite3 As I look into the Lib directory(which is in the classpath) of Jyt...
sqlite3 module for Jython
I'm using Java Scripting API to execute some external Python scripts from my Java application. The python scripts use sqlite3 module. Execution of the application is resulting in error ImportError: No module named sqlite3 As I look into the Lib directory(which is in the classpath) of Jython, there's no sqlite3 module....
[ "I don't believe there is any way to use a CPython extension in Jython, so you're out of luck there.\nThere's a Java wrapper for SQLite here: http://www.zentus.com/sqlitejdbc/\nThis is not going to work quite like a Python database driver, so using it would require some adaptation. \nNot fun, but perhaps you (or so...
[ 4 ]
[]
[]
[ "java", "javax.script", "jython", "python", "sqlite" ]
stackoverflow_0003875212_java_javax.script_jython_python_sqlite.txt
Q: Is there a library or reference around showing how to build a Ribbon menu using PyGTK? Hey there, everyone. A really random question, but I'm looking to get into some GUI programming with Python, specifically with the PyGTK library. I've only ever done GUI programming with Java/Swing, and I'd like to do some indep...
Is there a library or reference around showing how to build a Ribbon menu using PyGTK?
Hey there, everyone. A really random question, but I'm looking to get into some GUI programming with Python, specifically with the PyGTK library. I've only ever done GUI programming with Java/Swing, and I'd like to do some independent, personal projects in Python as a way of learning my way around the language, since i...
[ "There is ribbon like widgets developed as a part of GSC.\n\nhttp://arstechnica.com/open-source/news/2007/08/mono-developer-brings-the-ribbon-interface-to-linux.ars\nhttp://mono-soc-2007.googlecode.com/svn/trunk/laurent/src/Ribbons/\nhttp://debackerl.wordpress.com/2007/08/25/soc-ribbons-summary/\n\n" ]
[ 1 ]
[]
[]
[ "pygtk", "python", "ribbon", "user_interface" ]
stackoverflow_0003875723_pygtk_python_ribbon_user_interface.txt
Q: Proper way to do session handling in Python + Pylons for a php programmer I'm a php programmer who's just getting started with Python. I'm trying to get Python to handle login/logout via database-stored sessions. Things work, but seem inconsistent. For example, sometimes a user isn't logged out. Sometimes user...
Proper way to do session handling in Python + Pylons for a php programmer
I'm a php programmer who's just getting started with Python. I'm trying to get Python to handle login/logout via database-stored sessions. Things work, but seem inconsistent. For example, sometimes a user isn't logged out. Sometimes users "switch" logins. I'm guessing this has something to do with thread-safety, b...
[ "Pylons has a 'sessions' object that exists to handle this kind of situation. The example on the Pylons website seems to match what you want.\nI think you are seeing problems because of the globals 'user' and 'connection'. Pylons has a globals object that is designed to share information between all controllers and...
[ 3 ]
[]
[]
[ "pylons", "python", "session" ]
stackoverflow_0003873958_pylons_python_session.txt
Q: How does one convert a .NET tick to a python datetime? I have a file with dates and times listed as huge numbers like 634213557000000000. I believe this is a .NET tick. That's the number of 100 nanosecond increments since midnight on January 1, 1 A.D. What's a good way to read that into a python datetime object? ...
How does one convert a .NET tick to a python datetime?
I have a file with dates and times listed as huge numbers like 634213557000000000. I believe this is a .NET tick. That's the number of 100 nanosecond increments since midnight on January 1, 1 A.D. What's a good way to read that into a python datetime object?
[ "datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds = ticks//10)\n\nFor your example, this returns\ndatetime.datetime(2010, 9, 29, 11, 15)\n\n" ]
[ 16 ]
[]
[]
[ ".net", "datetime", "python", "timestamp" ]
stackoverflow_0003875806_.net_datetime_python_timestamp.txt
Q: How to script Firefox or any Mozilla based browser I need to automate something like this: Open an URL Wait until the page is fully loaded Save COMPLETE page as... (I can provide a name). I saw https://developer.mozilla.org/en/Command_Line_Options but I can't find an option to invoke the command "save page as......
How to script Firefox or any Mozilla based browser
I need to automate something like this: Open an URL Wait until the page is fully loaded Save COMPLETE page as... (I can provide a name). I saw https://developer.mozilla.org/en/Command_Line_Options but I can't find an option to invoke the command "save page as... (in mode Web page complete)". So I can have all css, js...
[ "Maybe something from the Selenium collection of tools works for you.\n\nSelenium IDE is an integrated development environment for Selenium scripts. It is implemented as a Firefox extension, and allows you to record, edit, and debug tests. Selenium IDE includes the entire Selenium Core, allowing you to easily and q...
[ 4 ]
[]
[]
[ "firefox", "python", "scripting" ]
stackoverflow_0003876070_firefox_python_scripting.txt
Q: What's the simplest way to resize an image to a given bounded area? I'd like to create a function, like: def generateThumbnail(self, width, height): """ Generates thumbnails for an image """ im = Image.open(self._file) im.thumbnail((width, height), Image.ANTIALIAS) im.save(self._path ...
What's the simplest way to resize an image to a given bounded area?
I'd like to create a function, like: def generateThumbnail(self, width, height): """ Generates thumbnails for an image """ im = Image.open(self._file) im.thumbnail((width, height), Image.ANTIALIAS) im.save(self._path + str(width) + 'x' + str(height) + '-' + self._filename, "J...
[ "You need to crop the image properly before resizing it. The basic idea is to determine the largest rectangular area of the source image having the same aspect (width to height) ratio as the thumbnail image and then trim off (crop) any excess around it before resizing to the thumbnail's dimensions). Here's a functi...
[ 6 ]
[]
[]
[ "image_resizing", "imaging", "python", "python_imaging_library" ]
stackoverflow_0003873859_image_resizing_imaging_python_python_imaging_library.txt
Q: Python: how to tell if a string represent a statement or an expression? I need to either call exec() or eval() based on an input string "s" If "s" was an expression, after calling eval() I want to print the result if the result was not None If "s" was a statement then simply exec(). If the statement happens to pri...
Python: how to tell if a string represent a statement or an expression?
I need to either call exec() or eval() based on an input string "s" If "s" was an expression, after calling eval() I want to print the result if the result was not None If "s" was a statement then simply exec(). If the statement happens to print something then so be it. s = "1 == 2" # user input # --- try: v = eva...
[ "Try to compile it as an expression. If it fails then it must be a statement (or just invalid).\nisstatement= False\ntry:\n code= compile(s, '<stdin>', 'eval')\nexcept SyntaxError:\n isstatement= True\n code= compile(s, '<stdin>', 'exec')\n\nresult= None\nif isstatement:\n exec s\nelse:\n result= eva...
[ 10, 6 ]
[]
[]
[ "detect", "expression", "python" ]
stackoverflow_0003876231_detect_expression_python.txt
Q: Lamson (Python SMTP Server) Error I've installed Lamson via easy_install on my webfaction shared hosting. Went to do the '30 Second Introduction' (See http://lamsonproject.org/docs/getting_started.html) but after: [almacmillan@web129 python2.6]$ lamson gen -project mymailserver I get: Traceback (most recent c...
Lamson (Python SMTP Server) Error
I've installed Lamson via easy_install on my webfaction shared hosting. Went to do the '30 Second Introduction' (See http://lamsonproject.org/docs/getting_started.html) but after: [almacmillan@web129 python2.6]$ lamson gen -project mymailserver I get: Traceback (most recent call last): File "/home/almacmillan/bi...
[ "There's already a ticket for the problem here: http://support.lamsonproject.org/tktview?name=06d488141d\nUse http://pypi.python.org/pypi/lockfile/0.8 as 0.9.1's\nAPI changes break python_daemon-1.5.5-py2.5.egg/daemon/pidlockfile.py.\n0.9.1 comes with easy_install. So, it's not an issue with lamson.\nTo solve: remo...
[ 3 ]
[]
[]
[ "email", "lamson", "python", "smtp" ]
stackoverflow_0003874771_email_lamson_python_smtp.txt
Q: Validating XML with DTD fails to import entity using lxml I have a tool producing NewsML type XML files and I want to validate them after producing the files. I'm receiving an error: Attempt to load network entity http://www.w3.org/TR/ruby/xhtml-ruby-1.mod The python call is: parser = etree.XMLParser(load_dtd=True...
Validating XML with DTD fails to import entity using lxml
I have a tool producing NewsML type XML files and I want to validate them after producing the files. I'm receiving an error: Attempt to load network entity http://www.w3.org/TR/ruby/xhtml-ruby-1.mod The python call is: parser = etree.XMLParser(load_dtd=True, dtd_validation=True) treeObject = etree.parse(f, parser) Fir...
[ "Try constructing the parser with no_network=False. As stated in the documentation:\n\nno_network - prevent network access when looking up external documents (on by default)\n\nImported dtd modules should get retrieved by lxml, but it will not be able to do so if network access is not allowed (this does not count f...
[ 4 ]
[]
[]
[ "dtd", "lxml", "python", "xml" ]
stackoverflow_0003874742_dtd_lxml_python_xml.txt
Q: Using pyinotify to watch for file creation, but waiting for it to be completely written to disk I'm using pyinotify to watch a folder for when files are created in it. And when certain files are created I want to move them. The problem is that as soon as the file is created (obviously), my program tries to move it...
Using pyinotify to watch for file creation, but waiting for it to be completely written to disk
I'm using pyinotify to watch a folder for when files are created in it. And when certain files are created I want to move them. The problem is that as soon as the file is created (obviously), my program tries to move it, even before it's completely written to disk. Is there a way to make pyinotify wait until a file is ...
[ "Have pyinotify react to IN_CLOSE_WRITE events:\nwm.add_watch(watched_dir, pyinotify.IN_CLOSE_WRITE, proc_fun=MyProcessEvent())\n\nThis is from man 5 incrontab, but it applies equally well to pyinotify:\n IN_ACCESS File was accessed (read) (*)\n IN_ATTRIB Metadata changed (permissions, times...
[ 15, 1, 1 ]
[]
[]
[ "file", "linux", "pyinotify", "python" ]
stackoverflow_0003876348_file_linux_pyinotify_python.txt
Q: timeout a subprocess I realize this might be a duplicate of Using module 'subprocess' with timeout. If it is, I apologize, just wanted to clarify something. I'm creating a subprocess, which I want to run for a certain amount of time, and if it doesn't complete within that time, I want it to throw an error. Would s...
timeout a subprocess
I realize this might be a duplicate of Using module 'subprocess' with timeout. If it is, I apologize, just wanted to clarify something. I'm creating a subprocess, which I want to run for a certain amount of time, and if it doesn't complete within that time, I want it to throw an error. Would something along the lines o...
[ "It would, but it has a problem. The process will continue on doing whatever it is you asked it to do even after you've given up on it. You'll have to send the process a signal to kill it once you've given up on it if you really want it to stop.\nSince you are spawning a new process (./configure which is presumab...
[ 6 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003876886_python_subprocess.txt
Q: Metaclass to parametrize Inheritance I've read some tutorials on Python metaclasses. I've never used one before, but I need one for something relatively simple and all the tutorials seem geared towards much more complex use cases. I basically want to create a template class that has some pre-specified body, but ...
Metaclass to parametrize Inheritance
I've read some tutorials on Python metaclasses. I've never used one before, but I need one for something relatively simple and all the tutorials seem geared towards much more complex use cases. I basically want to create a template class that has some pre-specified body, but takes its base class as a parameter. Sinc...
[ "Although it certainly can be done with metaclasses, you can do what you want without them because in Python classes are themselves objects. The means that—surprisingly—essentially nothing more than an almost one-to-one translation of the C++ code is required. Besides being relatively uncomplicated because of this,...
[ 10, 0 ]
[]
[]
[ "c++", "metaclass", "metaprogramming", "python", "templates" ]
stackoverflow_0003876921_c++_metaclass_metaprogramming_python_templates.txt
Q: Why does id({}) == id({}) and id([]) == id([]) in CPython? Why does CPython (no clue about other Python implementations) have the following behavior? tuple1 = () tuple2 = () dict1 = {} dict2 = {} list1 = [] list2 = [...
Why does id({}) == id({}) and id([]) == id([]) in CPython?
Why does CPython (no clue about other Python implementations) have the following behavior? tuple1 = () tuple2 = () dict1 = {} dict2 = {} list1 = [] list2 = [] # makes sense, tuples are immutable assert(id(tuple1) == id(tu...
[ "When you call id({}), Python creates a dict and passes it to the id function. The id function takes its id (its memory location), and throws away the dict. The dict is destroyed. When you do it twice in quick succession (without any other dicts being created in the mean time), the dict Python creates the second ti...
[ 45, 42 ]
[ "The == operator on lists and dicts do not compare the object IDs to see if they the same object - use obj1 is obj2 for that.\nInstead the == operator compares the members of the list of dict to see if they are the same. \n" ]
[ -6 ]
[ "cpython", "identity", "python", "python_internals" ]
stackoverflow_0003877230_cpython_identity_python_python_internals.txt
Q: Python - question about decimal arithmetic I have 3 questions pertaining to decimal arithmetic in Python, all 3 of which are best asked inline: 1) >>> from decimal import getcontext, Decimal >>> getcontext().prec = 6 >>> Decimal('50.567898491579878') * 1 Decimal('50.5679') >>> # How is this a precision of 6? If th...
Python - question about decimal arithmetic
I have 3 questions pertaining to decimal arithmetic in Python, all 3 of which are best asked inline: 1) >>> from decimal import getcontext, Decimal >>> getcontext().prec = 6 >>> Decimal('50.567898491579878') * 1 Decimal('50.5679') >>> # How is this a precision of 6? If the decimal counts whole numbers as >>> # part of ...
[ "\nPrecision follows sig figs, not fractional digits. The former is more useful in scientific applications.\nRaw data should never be mangled. Instead it does the mangling when operated upon.\nThis is how it's done.\n\n" ]
[ 8 ]
[]
[]
[ "decimal", "math", "python" ]
stackoverflow_0003877299_decimal_math_python.txt
Q: How to parallelize this situation with robots I'm working on a robotic problem. The situation is something like this: There are N number of robots (generally N>100) initially all at rest. Each robot attracts all other robots which are with in its radius r. I've set of equations with which I can compute accelerati...
How to parallelize this situation with robots
I'm working on a robotic problem. The situation is something like this: There are N number of robots (generally N>100) initially all at rest. Each robot attracts all other robots which are with in its radius r. I've set of equations with which I can compute acceleration, velocity & hence the position of the robot afte...
[ "Note: Python's threads still run on the same processor. If you want to use the full range of processors of your machine you should use multiprocessing (python2.6+).\nUsing MPI will only bring you clear benefits if the computation is going to be spread over multiple computers.\nThere are two approaches to your prob...
[ 2, 1, 0 ]
[]
[]
[ "mpi", "parallel_processing", "python" ]
stackoverflow_0003875036_mpi_parallel_processing_python.txt
Q: Named replaces in strings with Mako When creating a template in Mako, I would need to write things like : ${_('Hello, %(fname)s %(lname)s') % {'fname':'John','lname':'Doe'}} I keep getting SyntaxException: (SyntaxError) unexpected EOF while parsing when writing that. Is there wny way to do the same ? ${_('Hello, %...
Named replaces in strings with Mako
When creating a template in Mako, I would need to write things like : ${_('Hello, %(fname)s %(lname)s') % {'fname':'John','lname':'Doe'}} I keep getting SyntaxException: (SyntaxError) unexpected EOF while parsing when writing that. Is there wny way to do the same ? ${_('Hello, %s %s') % ('John', 'Doe')} works, but it d...
[ "Using {} inside Mako's ${} is complicated; apparently Mako stops parsing the expression after finding the first }. A possible workaround is to use dict() instead of {}:\n${_('Hello, %(fname)s %(lname)s') % dict(fname='John', lname='Doe')}\n\n", "Try the new Python string formatting:\n>>> \"{foo} {bar}\".format(...
[ 2, 0 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0003875520_mako_python.txt
Q: I embedded a matplotlib graph of a sphere into Tkinter, and can no longer orbit it! I embedded a matplotlib graph of a sphere into Tkinter. Now for some reason I've lost the ability to orbit the object, when dragging the mouse. Anyone have an idea of why this happened and how to fix this? #!/usr/bin/env python i...
I embedded a matplotlib graph of a sphere into Tkinter, and can no longer orbit it!
I embedded a matplotlib graph of a sphere into Tkinter. Now for some reason I've lost the ability to orbit the object, when dragging the mouse. Anyone have an idea of why this happened and how to fix this? #!/usr/bin/env python import matplotlib matplotlib.use('TkAgg') from mpl_toolkits.mplot3d import axes3d,Axes3...
[ "You need to setup your canvas before you plot, so move the block of code below to after this line self.canvas._tkcanvas.pack(side='top', fill='both', expand=1)\n #Move this Code \n ax = Axes3D(self.fig)\n u = np.linspace(0, 2 * np.pi, 100)\n v = np.linspace(0, np.pi, 100)\n x = 1...
[ 4 ]
[]
[]
[ "matplotlib", "python", "tkinter" ]
stackoverflow_0003877411_matplotlib_python_tkinter.txt
Q: Regex find numbers in specific position hi i have a string like this track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false; i want to use some regular expression so i would end up with groups pid = 1234 p1 = 21 p2 = 4343 A: import re s = "track._Event('product', 'test');Product.lisen(1234...
Regex find numbers in specific position
hi i have a string like this track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false; i want to use some regular expression so i would end up with groups pid = 1234 p1 = 21 p2 = 4343
[ "import re\n\ns = \"track._Event('product', 'test');Product.lisen(1234, 21, 4343); return false;\"\n\npattern = re.compile(r'.*lisen\\((?P<pid>\\d+),\\s*(?P<p1>\\d+),\\s*(?P<p2>\\d+)\\).*')\n\npid, p1, p2 = map(int, pattern.match(s).groups())\n\nNote: I used named capturing groups, but that is not necessary in thi...
[ 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003875475_python_regex.txt
Q: Google App Engine (Python)- Strange behaviour of REMOTE_ADDR In order to make the registration process on my website easy, I allow users to enter their email address which I will send a verification code to or alternatively they can solve a captcha. The problem is that in order to prevent robots from registering a...
Google App Engine (Python)- Strange behaviour of REMOTE_ADDR
In order to make the registration process on my website easy, I allow users to enter their email address which I will send a verification code to or alternatively they can solve a captcha. The problem is that in order to prevent robots from registering accounts (with fake emails) I limit the number of registrations all...
[ "I believe that I have figured out the reason for seeing so many warnings from google server IP addresses. It seems that immediately after a new user registers, the google crawlers are going to the same (registration) webpage (which I send information to as a GET instead of a POST for reasons which I will not get i...
[ 0 ]
[]
[]
[ "google_app_engine", "ip_address", "python" ]
stackoverflow_0003877631_google_app_engine_ip_address_python.txt
Q: Help editing a picture in python I have to suppose I'm given a picture, there shouldnt be any user inputs or calls to media.chose file, so given a picture return the average red value of all the Pixels in that Picture (as an int). If the average calculation results in a non-integer value, then truncate the result....
Help editing a picture in python
I have to suppose I'm given a picture, there shouldnt be any user inputs or calls to media.chose file, so given a picture return the average red value of all the Pixels in that Picture (as an int). If the average calculation results in a non-integer value, then truncate the result. For example, if you average the value...
[ "The question is almost answered here \n\nHow can I read the RGB value of a given pixel in Python?\n\nUse PIL to load the image, read it pixel by pixel and do your calculation.\n", "Python Imaging Library\n" ]
[ 1, 0 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0003877878_image_processing_python.txt
Q: Determine if a dice roll contains certain combinations? I am writing a dice game simulator in Python. I represent a roll by using a list containing integers from 1-6. So I might have a roll like this: [1,2,1,4,5,1] I need to determine if a roll contains scoring combinations, such as 3 of a kind, 4 of a kind, 2 ...
Determine if a dice roll contains certain combinations?
I am writing a dice game simulator in Python. I represent a roll by using a list containing integers from 1-6. So I might have a roll like this: [1,2,1,4,5,1] I need to determine if a roll contains scoring combinations, such as 3 of a kind, 4 of a kind, 2 sets of 3, and straights. Is there a simple Pythonic way of d...
[ "Reorganize into a dict with value: count and test for presence of various patterns.\n", "There are two ways to do this:\ndef getCounts(L):\n d = {}\n for i in range(1, 7):\n d[i] = L.count(i)\n return d # d is the dictionary which contains the occurrences of all possible dice values\n ...
[ 4, 2, 2 ]
[]
[]
[ "algorithm", "dice", "dictionary", "list", "python" ]
stackoverflow_0003877909_algorithm_dice_dictionary_list_python.txt
Q: How to catch login failures with PySVN? I'm new to Python and PySVN in general, and I'm trying to export my SVN repository using pysvn. Here's my code: #set up svn login data def svn_credentials (realm, username, may_save): return True, svn_login_name, svn_login_password, False #establish connection svn_...
How to catch login failures with PySVN?
I'm new to Python and PySVN in general, and I'm trying to export my SVN repository using pysvn. Here's my code: #set up svn login data def svn_credentials (realm, username, may_save): return True, svn_login_name, svn_login_password, False #establish connection svn_client = pysvn.Client () svn_client.callbac...
[ "If the credentials are wrong pysvn will call the callback, if the credentials are still wrong it will call it again, and again, and it will just keep doing that until the credentials are correct.\nFor an automated script you are probably better off not setting the callback and instead setting the default username ...
[ 4, 1 ]
[]
[]
[ "infinite_loop", "pysvn", "python" ]
stackoverflow_0002625344_infinite_loop_pysvn_python.txt
Q: Why are main runnable Python scripts not compiled to pyc files like modules? I understand that when you import a module, that file is compiled into a .pyc file to make it faster? Why is the main file also not compiled to a .pyc? Does this slow things down? Would it be better to keep the main file as small as possi...
Why are main runnable Python scripts not compiled to pyc files like modules?
I understand that when you import a module, that file is compiled into a .pyc file to make it faster? Why is the main file also not compiled to a .pyc? Does this slow things down? Would it be better to keep the main file as small as possible then, or does it not matter?
[ "When a module is loaded, the py file is \"byte compiled\" to pyc files. The time stamp is recorded in pyc files.\nThis is done not to make it run faster but to load faster. \nHence, it makes sense to \"byte compile\" modules when you load them.\n\nhttp://docs.python.org/tutorial/modules.html#compiled-python-files\...
[ 35, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003878479_python.txt
Q: Strange Problem with RPy2 After installing RPy2 from http://rpy.sourceforge.net/rpy2.html I'm trying to use it in Python 2.6 IDLE but I'm getting this error: >>> import rpy2.robjects as robjects >>> robjects.r['pi'] <RVector - Python:0x0121D8F0 / R:0x022A1760> What I'm doing wrong? A: Have you tried looking a...
Strange Problem with RPy2
After installing RPy2 from http://rpy.sourceforge.net/rpy2.html I'm trying to use it in Python 2.6 IDLE but I'm getting this error: >>> import rpy2.robjects as robjects >>> robjects.r['pi'] <RVector - Python:0x0121D8F0 / R:0x022A1760> What I'm doing wrong?
[ "Have you tried looking at the vector that's returned?\n >>> pi = robjects.r['pi']\n >>> pi[0]\n 3.14159265358979\n\n", "To expand on Shane's answer. rpy2 uses the following Python objects to represent the basic R types:\n\nRVector: R scalars and vectors, R Lists are represented as RVectors with names, see below...
[ 8, 5, 1, 1, 0 ]
[]
[]
[ "python", "python_idle", "r" ]
stackoverflow_0001649503_python_python_idle_r.txt
Q: Lisp's apply and funcall vs Python's apply Lisp's APPLY is for calling functions with computed argument stored in lists.(Modified from Rainer's comment) For example, the following code changes (list 1 2 3) to (+ 1 2 3). (apply #'+ '(1 2 3)) However, Python's apply does what Lisp's funcall does, except for some ...
Lisp's apply and funcall vs Python's apply
Lisp's APPLY is for calling functions with computed argument stored in lists.(Modified from Rainer's comment) For example, the following code changes (list 1 2 3) to (+ 1 2 3). (apply #'+ '(1 2 3)) However, Python's apply does what Lisp's funcall does, except for some minor differences (input is given as tuple/list)...
[ "\nIs there any reason why Python chose the name apply not funcall?\n\nBecause it's Python, not LISP. No need to have the same name, funcall is a LISP command and apply is something different in Python.\napply is deprecated in Python, use the extended call syntax.\nOld syntax:\napply(foo, args, kwargs)\n\nNew synta...
[ 8, 4, 2, 2, 1 ]
[]
[]
[ "common_lisp", "lisp", "python", "python_2.x" ]
stackoverflow_0003856917_common_lisp_lisp_python_python_2.x.txt
Q: Python HTTP Redirect requests forbidden I'm trying to scrape a website where the URL is redirected, however programmatically trying this gives me an 403 Error code (Forbidden). I can place the URL in the browser and the browser will properly follow the url though... to show a simple example i'm trying to go to : ...
Python HTTP Redirect requests forbidden
I'm trying to scrape a website where the URL is redirected, however programmatically trying this gives me an 403 Error code (Forbidden). I can place the URL in the browser and the browser will properly follow the url though... to show a simple example i'm trying to go to : http://en.wikipedia.org/w/index.php?title=Mik...
[ "Try changing the mechanize flag to not respect robots.txt. Also, consider changing the User-Agent HTTP header:\n>>> import mechanize\n>>> br = mechanize.Browser()\n>>> br.set_handle_robots(False)\n>>> br.addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')]\n\nWeb servers will no...
[ 3, 0 ]
[]
[]
[ "http", "python", "redirect", "urllib2" ]
stackoverflow_0003878257_http_python_redirect_urllib2.txt
Q: Downloading Mp3 using Python in Windows mangles the song however in Linux it doesn't I've setup a script to download an mp3 using urllib2 in Python. url = 'example.com' req2 = urllib2.Request(url) response = urllib2.urlopen(req2) #grab the data data = response.read() mp3Name = "song.mp3" song = open(mp3Name, "w"...
Downloading Mp3 using Python in Windows mangles the song however in Linux it doesn't
I've setup a script to download an mp3 using urllib2 in Python. url = 'example.com' req2 = urllib2.Request(url) response = urllib2.urlopen(req2) #grab the data data = response.read() mp3Name = "song.mp3" song = open(mp3Name, "w") song.write(data) # was data2 song.close() Turns out it was somehow related to me dow...
[ "Try binary file mode. open(mp3Name, \"wb\")\nYou're probably getting line ending translations.\nThe file is binary, yes. It's the mode that wasn't. When a file is opened, it can be set to read as a text file (this is default). When it does this, it will convert line endings to match the platform. On Windows, line ...
[ 15 ]
[]
[]
[ "httpwebrequest", "mp3", "python", "web_scraping" ]
stackoverflow_0003878882_httpwebrequest_mp3_python_web_scraping.txt
Q: "Unable to find vcvarsall.bat" error when trying to install qrcode-0.2.1 Please help me to solve this error C:\Python26\Lib\site-packages\pyqrcode\encoder>python setup.py install running install running bdist_egg running egg_info writing qrcode.egg-info\PKG-INFO writing top-level names to qrcode.egg-info\top_level...
"Unable to find vcvarsall.bat" error when trying to install qrcode-0.2.1
Please help me to solve this error C:\Python26\Lib\site-packages\pyqrcode\encoder>python setup.py install running install running bdist_egg running egg_info writing qrcode.egg-info\PKG-INFO writing top-level names to qrcode.egg-info\top_level.txt writing dependency_links to qrcode.egg-info\dependency_links.txt package ...
[ "Distutils does not play well with MS Compiler tool chain.\nThis file is required to setup the environment which will help distutils to use MS compiler tool chains.\nThere are quite a few ways in which this has been made to work.\nPlease look at the following post which may help you.\n\nCompile Python 2.7 Packages ...
[ 17, 4 ]
[]
[]
[ "installation", "python", "qr_code" ]
stackoverflow_0003879014_installation_python_qr_code.txt
Q: Created HTTP response to be the same as accessing .jpg in Python I want to server an image file but accept some attributes for processing before hand using Python and google app engine. Where I would normally have 'http://www.domain.com/image/desiredImage.jpg' as the image to server. I want to be able to add some ...
Created HTTP response to be the same as accessing .jpg in Python
I want to server an image file but accept some attributes for processing before hand using Python and google app engine. Where I would normally have 'http://www.domain.com/image/desiredImage.jpg' as the image to server. I want to be able to add some tracking to it so I can do something similar to 'http://www.domain.com...
[ "Could be a couple issues. By overloading the image and providing arguments to it as if it were a script, you might be triggering javascript sandboxing/security stuff meant to prevent cross-site scripting attacks. \nAnother issue might be 'dumbness' of the client app, some clients might expect '.jpg' regardless of ...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003879038_google_app_engine_python.txt
Q: Interacting with a c struct containing only function pointers using ctypes in python I have a struct in a dll that only contains function pointers (ie a vtable) that I would like to interact with in python (for test purposes). I am having a bit of trouble working out how to do this using ctypes. What I have is: st...
Interacting with a c struct containing only function pointers using ctypes in python
I have a struct in a dll that only contains function pointers (ie a vtable) that I would like to interact with in python (for test purposes). I am having a bit of trouble working out how to do this using ctypes. What I have is: struct ITest { virtual char const *__cdecl GetName() = 0; virtual void __cde...
[ "Something like this should be a good starting point (I don't have your DLL compiled to test)\nfrom ctypes import Structure, CFUNCTYPE, POINTER, c_char_p, windll\nclass ITest(Structure):\n _fields_ = [\n ('GetName', CFUNCTYPE(c_char_p)),\n ('SetName', CFUNCTYPE(None, c_char_p)\n ]\n\...
[ 3, 1 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003854388_ctypes_python.txt
Q: Python programs on different Operating Systems If I write a python script using only python standard libraries, using Python 2.6 will it work on all Operating Systems as long as python 2.6 is installed? A: Depends. There are a few parts of the Python standard libraries that are only available on certain platform...
Python programs on different Operating Systems
If I write a python script using only python standard libraries, using Python 2.6 will it work on all Operating Systems as long as python 2.6 is installed?
[ "Depends. There are a few parts of the Python standard libraries that are only available on certain platforms. These parts are noted in the Python documentation.\nYou also need to be careful of how you handle things like file paths - using os.path.join() and such to make sure paths are formatted in the right way.\n...
[ 8, 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003878593_python.txt
Q: How best to get map from key list/value list in groovy? In python, I can do the following: keys = [1, 2, 3] values = ['a', 'b', 'c'] d = dict(zip(keys, values)) assert d == {1: 'a', 2: 'b', 3: 'c'} Is there a nice way to construct a map in groovy, starting from a list of keys and a list of values? A: There's a...
How best to get map from key list/value list in groovy?
In python, I can do the following: keys = [1, 2, 3] values = ['a', 'b', 'c'] d = dict(zip(keys, values)) assert d == {1: 'a', 2: 'b', 3: 'c'} Is there a nice way to construct a map in groovy, starting from a list of keys and a list of values?
[ "There's also the collectEntries function in Groovy 1.8\ndef keys = [1, 2, 3]\ndef values = ['a', 'b', 'c']\n[keys,values].transpose().collectEntries { it }\n\n", "Try this:\ndef keys = [1, 2, 3]\ndef values = ['a', 'b', 'c']\ndef pairs = [keys, values].transpose()\n\ndef map = [:]\npairs.each{ k, v -> map[k] = v...
[ 22, 12, 5 ]
[]
[]
[ "dictionary", "groovy", "python" ]
stackoverflow_0003877454_dictionary_groovy_python.txt
Q: Mutable Default Argument Returns None I have a simple code that finds paths using a graph stored in a dictionary. The code is exactly: def find_path(dct, init, depth, path=[]): if depth == 0: return path next_ = dct[init] depth-=1 find_path(dct, next_, depth) If I print the path right before ret...
Mutable Default Argument Returns None
I have a simple code that finds paths using a graph stored in a dictionary. The code is exactly: def find_path(dct, init, depth, path=[]): if depth == 0: return path next_ = dct[init] depth-=1 find_path(dct, next_, depth) If I print the path right before return path it prints to screen the correct pa...
[ "Shouldn't this \nfind_path(dct, next_, depth)\n\nbe \nreturn find_path(dct, next_, depth)\n# ^^^^\n# Return\n\nIn Python (unlike in say, Ruby) you have to explicitly return a value. Otherwise None is returned. \n", "Because you're calling it with depth greater than 0, which is causing it to fall off the end and ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003879307_python.txt
Q: Why do I have to put the project name when importing tasks when using Django with Celery? I just installed and configured Celery with RabbitMQ for a Django project and I was having an issue running tasks when I imported them like so: from someapp.tasks import SomeTask It worked when I added the project name: from...
Why do I have to put the project name when importing tasks when using Django with Celery?
I just installed and configured Celery with RabbitMQ for a Django project and I was having an issue running tasks when I imported them like so: from someapp.tasks import SomeTask It worked when I added the project name: from myproject.someapp.tasks import SomeTask I tried adding this into the settings.py file but it ...
[ "It's probably because you have\nINSTALLED_APPS = (\"myproject.someapp\", )\n\nInstead you should add the directory containing the apps on the Python path (the project in \nthis case), and simply do \nINSTALLED_APPS = (\"someapp\", )\n\nIMHO this makes more sense for an \"app\" anyway.\n" ]
[ 1 ]
[]
[]
[ "celery", "django", "python", "rabbitmq" ]
stackoverflow_0003869369_celery_django_python_rabbitmq.txt
Q: object oriented design question for gui application guys, I am programming a GUI for an application, a cd container to insert cd, and currently I am not very clear and I think I need some help to clarify my understanding about object oriented design. so, first, I use observer pattern to build abstract Model and V...
object oriented design question for gui application
guys, I am programming a GUI for an application, a cd container to insert cd, and currently I am not very clear and I think I need some help to clarify my understanding about object oriented design. so, first, I use observer pattern to build abstract Model and View classes and also the concrete models(cd container) an...
[ "Option 1 seems most appropriate. In general, you should avoid inheritance unless the pattern calls for it, or there's some other compelling reason to use it. Overuse of inheritance will make your code a lot more tightly integrated than it has to be.\n", "What might make this a bit easier for you to shed the coup...
[ 1, 1 ]
[]
[]
[ "design_patterns", "oop", "python", "user_interface", "wxwidgets" ]
stackoverflow_0003838688_design_patterns_oop_python_user_interface_wxwidgets.txt
Q: how quick read 25k small txt file content with python i download many html store in os,now get their content ,and extract data what i need to persistence to mysql, i use the traditional load file one by one ,it's not efficant cost nealy 8 mins. any advice is welcome g_fields=[ 'name', 'price', 'productid', 'si...
how quick read 25k small txt file content with python
i download many html store in os,now get their content ,and extract data what i need to persistence to mysql, i use the traditional load file one by one ,it's not efficant cost nealy 8 mins. any advice is welcome g_fields=[ 'name', 'price', 'productid', 'site', 'link', 'smallImage', 'bigImage', 'description', ...
[ "If you've got 25,000 text files on disk, 'you're doing it wrong'. Depending on how you store them on disk, the slowness could literally be seeking on disk to find the files. \nIf you've got 25,0000 of anything it'll be faster if you put it in a database with an intelligent index -- even if you make the index field...
[ 0, 0, 0 ]
[]
[]
[ "file", "performance", "python" ]
stackoverflow_0003878918_file_performance_python.txt
Q: Downloading a webpage using urllib2 results in garbled junk? (only sometimes) How come I hit this webpage, I get HTML text: http://itunes.apple.com/us/app/mobile/id381057839 But when I hit this webpage, I get garbled junk? http://itunes.apple.com/us/app/mobile/id375562663 I use the same download() function in py...
Downloading a webpage using urllib2 results in garbled junk? (only sometimes)
How come I hit this webpage, I get HTML text: http://itunes.apple.com/us/app/mobile/id381057839 But when I hit this webpage, I get garbled junk? http://itunes.apple.com/us/app/mobile/id375562663 I use the same download() function in python, which is here: def download(source_url): try: socket.setdefaultti...
[ "Solved. It was compression issue.\ndef download(source_url):\n try:\n socket.setdefaulttimeout(10)\n agents = ['Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)','Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1)','Microsoft Internet Explorer/4.0b1 (Windows 95)','Opera/8.00 (Windows NT 5.1; U;...
[ 2 ]
[]
[]
[ "api", "http", "python", "rest", "urllib2" ]
stackoverflow_0003879633_api_http_python_rest_urllib2.txt
Q: how python manage object delete or destruction guys, I am rather new to python and learning it to build a gui application (with wypython). I have a question related with object destruction in python. e.g. in myFrame I have onNew (create a new document) and onOpen (open a file) method. briefly, it looks like this....
how python manage object delete or destruction
guys, I am rather new to python and learning it to build a gui application (with wypython). I have a question related with object destruction in python. e.g. in myFrame I have onNew (create a new document) and onOpen (open a file) method. briefly, it looks like this. def onNew self.data=DataModel() self.viewwi...
[ "Python has garbage collection. As long as you don't have any references to the old object hanging around it will be collected.\nAs soon as you say self.data = somethingElse then the old self.data won't have any references to it (unless another object had a reference to your object's self.data).\n" ]
[ 2 ]
[]
[]
[ "destruction", "object", "oop", "python" ]
stackoverflow_0003879860_destruction_object_oop_python.txt
Q: Python Extension Can't Use library_dirs WHen specifying library_dirs in a Python distutils.core.Extension I get this error when trying to build: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/dist.py:263: UserWarning: Unknown distribution option: 'library_dirs' warnings.warn(msg) Why ...
Python Extension Can't Use library_dirs
WHen specifying library_dirs in a Python distutils.core.Extension I get this error when trying to build: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/dist.py:263: UserWarning: Unknown distribution option: 'library_dirs' warnings.warn(msg) Why is this? I am using Python 2.5 on Mac OS X.
[ "The error means you're not passing library_dirs to distutils.core.Extension, but to the distutils.core.setup function.\n" ]
[ 1 ]
[]
[]
[ "c", "libraries", "python", "python_extensions" ]
stackoverflow_0003878673_c_libraries_python_python_extensions.txt
Q: How to create a list or tuple of empty lists in Python? I need to incrementally fill a list or a tuple of lists. Something that looks like this: result = [] firstTime = True for i in range(x): for j in someListOfElements: if firstTime: result.append([f(j)]) else: result[...
How to create a list or tuple of empty lists in Python?
I need to incrementally fill a list or a tuple of lists. Something that looks like this: result = [] firstTime = True for i in range(x): for j in someListOfElements: if firstTime: result.append([f(j)]) else: result[i].append(j) In order to make it less verbose an more elegan...
[ "result = [list(someListOfElements) for _ in xrange(x)]\n\nThis will make x distinct lists, each with a copy of someListOfElements list (each item in that list is by reference, but the list its in is a copy).\nIf it makes more sense, consider using copy.deepcopy(someListOfElements)\nGenerators and list comprehensio...
[ 53, 7, 5, 4, 0 ]
[]
[]
[ "memory_management", "python" ]
stackoverflow_0003880037_memory_management_python.txt
Q: Running a job on multiple nodes of a GridEngine cluster I have access to a 128-core cluster on which I would like to run a parallelised job. The cluster uses Sun GridEngine and my program is written to run using Parallel Python, numpy, scipy on Python 2.5.8. Running the job on a single node (4-cores) yields an ~3....
Running a job on multiple nodes of a GridEngine cluster
I have access to a 128-core cluster on which I would like to run a parallelised job. The cluster uses Sun GridEngine and my program is written to run using Parallel Python, numpy, scipy on Python 2.5.8. Running the job on a single node (4-cores) yields an ~3.5x improvement over a single core. I would now like to take t...
[ "Yes, you need to include the Grid Engine option -np 16 either in your script like this:\n# Use 16 processors\n#$ -np 16\n\nor on the command line when you submit the script. Or, for more permanent arrangements, use an .sge_request file.\nOn all the GE installations I've ever used this will give you 16 processors ...
[ 2 ]
[]
[]
[ "python", "qsub", "sungridengine" ]
stackoverflow_0003872977_python_qsub_sungridengine.txt
Q: Lua equivalent to Python dis()? In Python you have the ability to view the compiled bytecode of a user-defined function using dis. Is there a builtin equivalent to this for Lua? It would really useful! A: The luac utility that comes with standard lua can create an assembly listing from Lua source using its -l op...
Lua equivalent to Python dis()?
In Python you have the ability to view the compiled bytecode of a user-defined function using dis. Is there a builtin equivalent to this for Lua? It would really useful!
[ "The luac utility that comes with standard lua can create an assembly listing from Lua source using its -l option. For example, compiling from source on stdin:\n\nC:...> echo a=b | luac -l -\n\nmain (3 instructions, 12 bytes at 00334C30)\n0+ params, 2 slots, 0 upvalues, 0 locals, 2 constants, 0 functions\n ...
[ 7, 5, 2, 0 ]
[]
[]
[ "bytecode", "disassembly", "lua", "python" ]
stackoverflow_0003872861_bytecode_disassembly_lua_python.txt
Q: Arithmetic Progression in Python without storing all the values I'm trying to represent an array of evenly spaced floats, an arithmetic progression, starting at a0 and with elements a0, a0 + a1, a0 + 2a1, a0 + 3a1, ... This is what numpy's arange() method does, but it seems to allocate memory for the whole array o...
Arithmetic Progression in Python without storing all the values
I'm trying to represent an array of evenly spaced floats, an arithmetic progression, starting at a0 and with elements a0, a0 + a1, a0 + 2a1, a0 + 3a1, ... This is what numpy's arange() method does, but it seems to allocate memory for the whole array object and I'd like to do it using an iterator class which just stores...
[ "Well, one thing that you are doing wrong is that it should be for i, x in enumerate(a): print i, x.\nAlso, I'd probably use a generator method instead of the hassle with the __iter__ and next() methods, especially because your solution wouldn't allow you to iterate over the same mylist twice at the same time with ...
[ 3, 3, 1, 0, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0003880761_arrays_numpy_python.txt
Q: Standardizing camera input in OpenCV? (Contrast/Saturation/Brightness etc..) I am building an application using OpenCV that uses the webcam and runs some vision algorithms. I would like to make this application available on the internet after I am done, but I am concerned about the vast differences in camera setti...
Standardizing camera input in OpenCV? (Contrast/Saturation/Brightness etc..)
I am building an application using OpenCV that uses the webcam and runs some vision algorithms. I would like to make this application available on the internet after I am done, but I am concerned about the vast differences in camera settings on every computer, and I am worried that the algorithm may break if the settin...
[ "You can post process your image in openCV several ways.\nTo set the contrast you can use equalizeHist function.\nTo set brightness and saturation you should first convert the image to HSV color space with cvtColor. Then you can modify the saturation and the value (brightness) to an appropriate value by directly ac...
[ 3, 2 ]
[]
[]
[ "camera", "image_processing", "opencv", "python" ]
stackoverflow_0002733906_camera_image_processing_opencv_python.txt
Q: Require help in Django 'local variable 'form' referenced before assignment' I am having problem in django. I have created a form in my app where I can take details of a client. Now I want to create a form which can allow me to edit a form. However I am having some problems when I go to /index/edit_client/1, I get ...
Require help in Django 'local variable 'form' referenced before assignment'
I am having problem in django. I have created a form in my app where I can take details of a client. Now I want to create a form which can allow me to edit a form. However I am having some problems when I go to /index/edit_client/1, I get this error. local variable 'form' referenced before assignment I do not know wha...
[ "This will always run:\nreturn render_to_response('edit_client.html', {'form': form}\n\nBut if request.method is not POST, nothing is assigned to form.\nFixed code:\n@login_required \ndef edit_client(request, id=1):\n clients_list = Client.objects.filter(pk=id) \n form = ClientForm()\n if request.method =...
[ 5, 1 ]
[]
[]
[ "django", "django_forms", "html", "python", "syntax_error" ]
stackoverflow_0003881601_django_django_forms_html_python_syntax_error.txt
Q: Problem with MPICH2 & mpi4py Installation I'm on Windows XP2 32-bit machine. I'm trying to install MPICH2 & mpi4py. I've downloaded & installed MPICH2-1.2.1p1 I've downloaded & mpi4py When I run python setup.py install in mpi4pi\ directory. I get running install running build running build_py running build_ext M...
Problem with MPICH2 & mpi4py Installation
I'm on Windows XP2 32-bit machine. I'm trying to install MPICH2 & mpi4py. I've downloaded & installed MPICH2-1.2.1p1 I've downloaded & mpi4py When I run python setup.py install in mpi4pi\ directory. I get running install running build running build_py running build_ext MPI configuration: directory 'C:\Program Files\M...
[ "I don't know much about Python but here goes anyway:\nYour install script is failing to find a C compiler, C++ compiler or linker. Look inside the script and see where it is looking. Modify the script to look in the location where you have those items installed. You may (probably will) also find that you can sp...
[ 3, 0 ]
[]
[]
[ "installation", "mpi", "python" ]
stackoverflow_0003880231_installation_mpi_python.txt
Q: Deciding on RESTful Architecture for my Python code API I would like to build something like this Datastore | mycode.py | RESTful API | mywebapp.py(Django or Tornado) I checked Piston for Django but it seems that this way I am going to be tied to Django, I would rather have a RESTful API for mycode.py that is cons...
Deciding on RESTful Architecture for my Python code API
I would like to build something like this Datastore | mycode.py | RESTful API | mywebapp.py(Django or Tornado) I checked Piston for Django but it seems that this way I am going to be tied to Django, I would rather have a RESTful API for mycode.py that is consumable by more than one REST client and also can consume it f...
[ "Hmm, if you're into Python and open to a Java element, you might want to consider using the Java framework Restlet with Python code running in Jython. I'm a big fan of Restlet; its API embodies RESTful principles, so it encourages one to structure one's code and thinking according to those principles. It's also ju...
[ 0 ]
[]
[]
[ "java", "python", "rest" ]
stackoverflow_0003847803_java_python_rest.txt
Q: Future and stability of IronPython I am currently looking for a possible way to integrate my C++/C# application with some of my Python scripts. At this point, IronPython seems like the way to go. However, before proceeding, I would like to ask the following: How stable is IronPython right now? Is it ready for pro...
Future and stability of IronPython
I am currently looking for a possible way to integrate my C++/C# application with some of my Python scripts. At this point, IronPython seems like the way to go. However, before proceeding, I would like to ask the following: How stable is IronPython right now? Is it ready for production use? Are there any known major q...
[ "To answer your second question, yes, IronPython will be developed in the future. Right now, there is a \"language change moratorium\" on CPython, the main branch of Python (see PEP 3003. The Python folks want CPython, Jython, and other branches of Python development to catch up with CPython, and they've been doing...
[ 9 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0003881418_ironpython_python.txt
Q: Python: How to distinguish between inherited methods Newbie Python question. I have a class that inherits from several classes, and some of the specialization classes override some methods from the base class. In certain cases, I want to call the unspecialized method. Is this possible? If so, what's the syntax...
Python: How to distinguish between inherited methods
Newbie Python question. I have a class that inherits from several classes, and some of the specialization classes override some methods from the base class. In certain cases, I want to call the unspecialized method. Is this possible? If so, what's the syntax? class Base(object): def Foo(self): print "Ba...
[ "you can specifically make the call you want using the syntax\nBase.Foo(self)\n\nin your case:\nclass Base(object):\n # snipped\n\n def Bar(self):\n Base.Foo(self) # this will now call Base.Foo regardless of if a subclass\n # overrides it\n\n# snipped\n\n\nx = Composite()\nx.Foo...
[ 6 ]
[]
[]
[ "inheritance", "oop", "python" ]
stackoverflow_0003882109_inheritance_oop_python.txt
Q: Adding dynamic property to a python object site = object() mydict = {'name': 'My Site', 'location': 'Zhengjiang'} for key, value in mydict.iteritems(): setattr(site, key, value) print site.a # it doesn't work The above code didn't work. Any suggestion? A: The easiest way to populate one dict with another i...
Adding dynamic property to a python object
site = object() mydict = {'name': 'My Site', 'location': 'Zhengjiang'} for key, value in mydict.iteritems(): setattr(site, key, value) print site.a # it doesn't work The above code didn't work. Any suggestion?
[ "The easiest way to populate one dict with another is the update() method, so if you extend object to ensure your object has a __dict__ you could try something like this:\n>>> class Site(object):\n... pass\n...\n>>> site = Site()\n>>> site.__dict__.update(dict)\n>>> site.a\n\nOr possibly even:\n>>> class Site(o...
[ 7, 5, 1 ]
[]
[]
[ "add", "dynamic", "properties", "python" ]
stackoverflow_0003881895_add_dynamic_properties_python.txt
Q: IE7 vs. A Python Pickle Object I have an issue with IE7 not wanting to pass a pickled object through a ajax call using HTMLTMPL. It works in IE8 (and in compatibility mode) as well as in Firefox. I have pickled an object using the command: newhash['pickled'] = pickle.dumps(hash) Because JS didn't like the newlin...
IE7 vs. A Python Pickle Object
I have an issue with IE7 not wanting to pass a pickled object through a ajax call using HTMLTMPL. It works in IE8 (and in compatibility mode) as well as in Firefox. I have pickled an object using the command: newhash['pickled'] = pickle.dumps(hash) Because JS didn't like the newlines, i regex them out using: newhash[...
[ "First, read Why Python Pickle is Insecure. Don't use pickled objects that could be modified by users.\nInstead, why not simply use JSON, which is obviously made for JavaScript. It is included in Python >= 2.6 and also available for older versions. As your data is just a dictionary, JSON should work just fine.\nAno...
[ 3, 1, 0 ]
[]
[]
[ "ajax", "internet_explorer_7", "pickle", "python" ]
stackoverflow_0003881958_ajax_internet_explorer_7_pickle_python.txt
Q: Grab elements inside parentheses How can I grab the elements inside the parentheses and put them in a file? me (I) you (You) him (He) her (She) Thanks in advance, Adia A: import re txt = 'me (I) you (You) him (He) her (She)' words = re.findall('\((.+?)\)', txt) # words returns: ['I', 'You', 'He', 'She'] with ...
Grab elements inside parentheses
How can I grab the elements inside the parentheses and put them in a file? me (I) you (You) him (He) her (She) Thanks in advance, Adia
[ "import re\n\ntxt = 'me (I) you (You) him (He) her (She)'\nwords = re.findall('\\((.+?)\\)', txt)\n\n# words returns: ['I', 'You', 'He', 'She']\nwith open('filename.txt', 'w') as out:\n out.write('\\n'.join(words))\n\n# file 'filename.txt' contains now:\n\nI\nYou\nHe\nShe\n\n", "Have you checked out pyparsing?...
[ 5, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003882407_python_regex.txt
Q: Python 2.6 to 2.5 cheat sheet I've written my code to target Python 2.6.5, but I now need to run it on a cluster that only has 2.5.4, something that wasn't on the horizon when I wrote the code. Backporting the code to 2.5 shouldn't be too hard, but I was wondering if there was either a cheat-sheet or an automated ...
Python 2.6 to 2.5 cheat sheet
I've written my code to target Python 2.6.5, but I now need to run it on a cluster that only has 2.5.4, something that wasn't on the horizon when I wrote the code. Backporting the code to 2.5 shouldn't be too hard, but I was wondering if there was either a cheat-sheet or an automated tool that would help me with this. ...
[ "Have you read the What's New in Python 2.6 document? It describes the 2.5->2.6 direction, but you should be able to figure out the reverse from it.\nAs far as I know, there are no automated tools for 2.6 to 2.5. The only tool I know of is the 2to3 app for going to Python 3.\n", "Have you tried pyqver? It will ...
[ 8, 4 ]
[]
[]
[ "backport", "python", "python_2.5", "python_2.6" ]
stackoverflow_0003881980_backport_python_python_2.5_python_2.6.txt
Q: Getting rid of \x## in strings (Python) I need to extract a description from a file, which looks like this: "TES4!\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x00\x00\x00HEDR\x0c\x00\xd7\xa3p?h\x03\x00\x00\x00\x08\x00\xffCNAM\t\x00Martigen\x00SNAM\xaf\x00Mart's Mutant Mod - RC4\n\nDiverse creat...
Getting rid of \x## in strings (Python)
I need to extract a description from a file, which looks like this: "TES4!\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x00\x00\x00HEDR\x0c\x00\xd7\xa3p?h\x03\x00\x00\x00\x08\x00\xffCNAM\t\x00Martigen\x00SNAM\xaf\x00Mart's Mutant Mod - RC4\n\nDiverse creatures & NPCs, new creatures & NPCs, dynamic si...
[ "you could try:\nimport string\n\ncleaneddata = ''.join(c for c in data if c in string.printable)\n\nThis assumes that you already have data in a string.\nHere's how it works for me:\n>>> s = \"\"\"TES4!\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x0f\\x00\\x00\\x00HEDR\\x0c\\x00\\xd...
[ 4, 4, 0 ]
[]
[]
[ "file", "python", "string" ]
stackoverflow_0003882607_file_python_string.txt
Q: Caesar Cipher in python The error which i am getting is Traceback (most recent call last): File "imp.py", line 52, in <module> mode = getMode() File "imp.py", line 8, in getMode mode = input().lower() File "<string>", line 1, in <module> NameError: name 'encrypt' is not defined Below is the code. # ...
Caesar Cipher in python
The error which i am getting is Traceback (most recent call last): File "imp.py", line 52, in <module> mode = getMode() File "imp.py", line 8, in getMode mode = input().lower() File "<string>", line 1, in <module> NameError: name 'encrypt' is not defined Below is the code. # Caesar Cipher MAX_KEY_SIZE ...
[ "The problem is here:\nprint('Do you wish to encrypt or decrypt a message?')\nmode = input().lower()\n\nIn Python 2.x input use raw_input() instead of input().\nPython 2.x:\n\nRead a string from standard input: raw_input()\nRead a string from standard input and then evaluate it: input().\n\nPython 3.x:\n\nRead a st...
[ 7, 2 ]
[]
[]
[ "input", "python", "python_2.x" ]
stackoverflow_0003883074_input_python_python_2.x.txt
Q: Qt Python Combo-Box "currentIndexChanged" firing twice I have a combo, which is showing some awkward behavior. Given a list of options from the combo-box, the user should pick the name of a city clicking with the mouse. Here is the code: QtCore.QObject.connect(self.comboCity, QtCore.SIGNAL("currentIndexChanged(QSt...
Qt Python Combo-Box "currentIndexChanged" firing twice
I have a combo, which is showing some awkward behavior. Given a list of options from the combo-box, the user should pick the name of a city clicking with the mouse. Here is the code: QtCore.QObject.connect(self.comboCity, QtCore.SIGNAL("currentIndexChanged(QString)"), self.checkChosenCity) def checkCh...
[ "I had exactly the same problem. After some debugging it turned out that using \ncurrentIndexChanged(int)\ninstead of\ncurrentIndexChanged(QString)\nfixed it for me.\nIt still don't understand why the former fires twice.\n" ]
[ 0 ]
[ "Thanks Eli..\nHere is what I have:\ncombo1 : [customernames] - pick a customer.\ncombo2 : [cityList] - pick a city for the chosen customer.\ncombo3 : [emploeeList] - load employees for that city, given the chosen customer.\n\nWhat I find out is that, even when no city is chosen, the combox-box for city is activate...
[ -1 ]
[ "combobox", "pyqt", "python", "qt" ]
stackoverflow_0001997478_combobox_pyqt_python_qt.txt
Q: Handling HTTP/1.1 Upgrade requests in CherryPy I'm using CherryPy for a web server, but would like it to handle HTTP/1.1 Upgrade requests. Thus, when a client sends: OPTIONS * HTTP/1.1 Upgrade: NEW_PROTOCOL/1.0 Connection: Upgrade I'd like the server to hand the connection off to some NEW_PROTOCOL handler after ...
Handling HTTP/1.1 Upgrade requests in CherryPy
I'm using CherryPy for a web server, but would like it to handle HTTP/1.1 Upgrade requests. Thus, when a client sends: OPTIONS * HTTP/1.1 Upgrade: NEW_PROTOCOL/1.0 Connection: Upgrade I'd like the server to hand the connection off to some NEW_PROTOCOL handler after responding with the necessary HTTP/1.1 101 Switching...
[ "This is fairly easy to do in trunk (which will eventually be 3.2 final). I'm sure it's possible in older versions but much more convoluted.\nAll you need to do is make a new subclass of wsgiserver.Gateway that looks for the headers in question and then either hands off the conn or proceeds to the usual gateway. Fo...
[ 2 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0003859823_cherrypy_python.txt
Q: How do I cleanly bridge client connections between a frontend webserver and a backend running CherryPy? The title may be a bit vague, but here's my goal: I have a frontend webserver which takes incoming HTTP requests, does some preprocessing on them, and then passes the requests off to my real webserver to get th...
How do I cleanly bridge client connections between a frontend webserver and a backend running CherryPy?
The title may be a bit vague, but here's my goal: I have a frontend webserver which takes incoming HTTP requests, does some preprocessing on them, and then passes the requests off to my real webserver to get the HTTP response, which is then passed back to the client. Currently, my frontend is built off of BaseHTTPServ...
[ "Is your main app a wsgi application? If so, you could write some middleware that wraps around it and does all the request wrangling before passing on to the main application. \nIf this this is possible it would avoid you having to run two webservers and all the problems you are encountering.\n", "Answered the Up...
[ 1, 0 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0003875490_cherrypy_python.txt
Q: Stop-word elimination and stemmer in python I have a somewhat large document and want to do stop-word elimination and stemming on the words of this document with Python. Does anyone know an of the shelf package for these? If not a code which is fast enough for large documents is also welcome. Thanks A: NLTK supp...
Stop-word elimination and stemmer in python
I have a somewhat large document and want to do stop-word elimination and stemming on the words of this document with Python. Does anyone know an of the shelf package for these? If not a code which is fast enough for large documents is also welcome. Thanks
[ "NLTK supports this.\n", "If for some reason you don't want to use NLTK, you can try PyStemmer. For stop words just download a list (google it) and filter them out.\n" ]
[ 8, 4 ]
[]
[]
[ "nlp", "python", "stemming", "stop_words" ]
stackoverflow_0003882921_nlp_python_stemming_stop_words.txt
Q: How to change text on gtk.label in frequent intervals - PyGTK I am coding a desktop application which shows contents from text file in a gtk.label, i update that text file, say once in every 15 mints. Are are there any methods to make the application to read the text file in constant intervals and display it witho...
How to change text on gtk.label in frequent intervals - PyGTK
I am coding a desktop application which shows contents from text file in a gtk.label, i update that text file, say once in every 15 mints. Are are there any methods to make the application to read the text file in constant intervals and display it without restarting the window
[ "On all platforms, you can call gobject.timeout_add() to read the file every once in a while, or gobject.idle_add() with an mtime check to do it when the app is idle.\nOn linux, I'd recommend using pyinotify to monitor the file and re-read it only when it's updated.\n" ]
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0003883431_gtk_pygtk_python.txt
Q: Adding Values to an Array and getting distinct values using Python I have python code below that will loop through a table and print out values within a particular column. What is not shown is the form in which the user selects a Feature Layer. Once the Feature Layer is selected a second Dropdown is populated wi...
Adding Values to an Array and getting distinct values using Python
I have python code below that will loop through a table and print out values within a particular column. What is not shown is the form in which the user selects a Feature Layer. Once the Feature Layer is selected a second Dropdown is populated with all the Column Headings for that Feature and the user chooses which C...
[ "You can store distinct values in a set:\n>>> a = [ 1, 2, 3, 1, 5, 3, 2, 1, 5, 4 ]\n>>> b = set( a )\n>>> b\n{1, 2, 3, 4, 5}\n>>> b.add( 5 )\n>>> b\n{1, 2, 3, 4, 5}\n>>> b.add( 6 )\n>>> b\n{1, 2, 3, 4, 5, 6}\n\nAlso you can make your loop more pythonic, although I'm not sure why you loop over the row to begin with ...
[ 3, 1 ]
[]
[]
[ "arcgis", "python" ]
stackoverflow_0003883836_arcgis_python.txt
Q: Any dhcp python library? Is there any library to help me instantiate a dhcp server in python? A: There are some in development and alpha verity : http://ostatic.com/pydhcpd/ Other servers: http://code.google.com/p/staticdhcpd/ And a library for working on dhcp too http://nixbit.com/cat/programming/libraries...
Any dhcp python library?
Is there any library to help me instantiate a dhcp server in python?
[ "There are some in development and alpha verity :\n\nhttp://ostatic.com/pydhcpd/\n\nOther servers:\n\nhttp://code.google.com/p/staticdhcpd/\n\nAnd a library for working on dhcp too\n\nhttp://nixbit.com/cat/programming/libraries/pydhcplib/\n\nDHCP command line query and testing tool\n\nhttp://code.google.com/p/dhque...
[ 8, 4 ]
[]
[]
[ "dhcp", "python" ]
stackoverflow_0003883811_dhcp_python.txt
Q: How to: remove part of a Unicode string in Python following a special character first a short summery: python ver: 3.1 system: Linux (Ubuntu) I am trying to do some data retrieval through Python and BeautifulSoup. Unfortunately some of the tables I am trying to process contains cells where the following text strin...
How to: remove part of a Unicode string in Python following a special character
first a short summery: python ver: 3.1 system: Linux (Ubuntu) I am trying to do some data retrieval through Python and BeautifulSoup. Unfortunately some of the tables I am trying to process contains cells where the following text string exists: 789.82 ± 10.28 For this i to work i need two things: How do i handle "weird...
[ "You need to have your Python file encoded in utf-8. Otherwise, it's quite trivial:\n>>> s = '789.82 ± 10.28'\n>>> s[:s.index('±')]\n'789.82 '\n>>> s.partition('±')\n('789.82 ', '±', ' 10.28')\n\n" ]
[ 0 ]
[]
[]
[ "beautifulsoup", "python", "special_characters", "string", "unicode" ]
stackoverflow_0003883976_beautifulsoup_python_special_characters_string_unicode.txt
Q: Maintaining a Python Object when embedding in C Due to refactoring/reworking on a controller I've had to embed a Python Interpreter inside a C application. I can now call python functions and pass/get Objects into Python fine. The python code is a controller for a robot (currently simulated), this now needs make...
Maintaining a Python Object when embedding in C
Due to refactoring/reworking on a controller I've had to embed a Python Interpreter inside a C application. I can now call python functions and pass/get Objects into Python fine. The python code is a controller for a robot (currently simulated), this now needs make use of some C code for comparisons I'm making. Previ...
[ "This may not be the answer you want, but there are ways of working with C and Python other than embedding an interpreter inside a C application.\nNamely, why don't you do the opposite? Create C libraries for Python? You can control the general flow of your application in Python, which is much more comfortable, and...
[ 1 ]
[]
[]
[ "c", "embedded_language", "python" ]
stackoverflow_0003883724_c_embedded_language_python.txt
Q: Designing an Python API: Fluent interface or arguments I'm playing around with a simple port of the Protovis API to Python. Consider the simple bar chart example, in Javascript: var vis = new pv.Panel() .width(150) .height(150); vis.add(pv.Bar) .data([1, 1.2, 1.7, 1.5, .7, .3]) .width(20) .h...
Designing an Python API: Fluent interface or arguments
I'm playing around with a simple port of the Protovis API to Python. Consider the simple bar chart example, in Javascript: var vis = new pv.Panel() .width(150) .height(150); vis.add(pv.Bar) .data([1, 1.2, 1.7, 1.5, .7, .3]) .width(20) .height(function(d) d * 80) .bottom(0) .left(function(...
[ "My vote is anti-chaining, pro-named-params.\n\ndot-chaining makes for poor code-intellisense since the empirical prototype is just an empty Panel() or Bar(), you can of course pydoc on it, but in this day and age intellisense is available in most IDEs and a great productivity booster.\nChaining makes programatical...
[ 20 ]
[]
[]
[ "interface_design", "python" ]
stackoverflow_0003883907_interface_design_python.txt
Q: combining strings using string substitution - python hey guys, i want to perform the following operation: b = 'random' c = 'stuff' a = '%s' + '%s' %(b, c) but i get the following error: TypeError: not all arguments converted during string formatting does any one of you know to do so ? A: '%s%s' % (b, c) or...
combining strings using string substitution - python
hey guys, i want to perform the following operation: b = 'random' c = 'stuff' a = '%s' + '%s' %(b, c) but i get the following error: TypeError: not all arguments converted during string formatting does any one of you know to do so ?
[ "'%s%s' % (b, c)\n\nor \nb + c\n\nor the newstyle format way\n'{0}{1}'.format(a, b)\n\n", "Depending on what you want :\n>>> b = 'random'\n>>> c = 'stuff'\n>>> a = '%s' %b + '%s' % c\n>>> a\n'randomstuff'\n>>> \n\n>>> b + c\n'randomstuff'\n>>> \n>>> z = '%s + %s' % (b, c)\n>>> z\n'random + stuff'\n>>> \n\n", "...
[ 4, 1, 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0003884061_python_syntax.txt
Q: How to deal with IndentationError? I get the following error: File "imp.py", line 55 key = get Key() ^ IndentationError: expected an indented block With the following Code: # Caesar Cipher MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt or brute force ...
How to deal with IndentationError?
I get the following error: File "imp.py", line 55 key = get Key() ^ IndentationError: expected an indented block With the following Code: # Caesar Cipher MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt or brute force a message?') mode = raw_input()....
[ "\nDo not use += to build strings. Use ''.join(mylist)\nDo as it asks: give it an indented block.\n\n", "From An Informal Introduction to Python, \"The body of the loop is indented: indentation is Python’s way of grouping statements.\"\nIf you are familiar with C or Java, you might recognize this syntax:\nif (.....
[ 3, 2 ]
[]
[]
[ "indentation", "python", "syntax" ]
stackoverflow_0003884006_indentation_python_syntax.txt
Q: How do I use regular expressions to parse HTML tags? Was wondering how I would extrapolate the value of an html element using a regular expression (in python preferably). For example, <a href="http://google.com"> Hello World! </a> What regex would I use to extract Hello World! from the above html? A: Using regex...
How do I use regular expressions to parse HTML tags?
Was wondering how I would extrapolate the value of an html element using a regular expression (in python preferably). For example, <a href="http://google.com"> Hello World! </a> What regex would I use to extract Hello World! from the above html?
[ "Using regex to parse HTML has been covered extensively on SO. The consensus is that it shouldn't be done.\nHere are some related links worth reading:\n\nRegEx match open tags except XHTML self-contained tags\nhttp://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html\n\nOne trick I have used in th...
[ 8, 7, 0 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0003884419_html_python_regex.txt
Q: Is there a processing python implementation? There are javascript and actionscript ports of Processing. Is there a python port ? A: There is pyprocessing, which is experimental. A: And there's the more pythonic: http://nodebox.net/code/index.php/Home A: Just to add to the existing answers: Field, via @yaxu ...
Is there a processing python implementation?
There are javascript and actionscript ports of Processing. Is there a python port ?
[ "There is pyprocessing, which is experimental. \n", "And there's the more pythonic: http://nodebox.net/code/index.php/Home\n", "Just to add to the existing answers: Field, via @yaxu\n\n\n\nUpdate\nAs of 15.04.2014 (version 2.1.2) Processing includes a Python mode in development.\n", "pygame already comes pret...
[ 5, 3, 1, 1 ]
[]
[]
[ "port", "processing", "python" ]
stackoverflow_0003398190_port_processing_python.txt
Q: How can I open a Python shell at a network path in Windows? How can I open a Python interpreter at a specific network path in Windows? In the Explorer address bar the path is in UNC form: \\myhost\myshare\.... I can't work out how to change to this directory from the Windows command line, nor in what format I coul...
How can I open a Python shell at a network path in Windows?
How can I open a Python interpreter at a specific network path in Windows? In the Explorer address bar the path is in UNC form: \\myhost\myshare\.... I can't work out how to change to this directory from the Windows command line, nor in what format I could pass it as an argument to os.chdir. I'm running Python 2.5 on W...
[ "Well, I'm going to ask it anyway because it has bit me before but have you tried something like this?\npath = r'\\\\myhost\\myshare\\some_file.dat'\n\nThe r being the important bit here.See this post as well.\n", "You need to map it as a drive.\n", "hope this helps : http://www.blog.pythonlibrary.org/2008/05/1...
[ 2, 0, 0 ]
[]
[]
[ "python", "windows_xp" ]
stackoverflow_0003884881_python_windows_xp.txt
Q: Parse dict of dicts to string I have a dictionary with following structure : {1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}} I'd like to create a string containing values from the inner dictionary in this form : string = "<span>test1</span><span>user1</span><br /> ...
Parse dict of dicts to string
I have a dictionary with following structure : {1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}} I'd like to create a string containing values from the inner dictionary in this form : string = "<span>test1</span><span>user1</span><br /> <span>test2</span>..." I've tried...
[ ">>> d={1: {'message': u'test', 'user': u'user1'}, 2: {'message': u'test2', 'user': u'user2'}}\n\n>>> ''.join('<span>%(message)s</span><span>%(user)s</span><br/>' % v for k,v in sorted(d.items()))\nu'<span>test</span><span>user1</span><br/><span>test2</span><span>user2</span><br/>'\n\n", "How about something like...
[ 4, 1, 1, 0 ]
[]
[]
[ "dictionary", "parsing", "python" ]
stackoverflow_0003884990_dictionary_parsing_python.txt
Q: Why am I getting Name Error when importing a class? I am just starting to learn Python, but I have already run into some errors. I have made a file called pythontest.py with the following contents: class Fridge: """This class implements a fridge where ingredients can be added and removed individually or...
Why am I getting Name Error when importing a class?
I am just starting to learn Python, but I have already run into some errors. I have made a file called pythontest.py with the following contents: class Fridge: """This class implements a fridge where ingredients can be added and removed individually or in groups""" def __init__(self, items={}): "...
[ "No one seems to mention that you can do \nfrom pythontest import Fridge\n\nThat way you can now call Fridge() directly in the namespace without importing using the wildcard\n", "You need to do:\n>>> import pythontest\n>>> f = pythontest.Fridge()\n\nBonus: your code would be better written like this:\ndef __init_...
[ 9, 5, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003885084_python.txt
Q: Determine IP address of CONNECTED interface (linux) in python On my linux machine, 1 of 3 network interfaces may be actually connected to the internet. I need to get the IP address of the currently connected interface, keeping in mind that my other 2 interfaces may be assigned IP addresses, just not be connected. ...
Determine IP address of CONNECTED interface (linux) in python
On my linux machine, 1 of 3 network interfaces may be actually connected to the internet. I need to get the IP address of the currently connected interface, keeping in mind that my other 2 interfaces may be assigned IP addresses, just not be connected. I can just ping a website through each of my interfaces to determin...
[ "If the default gateway for the system is reliable, then grab that from the output from route -n the line that contains \" UG \" (note the spaces) will also contain the IP of the gateway and interface name of the active interface.\n", "the solution is here : http://code.activestate.com/recipes/439093-get-names-of...
[ 0, 0 ]
[]
[]
[ "ip_address", "linux", "networking", "python" ]
stackoverflow_0003885160_ip_address_linux_networking_python.txt
Q: using function attributes to store results for lazy (potential) processing I'm doing some collision detection and I would very much like to use the same function in two different contexts. In one context, I would like for it to be something like def detect_collisions(item, others): return any(collides(item, ot...
using function attributes to store results for lazy (potential) processing
I'm doing some collision detection and I would very much like to use the same function in two different contexts. In one context, I would like for it to be something like def detect_collisions(item, others): return any(collides(item, other) for other in others) and in another, I would like it to be def get_collisi...
[ "Just make get_collisions return a generator:\ndef get_collisions(item, others):\n return (other for other in others if collides(item, other))\n\nThen, if you want to do a check:\nfor collision in get_collisions(item, others):\n    print 'Collision!'\n break\nelse:\n    print 'No collisions!'\n\n", "This is...
[ 4, 0 ]
[]
[]
[ "function_attributes", "python" ]
stackoverflow_0003881211_function_attributes_python.txt
Q: Is it possible to use a USB flash drive to serve files locally to a browser? Using just python, is it possible to possible to use a USB flash drive to serve files locally to a browser, and save information off the online web? Ideally I would only need python. Where would I start? A: You can use portable python o...
Is it possible to use a USB flash drive to serve files locally to a browser?
Using just python, is it possible to possible to use a USB flash drive to serve files locally to a browser, and save information off the online web? Ideally I would only need python. Where would I start?
[ "You can use portable python on the flash drive. Portable Python And code some sort of little python webserver, handling get and post extending the BaseHTTPRequestHandler class.\n", "This doesn't seem much different then serving files from a local hard drive. You could map the thumbdrive to always be something n...
[ 1, 0 ]
[]
[]
[ "python", "usb", "web_services" ]
stackoverflow_0003885519_python_usb_web_services.txt
Q: Special character use in Python 2.6 I am more than a bit tired, but here goes: I am doing tome HTML scraping in python 2.6.5 with BeautifulSoap on an ubuntubox Reason for python 2.6.5: BeautifulSoap sucks under 3.1 I try to run the following code: # dataretriveal from html files from DETHERM # -*- coding: utf-8 -*...
Special character use in Python 2.6
I am more than a bit tired, but here goes: I am doing tome HTML scraping in python 2.6.5 with BeautifulSoap on an ubuntubox Reason for python 2.6.5: BeautifulSoap sucks under 3.1 I try to run the following code: # dataretriveal from html files from DETHERM # -*- coding: utf-8 -*- import sys,os,re,csv from BeautifulSou...
[ "Byte strings like \"±\" (in Python 2.x) are encoded in the source file's encoding, which might not be what you want. If col2 is really a Unicode object, you should use u\"±\" instead like you already tried. You might know that somestring.index raises an exception if it doesn't find an occurrence whereas somestring...
[ 2 ]
[]
[]
[ "beautifulsoup", "python", "special_characters" ]
stackoverflow_0003885569_beautifulsoup_python_special_characters.txt
Q: How to strip variable spaces in each line of a text file based on special condition - one-liner in Python? I have some data (text files) that is formatted in the most uneven manner one could think of. I am trying to minimize the amount of manual work on parsing this data. Sample Data : Name Degree CLA...
How to strip variable spaces in each line of a text file based on special condition - one-liner in Python?
I have some data (text files) that is formatted in the most uneven manner one could think of. I am trying to minimize the amount of manual work on parsing this data. Sample Data : Name Degree CLASS CODE EDU Scores ----------------------------------------------------------------------------...
[ "It still seems tome that there's some format in your files:\n>>> regex = r'^(.+)\\b\\s{2,}\\b(.+)\\s+(\\d+)\\s+(\\d+)\\s+(.+)\\s+(\\d+)'\n>>> for line in s.splitlines():\n lst = [i.strip() for j in re.findall(regex, line) for i in j if j]\n print(lst)\n\n\n[]\n[]\n['John Marshall', 'CSC', '78659944', '89989'...
[ 3, 2, 1 ]
[]
[]
[ "delimiter", "formatting", "parsing", "python", "text_parsing" ]
stackoverflow_0003874117_delimiter_formatting_parsing_python_text_parsing.txt
Q: Ruby use case for nil, equivalent to Python None or JavaScript undefined How does Ruby's nil manifest in code? For example, in Python you might use None for a default argument when it refers to another argument, but in Ruby you can refer to other arguments in the arg list (see this question). In JS, undefined pops...
Ruby use case for nil, equivalent to Python None or JavaScript undefined
How does Ruby's nil manifest in code? For example, in Python you might use None for a default argument when it refers to another argument, but in Ruby you can refer to other arguments in the arg list (see this question). In JS, undefined pops up even more because you can't specify default arguments at all. Can you give...
[ "Ruby's nil and Python's None are equivalent in the sense that they represent the absence of a value. However, people coming from Python may find some behavior surprising. First, Ruby returns nil in situations Python raises an exception:\nAccessing arrays and hashes:\n[1, 2, 3][999] # nil. But [].fetch(0) raises an...
[ 9, 2, 2, 0, 0 ]
[]
[]
[ "javascript", "null", "python", "ruby" ]
stackoverflow_0003884004_javascript_null_python_ruby.txt
Q: Windows platform programming I am hired by my local company here which makes small accounting/billing/payroll softwares to manage its clients' companies. Most of them use windows platform and the softwares themselves will not be too complex ones. I want to ask which language should i opt for? Python, C#, VB.net or...
Windows platform programming
I am hired by my local company here which makes small accounting/billing/payroll softwares to manage its clients' companies. Most of them use windows platform and the softwares themselves will not be too complex ones. I want to ask which language should i opt for? Python, C#, VB.net or something else which will make th...
[ "For programming on Windows you want to go with .NET and probably WPF for the presentation layer if you can wrap your head around MVVM as it gives you much more scope for delivering flexible UIs than forms. \nFor cross platform utility - probably python, but I'm not sure I'd want it to be my principal development t...
[ 2, 2, 0, 0 ]
[]
[]
[ "c#", "python", "user_interface", "vb.net" ]
stackoverflow_0003884405_c#_python_user_interface_vb.net.txt
Q: Calling a file in python I'd like to call a .py file from within python. It is in the same directory. Effectivly, I would like the same behavior as calling python foo.py from the command line without using any of the command line tools. How should I do this? A: execfile('foo.py') See also: Further reading on e...
Calling a file in python
I'd like to call a .py file from within python. It is in the same directory. Effectivly, I would like the same behavior as calling python foo.py from the command line without using any of the command line tools. How should I do this?
[ "execfile('foo.py')\n\nSee also:\n\nFurther reading on execfile\n\n", "It's not quite clear (at least to me) what you mean by using \"none of the command-line tools\". \nTo run a program in a subprocess, one usually uses the subprocess module. However, if both the calling and the callee are python scripts, there ...
[ 4, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003885846_python.txt
Q: type of class in python why if I do: class C(): pass type(C()) I got: <type 'instance'>, but if I do: class C(object): pass type(c()) I got: <class '__main__.c'> ? The first is not very userfull A: Look up the difference between old-style and new-style classes. The former are the default, and the latter inheri...
type of class in python
why if I do: class C(): pass type(C()) I got: <type 'instance'>, but if I do: class C(object): pass type(c()) I got: <class '__main__.c'> ? The first is not very userfull
[ "Look up the difference between old-style and new-style classes. The former are the default, and the latter inherit explicitly from object.\nAll old-style objects were implemented with the built-in type instance. The fact that they are still the default and their type remains 'instance' is a result of retro-compati...
[ 3 ]
[]
[]
[ "class", "new_style_class", "python", "types" ]
stackoverflow_0003886117_class_new_style_class_python_types.txt
Q: How to use session on Google app engine I'm building an application using Google app engine with python, and I'm stuck with making sessions. Is there any app that already does that for app engine? Thank you. A: I recommend gae-sessions. The source includes demos which show how to use it, including how to integr...
How to use session on Google app engine
I'm building an application using Google app engine with python, and I'm stuck with making sessions. Is there any app that already does that for app engine? Thank you.
[ "I recommend gae-sessions. The source includes demos which show how to use it, including how to integrate with the Users API or RPX/JanRain.\nDisclaimer: I wrote gae-sessions, but for an informative comparison of it with alternatives, read this article.\n" ]
[ 20 ]
[]
[]
[ "authentication", "google_app_engine", "python", "session" ]
stackoverflow_0003885996_authentication_google_app_engine_python_session.txt
Q: Python module paramiko cannot connect as paramiko.Transport((host,port)).connect(username = username, password = password) This is an example which works fine on friend's computer: import paramiko host = "157.178.35.134" port = 222 username = "stackoverflow" password = "e2fghK3" transport = paramiko.Transport((h...
Python module paramiko cannot connect as paramiko.Transport((host,port)).connect(username = username, password = password)
This is an example which works fine on friend's computer: import paramiko host = "157.178.35.134" port = 222 username = "stackoverflow" password = "e2fghK3" transport = paramiko.Transport((host, port)) transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) ...
[ "Can you try this and let me know how it goes:\nssh = paramiko.SSHClient()\nssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\nssh.connect(\"157.178.35.13\", username=\"stackoverflow\", password=\"e2fghK3\")\nftp=ssh.open_sftp()\npath = './file.testy' #server\nlocalpath = '/home/iwtu/test' \nftp.put(loca...
[ 2 ]
[]
[]
[ "eoferror", "paramiko", "python" ]
stackoverflow_0003410369_eoferror_paramiko_python.txt
Q: More efficient ways of doing this for i in vr_world.getNodeNames(): if i != "_error_": World[i] = vr_world.getChild(i) vr_world.getNodeNames() returns me a gigantic list, vr_world.getChild(i) returns a specific type of object. This is taking a long time to run, is there anyway to make it more efficie...
More efficient ways of doing this
for i in vr_world.getNodeNames(): if i != "_error_": World[i] = vr_world.getChild(i) vr_world.getNodeNames() returns me a gigantic list, vr_world.getChild(i) returns a specific type of object. This is taking a long time to run, is there anyway to make it more efficient? I have seen one-liners for loops be...
[ "I don't think you can make it faster than what you have there. Yes, you can put the whole thing on one line but that will not make it any faster. The bottleneck obviously is getNodeNames(). If you can make it a generator, you will start populating the World dict with results sooner (if that matters to you) and if ...
[ 1, 1, 0, 0 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0003885352_optimization_python.txt
Q: How do I remove the y-axis from a Pylab-generated picture? import pylab # matplotlib x_list = [1,1,1,1,5,4] y_list = [1,2,3,4,5,4] pylab.plot(x_list, y_list, 'bo') pylab.show() What I want to do is remove the y-axis from the diagram, only keeping the x-axis. And adding more margin to the diagram, we can see t...
How do I remove the y-axis from a Pylab-generated picture?
import pylab # matplotlib x_list = [1,1,1,1,5,4] y_list = [1,2,3,4,5,4] pylab.plot(x_list, y_list, 'bo') pylab.show() What I want to do is remove the y-axis from the diagram, only keeping the x-axis. And adding more margin to the diagram, we can see that a lot of dots are on the edge of the canvas and don't look g...
[ "ax = pylab.gca()\nax.yaxis.set_visible(False)\npylab.show()\n\n" ]
[ 14 ]
[]
[]
[ "matplotlib", "python", "python_imaging_library" ]
stackoverflow_0003886255_matplotlib_python_python_imaging_library.txt