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: hadoop-streaming : How reduce task calculates reduce input size? and how to fix it? I see the following in jobtracker log : 011-11-02 10:04:09,595 WARN org.apache.hadoop.mapred.JobInProgress: No room for reduce task. Node tracker_worker1:localhost/127.0.0.1:52295 has 62087933952 bytes free; but we expect reduce ...
hadoop-streaming : How reduce task calculates reduce input size? and how to fix it?
I see the following in jobtracker log : 011-11-02 10:04:09,595 WARN org.apache.hadoop.mapred.JobInProgress: No room for reduce task. Node tracker_worker1:localhost/127.0.0.1:52295 has 62087933952 bytes free; but we expect reduce input to take 176511226508 I want to know how hadoop calculated that reducer input ...
[ "Check the ResourceEstimator#getEstimatedReduceInputSize(). As always, the comments around the getEstimatedReduceInputSize function are sparse. Some effort has to be put to understand it.\n" ]
[ 1 ]
[]
[]
[ "hadoop", "hadoop_streaming", "mapreduce", "python" ]
stackoverflow_0007984418_hadoop_hadoop_streaming_mapreduce_python.txt
Q: How do I get the size of a pygtk window? I'm trying to use gtk.window.get_size(), but it always just returns the default width and height. The documentation says The get_size() method returns a tuple containing the current width and height of the window. If the window is not on-screen, it returns the size PyG...
How do I get the size of a pygtk window?
I'm trying to use gtk.window.get_size(), but it always just returns the default width and height. The documentation says The get_size() method returns a tuple containing the current width and height of the window. If the window is not on-screen, it returns the size PyGTK will suggest to the window manager for the ...
[ "This seems to fix your problem:\nimport gtk\n\ndef print_size(widget, data=None):\n print window.get_size()\n\ndef delete_event(widget, data=None):\n print window.get_size()\n return False\n\ndef destroy(widget, data=None):\n gtk.main_quit()\n\nwindow = gtk.Window()\nwindow.connect('delete_event', dele...
[ 6, 0 ]
[]
[]
[ "gtk", "pygtk", "python", "window" ]
stackoverflow_0007960915_gtk_pygtk_python_window.txt
Q: python subprocess proc.stderr.read() introduce extra lines? I want to run some command and grab whatever is output to stderr. I have two versions of function that does this version 1. def Getstatusoutput(cmd): """Return (status, output) of executing cmd in a shell.""" import sys mswindows = (sys.plat...
python subprocess proc.stderr.read() introduce extra lines?
I want to run some command and grab whatever is output to stderr. I have two versions of function that does this version 1. def Getstatusoutput(cmd): """Return (status, output) of executing cmd in a shell.""" import sys mswindows = (sys.platform == "win32") import os if not mswindows: cmd...
[ "You could use subprocess.check_output([cmd], stderr=STDOUT) to capture all output.\nTo capture stdout, stderr separately you could use .communicate():\nstdout, stderr = Popen([cmd], stdout=PIPE, stderr=PIPE).communicate()\n\nTo get all lines without a newline character at the end you could call stderr.splitlines()...
[ 2, 2 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0007985334_python_subprocess.txt
Q: wxPython Navigation Panel (like Finder (Mac OS X), Nautilus (Ubuntu), Explorer (Windows 7)) My question is simple how to get make a navigation panel that is similar to Finder (Mac OS X) Explorer (Windows 7) Nautilus (Ubuntu) As for using a wx.TreeCtrl that does not work.... Example http://paste.pocoo.org/show/...
wxPython Navigation Panel (like Finder (Mac OS X), Nautilus (Ubuntu), Explorer (Windows 7))
My question is simple how to get make a navigation panel that is similar to Finder (Mac OS X) Explorer (Windows 7) Nautilus (Ubuntu) As for using a wx.TreeCtrl that does not work.... Example http://paste.pocoo.org/show/500311/ As you can see the first problem is that there is a huge pink strip that is on the left a...
[ "Try using Treebook.\nupdate:\nAlternatively, try doing something with wx.lib.agw.foldpanelbar. Check out it's demo in the demo suite, depending on what you actually need it may be enough. If not, you can always make your own from scratch.\n", "If you are really looking for browsing directory structure:\nimport o...
[ 1, 1, 1 ]
[]
[]
[ "navigation", "python", "wxpython" ]
stackoverflow_0007943561_navigation_python_wxpython.txt
Q: A curious occurrence in Python For some reason in Python 2.7 expressions of the form tuple > list return True, but tuple < list and tuple == list return False. Why is that? This observation is not original to me by any means. A: tuple and list are not the same type. Python does something kind of surprising when...
A curious occurrence in Python
For some reason in Python 2.7 expressions of the form tuple > list return True, but tuple < list and tuple == list return False. Why is that? This observation is not original to me by any means.
[ "tuple and list are not the same type. Python does something kind of surprising when comparing values that are not of the same type, and which don't define comparators that work across these types. it compares the dictionary order of the names of the classes:\n>>> class Coffee(object):\n... pass\n... \n>>> cl...
[ 6, 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007985696_python.txt
Q: Wxpython - TextCtrl questions/weird copy "bug" (?) I have a weird problem. I can only copy the text once. If I press clear and type again the text disappears and I have to restart it. Where have I messed up? Now the questions: 1) Can I bind the clear function to the "Encrypt/Decrypt" so that each time I want to ty...
Wxpython - TextCtrl questions/weird copy "bug" (?)
I have a weird problem. I can only copy the text once. If I press clear and type again the text disappears and I have to restart it. Where have I messed up? Now the questions: 1) Can I bind the clear function to the "Encrypt/Decrypt" so that each time I want to type again it clears automatically? 2)How can I copy the ...
[ "Every time you push the button (method option1) you create a new overlapping TextCtrl. You should have created in the constructor and just change the text in the method.\n1) Just call self.output.Clear() at the beginning of the option1 method.\n2) \nclipdata = wx.TextDataObject()\nclipdata.SetText(\"Text here\")\n...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007985667_python_wxpython.txt
Q: How to detect memory limit of os.system I'm currently setting up and running a number of commands with os.fork and os.system commands. I set the time and memory limits through resource.setrlimit, and that seems to be working fine. However, each program has it's own way of crashing because of a memory cap -- a pyth...
How to detect memory limit of os.system
I'm currently setting up and running a number of commands with os.fork and os.system commands. I set the time and memory limits through resource.setrlimit, and that seems to be working fine. However, each program has it's own way of crashing because of a memory cap -- a python program throws a MemoryError, a c++ progra...
[ "See http://blog.tsul.net/2008/04/ossystem-and-its-return-value.html\nOn windows it seems that system() and wait() both always return 0.\nOn unix or mac, system() will return \"a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and wh...
[ 0, 0 ]
[]
[]
[ "memory_management", "python" ]
stackoverflow_0007986036_memory_management_python.txt
Q: Why does this twisted server interact wrongly with a process? The server is at https://github.com/EmeraldHaze/Socketd/blob/master/Serv.py ; the process is at https://github.com/EmeraldHaze/QFTSOM/blob/master/main.py A client too test this is at http://www.kongregate.com/games/EmeraldHaze/this-is-why-we-have-maps ...
Why does this twisted server interact wrongly with a process?
The server is at https://github.com/EmeraldHaze/Socketd/blob/master/Serv.py ; the process is at https://github.com/EmeraldHaze/QFTSOM/blob/master/main.py A client too test this is at http://www.kongregate.com/games/EmeraldHaze/this-is-why-we-have-maps ; port forwarding and whatnot is set up correctly. The point is tha...
[ "Uh, I solved this. It was becouse sys.stdin.readline() stops blocking when it gets a \\n, but either twisted or the client strip them off, meaning it will block indefinitly despite getting input.\n" ]
[ 1 ]
[]
[]
[ "ipc", "networking", "python", "sockets", "twisted" ]
stackoverflow_0007961884_ipc_networking_python_sockets_twisted.txt
Q: Printing a histogram I have a list of integer percentages which I need to print using the following pattern: The index of a value, a tab (8 spaces), a '*' printed for each percentage point also if the value for an index is 0, print 'less than 1 percent' I have tried this code: for b in new_tally: if b > 0: ...
Printing a histogram
I have a list of integer percentages which I need to print using the following pattern: The index of a value, a tab (8 spaces), a '*' printed for each percentage point also if the value for an index is 0, print 'less than 1 percent' I have tried this code: for b in new_tally: if b > 0: print new_tally[b]...
[ "I think the code you wanted was:\n>>> new_tally = [5, 7, 8, 6, 4, 2]\n>>> for i, b in enumerate(new_tally, 1):\n print i, ':', b, '*' * b\n\n1 : 5 *****\n2 : 7 *******\n3 : 8 ********\n4 : 6 ******\n5 : 4 ****\n6 : 2 **\n\nThe cause of the original traceback is that list members are looked up using square b...
[ 5, 0, 0 ]
[]
[]
[ "histogram", "indexing", "list", "python", "traceback" ]
stackoverflow_0007985603_histogram_indexing_list_python_traceback.txt
Q: importing configuration from subfolders I am trying to tidy up my configuration file, and I wanted to split it into several files that can be edited based on the deployment need. So in my project directy I have a subdirectory called config containing a few specific configuration files My "main" configuration file...
importing configuration from subfolders
I am trying to tidy up my configuration file, and I wanted to split it into several files that can be edited based on the deployment need. So in my project directy I have a subdirectory called config containing a few specific configuration files My "main" configuration file (settings.py) is located in my project direc...
[ "You should be able to do\nfrom config.common import *\nfrom config.specific import *\n\nYou shouldn't have to mess with the Python path, either, as Django's manage.py script will add the its directory and its parent to the path.\n" ]
[ 1 ]
[]
[]
[ "configuration", "django", "python" ]
stackoverflow_0007984771_configuration_django_python.txt
Q: Show Explorer's properties dialog for a file in Windows Is there an easy way to show the properties dialog for a file in Windows using Python? I'm trying to show the same window that pops up when you right click a file in Explorer and choose Properties. A: The way to do this is to call the Windows ShellExecuteEx...
Show Explorer's properties dialog for a file in Windows
Is there an easy way to show the properties dialog for a file in Windows using Python? I'm trying to show the same window that pops up when you right click a file in Explorer and choose Properties.
[ "The way to do this is to call the Windows ShellExecuteEx() API passing the properties verb. There are various high-level Python wrappers of this but I have not succeeded in getting any of them to work with the properties verb. Instead I would use good old ctypes.\nimport time\nimport ctypes\nimport ctypes.wintypes...
[ 7 ]
[]
[]
[ "python", "winapi", "windows" ]
stackoverflow_0007985122_python_winapi_windows.txt
Q: python: how to override str.join? We have a subclass of str (call it MyStr), and I need to be able to control how str.join interacts with my subclass. At minimum, a join of all MyStr's should produce another MyStr, and joining of MyStr and "plain" str should throw a TypeError. Currently, this is what happens: (MyS...
python: how to override str.join?
We have a subclass of str (call it MyStr), and I need to be able to control how str.join interacts with my subclass. At minimum, a join of all MyStr's should produce another MyStr, and joining of MyStr and "plain" str should throw a TypeError. Currently, this is what happens: (MyStr subclasses unicode) >>> m = MyStr(':...
[ "Couldn't your class just override join:\nclass MyStr(unicode):\n def join(self, strs):\n # your code here\n\nThis will at least cover the case of MyStr(...).join(...)\nAfter @bukzor's comment, I looked up how this works, and it looks like join is a C function that always returns a unicode object when cal...
[ 5, 0 ]
[]
[]
[ "python", "string", "subclass" ]
stackoverflow_0007984923_python_string_subclass.txt
Q: How do I turn this unicode into a dict? Sorry, I completely neglected to mention that I'm using Python. Let me try this again. I'm using Python to consume a web service that returns the following JSON: { "results" : [ { "paramName" : "output", "dataType" : "GPString", "value" : "{'city': 'F...
How do I turn this unicode into a dict?
Sorry, I completely neglected to mention that I'm using Python. Let me try this again. I'm using Python to consume a web service that returns the following JSON: { "results" : [ { "paramName" : "output", "dataType" : "GPString", "value" : "{'city': 'Falls Church', 'isRuralArea': False, 'zip': '2...
[ "Since your results object looks like a string/unicode version of a dict, you need to eval it. A safe way of doing this (as of Python 2.6) would be to use the ast.literal_eval function:\nresults = ast.literal_eval(responseAsJson['results'][0]['value'])\n\n", "This is not nearly a complete answer, since it's hard ...
[ 2, 0 ]
[]
[]
[ "json", "python", "unicode" ]
stackoverflow_0007985561_json_python_unicode.txt
Q: Sending multiple fields with AJAX I'm trying to figure out how to send multiple fields with AJAX. Would I use a GET or POST? I'm using Python Server Pages. I want my fields to update based on what option is selected in a select box - as far as I know I've gotten that to work so far, I'm just wondering how to send ...
Sending multiple fields with AJAX
I'm trying to figure out how to send multiple fields with AJAX. Would I use a GET or POST? I'm using Python Server Pages. I want my fields to update based on what option is selected in a select box - as far as I know I've gotten that to work so far, I'm just wondering how to send multiple discrete pieces of data via XM...
[ "While I'm not familiar with Python, I'd bet that there is a way to serialize your data to JSON to return to the client.\n{\"fname\" : \"Bob\", \"lname\" : \"Johnson\", \"email\" : \"email.@email.com\" ... }\n\nOn the client side, you'd then be able to traverse the data like you would any other javascript object:\n...
[ 1, 1 ]
[]
[]
[ "ajax", "javascript", "python" ]
stackoverflow_0007986934_ajax_javascript_python.txt
Q: Lookup admin change url for arbitrary Django model How do you lookup the admin change url for an arbitrary model? If I know the model, I can get the url by doing something like: >>> print urlresolvers.reverse('admin:myapp_mymodel_change', args=(obj.id,)) /admin/myapp/mymodel/123/ I have a generic foreign key on a...
Lookup admin change url for arbitrary Django model
How do you lookup the admin change url for an arbitrary model? If I know the model, I can get the url by doing something like: >>> print urlresolvers.reverse('admin:myapp_mymodel_change', args=(obj.id,)) /admin/myapp/mymodel/123/ I have a generic foreign key on a model, and I'd like to provide a link in admin to the o...
[ "Once you have the object, you can access its app label and name on its _meta class, then construct the name of the admin change url dynamically.\napp_label = obj._meta.app_label\nmodel = obj._meta.module_name\n\nreverse('admin:%s_%s_change' % (app_label, model), args=(obj.id,))\n\n" ]
[ 5 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0007986417_django_django_admin_python.txt
Q: PHP in python through bash As I am messing around with Python, I wanted to write an application that would have its own web server. I am currently using a written code from this website for http server: Python Web Server and this is the direct link of the script This script can handle html but I wanted to add php ...
PHP in python through bash
As I am messing around with Python, I wanted to write an application that would have its own web server. I am currently using a written code from this website for http server: Python Web Server and this is the direct link of the script This script can handle html but I wanted to add php to it too. Since I know that in ...
[ "You can use getoutput from the commands package for this simple case.\nfrom commands import getoutput\n\nresponse = getoutput('php myscript.php')\n\n", "You should eschew the use of os.system() in favor of the more modern subprocess module.\nYou might especially look at popen.communicate().\n" ]
[ 3, 2 ]
[]
[]
[ "bash", "php", "python" ]
stackoverflow_0007987295_bash_php_python.txt
Q: How to set relative position with wxpython? i have a wxpython listbox and its height set to -1, which would mean that it would automatically set to the height of the window. Is there a way to leave a 200px at the end of the window? So basicilly i guess what i am looking for is (window_height - 200), to leave a 200...
How to set relative position with wxpython?
i have a wxpython listbox and its height set to -1, which would mean that it would automatically set to the height of the window. Is there a way to leave a 200px at the end of the window? So basicilly i guess what i am looking for is (window_height - 200), to leave a 200 space. -1 would go the full window height. Thank...
[ "Put it in a sizer: mysizer.Add(myListBox, 0, wx.BOTTOM, 200)\nEDIT: Or you could use wx.GetDisplaySize() to get the width and height of the window, subtract 200 from the height and use that to set the size of the listbox.\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007987269_python_wxpython.txt
Q: Matplotlib: how to set the current figure? This is hopefully a simple question but I can't figure it out at the moment. I want to use matplotlib to show 2 figures and then use them interactively. I create the figures with: import matplotlib import pylab as pl f1 = pl.figure() f2 = pl.figure() and can use the MAT...
Matplotlib: how to set the current figure?
This is hopefully a simple question but I can't figure it out at the moment. I want to use matplotlib to show 2 figures and then use them interactively. I create the figures with: import matplotlib import pylab as pl f1 = pl.figure() f2 = pl.figure() and can use the MATLAB-like pyplot interface to plot and draw in bo...
[ "You can simply set figure f1 as the new current figure with:\npl.figure(f1.number)\n\nAnother option is to give names (or numbers) to figures, which might help make the code easier to read:\npl.figure(\"Share values\")\n# ... some plots ...\npl.figure(\"Profits\")\n# ... some plots ...\n\npl.figure(\"Share values\...
[ 109, 18 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007986567_matplotlib_python.txt
Q: ValueError: invalid literal for float() in Python To all: I have curious if someone can help me understand the error: ValueError: invalid literal for float(). I am getting this when I am passing a text file to a list then trying to convert this list to float values. a = open("input.txt","r") lines = a.readlines()...
ValueError: invalid literal for float() in Python
To all: I have curious if someone can help me understand the error: ValueError: invalid literal for float(). I am getting this when I am passing a text file to a list then trying to convert this list to float values. a = open("input.txt","r") lines = a.readlines() b = map(float, lines) What is odd, at least to me is ...
[ "You don't need readlines in this case -- it's a waste of time and memory.\nIf you want a list of lists of floats:\nb = [[float(v) for v in line.rstrip('\\n').split('\\t')] for line in a]\n\nor just one big list of floats:\nb = [float(v) for line in a for v in line.rstrip('\\n').split('\\t')]\n\n", "a.readlines()...
[ 7, 2, 2 ]
[]
[]
[ "floating_point", "iterable", "literals", "python" ]
stackoverflow_0007986459_floating_point_iterable_literals_python.txt
Q: How does the GUI testing tool PyUseCase compare to Dogtail? How does the GUI testing tool PyUseCase renamed to StoryText. compare to Dogtail? I want to hear from people who have hopefully experience in using both. Interested in: Maintainabilty of the testing code How well they work against real GUI's? A: Firstl...
How does the GUI testing tool PyUseCase compare to Dogtail?
How does the GUI testing tool PyUseCase renamed to StoryText. compare to Dogtail? I want to hear from people who have hopefully experience in using both. Interested in: Maintainabilty of the testing code How well they work against real GUI's?
[ "Firstly: I'm the author of PyUseCase and I haven't done more than play around with Dogtail...\nThe tools are different in a number of respects. \n\nDogtail works via the accessibility interface under Gnome on Linux, while PyUseCase operates via GUI toolkits (PyGTK, Tkinter, SWT/Eclipse in the current release, plus...
[ 8 ]
[]
[]
[ "automation", "compare", "python", "testing", "user_interface" ]
stackoverflow_0007975211_automation_compare_python_testing_user_interface.txt
Q: Replacement of an ampersand in xml document after encodings/decodings How do i replace a amphersand with the html sign & in a xml document? normally it works simply with a = u"TORE & Co & KG" i = a.replace('&','&amp;') print i Here it doesn't work:i get my xml structure out of an email and process it like this...
Replacement of an ampersand in xml document after encodings/decodings
How do i replace a amphersand with the html sign & in a xml document? normally it works simply with a = u"TORE & Co & KG" i = a.replace('&','&amp;') print i Here it doesn't work:i get my xml structure out of an email and process it like this: saver=StringIO(u"") # Edit a=str(msg) i= a.decode('quopri').decode('utf-8...
[ "may be change \nsavercontent.replace('&','&amp;')\n\nto \nsavercontent = savercontent.replace('&','&amp;')\n\n", "You could try:\na = str(msg)\ni = a.decode('quopri').decode('utf-8').replace('&', '&amp;')\nsaver.write(i)\nsavercontent = saver.getvalue()\n\nOr try:\ni = a.decode('quopri').replace('&', '&amp;').de...
[ 3, 3 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0007987645_python_replace.txt
Q: Python script freezes infinitely during a socket connection I have a simple python script that updates that statuses of justin.tv streams in my database. It's a Django based web application. This script worked perfectly before I moved it to my production server, but now it has issues with timing out or freezing. I...
Python script freezes infinitely during a socket connection
I have a simple python script that updates that statuses of justin.tv streams in my database. It's a Django based web application. This script worked perfectly before I moved it to my production server, but now it has issues with timing out or freezing. I've solved the time out problem by adding try/except blocks and m...
[ "Down in JtvClient.py it uses httplib to handle the connection. Have you tried changing this to use httplib2 instead?\nOther than that stab in the dark, I would add a lot of logging statements to this code in order to track what actually happens and where it gets stuck. Then I would make sure that the point where i...
[ 0, 0, 0 ]
[]
[]
[ "django", "python", "sockets" ]
stackoverflow_0007729427_django_python_sockets.txt
Q: strange python regex behavior - maybe connected to unicode or sqlalchemy I'm trying to search for a pattern in sqlalchemy results (actually filter by a 'like' or 'op'('regexp')(pattern) which I believe is implanted with regex somewhere) - the string and the search string are both in hebrew, and presumably (maybe I...
strange python regex behavior - maybe connected to unicode or sqlalchemy
I'm trying to search for a pattern in sqlalchemy results (actually filter by a 'like' or 'op'('regexp')(pattern) which I believe is implanted with regex somewhere) - the string and the search string are both in hebrew, and presumably (maybe I'm wrong-)-unicode where r = u'לבן' and c = u'לבן, ורוד, ' when I do re.sea...
[ "c = f[0].color\n\nis not returning a Unicode string (or its repr() would show a u'...' kind of string), but a UTF-8 encoded string.\nTry \nc = f[0].color.decode(\"utf-8\")\n\nwhich results in\nu'\\u05dc\\u05d1\\u05df,\\u05d5\\u05e8\\u05d5\\u05d3,'\n\nor\nu'לבן,ורוד,'\n\nif your console can display Hebrew character...
[ 3, 2 ]
[]
[]
[ "python", "regex", "sqlalchemy" ]
stackoverflow_0007987981_python_regex_sqlalchemy.txt
Q: Make qt4 designer under linux to use python3 for handling custom widgets plugins I use this script to start qt designer with my custom widgets (in Python 3) visible: #!/usr/bin/env python3 import os, sys, subprocess curDir = os.path.dirname(os.path.abspath(__file__)) params = list(sys.argv) # copy list params[0]...
Make qt4 designer under linux to use python3 for handling custom widgets plugins
I use this script to start qt designer with my custom widgets (in Python 3) visible: #!/usr/bin/env python3 import os, sys, subprocess curDir = os.path.dirname(os.path.abspath(__file__)) params = list(sys.argv) # copy list params[0] = 'designer' # "designer-qt4" on Linux widgetsDir = os.path.join(curDir, 'wic', 'wid...
[ "It looks like PyQt does not allow for side-by-side installation of the designer plugin that handles custom widgets (libpythonplugin.so). So there will normally be a single plugin linked against either python2, or python3, but not both.\nIt would appear that Kubuntu currently installs the python2 version of the plu...
[ 2 ]
[]
[]
[ "plugins", "pyqt", "pyqt4", "python", "qt_designer" ]
stackoverflow_0007986492_plugins_pyqt_pyqt4_python_qt_designer.txt
Q: Compare two integers for similarity Example: number1 = 54378 number2 = 54379 if number1 (is similar to) number2: print (number1 + " " + number2) input("what to do") I would like to compare between these two numbers, and let the program notify me when this kind of (between number1 and number2 ) similarity h...
Compare two integers for similarity
Example: number1 = 54378 number2 = 54379 if number1 (is similar to) number2: print (number1 + " " + number2) input("what to do") I would like to compare between these two numbers, and let the program notify me when this kind of (between number1 and number2 ) similarity happens. I would like the solution to be fl...
[ "You can use difflib for this:\n>>> from difflib import SequenceMatcher\n>>> number1 = 54378\n>>> number2 = 54379\n>>> SequenceMatcher(None, str(number1), str(number2)).ratio()\n0.80000000000000004\n\nAfter creating a SequenceMatcher object with string representations of their numbers, use ratio() (or quick_ratio()...
[ 4, 0 ]
[]
[]
[ "comparison", "python", "similarity" ]
stackoverflow_0007988322_comparison_python_similarity.txt
Q: Using %r, prevent 'this' Is there any way to avoid the single-quotes around a % string? I am trying to do this: playCmd = """osascript -e 'tell application "iTunes" to play track %r'""" % theSong that results in: ...play track 'theSong' not: ...play track theSong like I want. I would just use playCmd.relpace, bu...
Using %r, prevent 'this'
Is there any way to avoid the single-quotes around a % string? I am trying to do this: playCmd = """osascript -e 'tell application "iTunes" to play track %r'""" % theSong that results in: ...play track 'theSong' not: ...play track theSong like I want. I would just use playCmd.relpace, but because of the single-qoutes...
[ "Is there a reason why %s is inappropriate? Because replacing %r with %s is the first thing I'd try.\n", "Then you don't want %r; use %s, it will place the string in the output verbatim, without any extra quotes.\n\nwhat's really happening is that %s calls str(value) and %r calls repr(value). \n" ]
[ 5, 3 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007988607_python_string.txt
Q: Acess the dictionary being created inside dictionary comprehension I have a dictionary of numbers to lists of numbers like: a = { 1: [2,3,4] , 2: [1,4] } i want to create a new dictionary with comprehension based on it where each element from each list would be linked to the key to that list. That would be somet...
Acess the dictionary being created inside dictionary comprehension
I have a dictionary of numbers to lists of numbers like: a = { 1: [2,3,4] , 2: [1,4] } i want to create a new dictionary with comprehension based on it where each element from each list would be linked to the key to that list. That would be something like: b = { element : [key] for key in a.keys() for element in a[k...
[ "It's easy to build your dictionary using defaultdict and two loops.\nfrom collections import defaultdict\na = { 1: [2,3,4] , 2: [1,4] }\nb = defaultdict(list)\nfor key, value in a.iteritems():\n for elem in value:\n b[elem].append(key)\n\n", "im assuming this is for some form of mapping: \nfrom iterto...
[ 3, 2, 2 ]
[]
[]
[ "dictionary", "list_comprehension", "python" ]
stackoverflow_0007988399_dictionary_list_comprehension_python.txt
Q: What would be the most efficient/clean way to deeply sort a multidimensional list in Python? Example: From this list: list = [[10, 9, 1], [2, 1, 1,], [4, 11, 16]] I'd like to have: print list [[1, 1, 1], [2, 4, 9], [10, 11, 16]] Is it possible with the list.sort() function or do I have to write a custom loop ?...
What would be the most efficient/clean way to deeply sort a multidimensional list in Python?
Example: From this list: list = [[10, 9, 1], [2, 1, 1,], [4, 11, 16]] I'd like to have: print list [[1, 1, 1], [2, 4, 9], [10, 11, 16]] Is it possible with the list.sort() function or do I have to write a custom loop ?
[ "Here's an example of flattening, sorting, then rebuilding the nested lists, as @Inerdia suggested in the comments above.\nI've tried to use generators and iterators where possible, but I'm sure there are cleverer, more efficient ways of getting the result!\nfrom itertools import izip\n\nl = [[10, 9, 1], [2, 1, 1,]...
[ 1, 0 ]
[]
[]
[ "arrays", "list", "multidimensional_array", "python", "sorting" ]
stackoverflow_0007988310_arrays_list_multidimensional_array_python_sorting.txt
Q: MCMC Image Processing Example in Matlab or Python I am looking for a sample code that utilizes Markov Chain Monte Carlo method for image processing, preferably for segmentation, in Matlab or Python. Except for the MRP ICM.m example, I was not able to find any. Any pointers? A: From Mumford's Pattern Theory boo...
MCMC Image Processing Example in Matlab or Python
I am looking for a sample code that utilizes Markov Chain Monte Carlo method for image processing, preferably for segmentation, in Matlab or Python. Except for the MRP ICM.m example, I was not able to find any. Any pointers?
[ "From Mumford's Pattern Theory book samples\nhttp://www.dam.brown.edu/ptg/MDbook/\nthis chapter\nhttp://www.dam.brown.edu/ptg/MDbook/Chapter4.html\nhas Ising model and MCMC (Gibbs sampling). \nAlso\nhttp://elec.otago.ac.nz/w/images/1/19/ELEC404_Inverse_Problems.pdf\nI found that searching for \"imread\", \"MCMC\", ...
[ 1, 0 ]
[]
[]
[ "image_processing", "matlab", "python" ]
stackoverflow_0007984188_image_processing_matlab_python.txt
Q: How to scale/zoom a QTextEdit area from a toolbar button click and/or ctrl + mouse wheel Is it possible to scale (or "zoom") a QTextEdit area? I believe I read that placing QTextEdit inside QLayout can allow for scaling of the QTextEdit area, though did not find how to implement it. Couple of options... CTRL + R...
How to scale/zoom a QTextEdit area from a toolbar button click and/or ctrl + mouse wheel
Is it possible to scale (or "zoom") a QTextEdit area? I believe I read that placing QTextEdit inside QLayout can allow for scaling of the QTextEdit area, though did not find how to implement it. Couple of options... CTRL + Roll of Mouse Wheel Running the code below, holding down the CTRL (control) key and rolling the...
[ "The two error messages can be expained as follows:\n\nThe QMainWidget automatically gets a layout, so the QFormLayout is redundant. If you want to add a layout, create a QWidget to be the central widget and make it the parent of the new layout. Other widgets can then be added to that new layout.\nThe parent of a Q...
[ 4 ]
[]
[]
[ "pyqt", "pyqt4", "pyside", "python" ]
stackoverflow_0007987881_pyqt_pyqt4_pyside_python.txt
Q: ipython debugger: full traceback on interactive pdb? I recently switched from ipython0.10 to ipython0.11. In ipython0.11, I only see a small snippet of the full traceback when the python debugger engages (i.e. using %pdb), whereas in ipython0.10 I'd see the full traceback. As far as I can tell, the full tracebac...
ipython debugger: full traceback on interactive pdb?
I recently switched from ipython0.10 to ipython0.11. In ipython0.11, I only see a small snippet of the full traceback when the python debugger engages (i.e. using %pdb), whereas in ipython0.10 I'd see the full traceback. As far as I can tell, the full traceback is not directly accessible from the pdb command line - y...
[ "\nis there any way to have ipython just show the Exception that was\n caught, rather than showing where in the code it was caught?\n\nYou could use sys.excepthook:\nimport sys\n\ndef exc_hook(type, value, traceback):\n print type\n\nsys.excepthook = exc_hook\n\nFrom the sys module documentation:\n\nsys.excepth...
[ 6 ]
[]
[]
[ "ipdb", "ipython", "pdb", "python" ]
stackoverflow_0007988864_ipdb_ipython_pdb_python.txt
Q: Sqlite query formulation targeting row content I'm trying to formulate the right query to select records that each have a category: drop table if exists entries; create table entries ( id integer primary key autoincrement, title string not null, text string not null, pub_date integer, category string not null); I...
Sqlite query formulation targeting row content
I'm trying to formulate the right query to select records that each have a category: drop table if exists entries; create table entries ( id integer primary key autoincrement, title string not null, text string not null, pub_date integer, category string not null); I read the sqlite documentation and I still can't fig...
[ "There are a number of problems with your code but the most basic one is that your final SQL statement does not place quotation marks around the value of category_name as required for strings in SQL (and most other languages).\nWhat you are sending to SQLite is:\nselect id,title, text,pub_date,category from entries...
[ 1, 0 ]
[]
[]
[ "flask", "python", "sqlite" ]
stackoverflow_0007988780_flask_python_sqlite.txt
Q: Get headers sent in urllib2 http request I know how to get the headers RECEIVED resp = urllib2.urlopen('http://www.google.com') print resp.info() But how do you access the headers SENT to 'http://www.google.com' ? I usually use wireshark to analyze and see what is actually being sent, but I'd like to have access ...
Get headers sent in urllib2 http request
I know how to get the headers RECEIVED resp = urllib2.urlopen('http://www.google.com') print resp.info() But how do you access the headers SENT to 'http://www.google.com' ? I usually use wireshark to analyze and see what is actually being sent, but I'd like to have access to this information in my script.
[ "import httplib\nimport urllib2\n\nclass CustomHTTPConnection(httplib.HTTPConnection):\n def request(self, method, url, body=None, headers={}):\n print headers\n self._send_request(method, url, body, headers)\n\nclass CustomHTTPHandler(urllib2.AbstractHTTPHandler):\n def http_open(self, req):\n ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006085709_python.txt
Q: matplotlib: how can I convert a XYZ scatter to a pixel image? I'm looking for some way in to convert a scatter plot (X vs Y, color normalized by Z) into a 2D "pixel" image. I.e. how can I plot a pixelized image where the pixels are colored according to a third variable? In my case, I have a list of galaxies, each...
matplotlib: how can I convert a XYZ scatter to a pixel image?
I'm looking for some way in to convert a scatter plot (X vs Y, color normalized by Z) into a 2D "pixel" image. I.e. how can I plot a pixelized image where the pixels are colored according to a third variable? In my case, I have a list of galaxies, each a with sky coordinate (X,Y) and a distance (Z). I want to make a p...
[ "Okay - there are two ways that you can do this. One would be for you to have a discreet number of bins for the distances (like d < 10pc, 10pc < d < 20pc, d> 20pc). This is relatively easy, all you need to do are a few loops - here is an example with 3:\nraclose = []\nramid = []\nrafar = []\ndecdlose = []\ndecmid...
[ 2 ]
[]
[]
[ "colors", "image", "matplotlib", "python", "scatter" ]
stackoverflow_0007988473_colors_image_matplotlib_python_scatter.txt
Q: How to understand this code, to split an array in Python? I'm a bit confused about a line in Python: We use Python and a custom function to split a line: we want what is between quotes to be a single entry in the array. The line is, for example: "La Jolla Bank, FSB",La Jolla,CA,32423,19-Feb-10,24-Feb-10 So "La J...
How to understand this code, to split an array in Python?
I'm a bit confused about a line in Python: We use Python and a custom function to split a line: we want what is between quotes to be a single entry in the array. The line is, for example: "La Jolla Bank, FSB",La Jolla,CA,32423,19-Feb-10,24-Feb-10 So "La Jolla Bank, FSB" should be a single entry in the array. And I'm ...
[ "You're viewing it as though both if char == '\"' and elif char == ',' and not quote were run.\nHowever the if statement explicitly makes it so that only one will run.\nEither, quote will be inverted OR the current value will get cut.\nIn the case where the current char is \", then the logic will be called to inver...
[ 3, 1, 1, 1, 1, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0007989161_python_string.txt
Q: checking for disconnected clients in a list? in python Okay so this is what I'm trying to do in my python socket server. I'm trying to have a way for my server to send data. But if it finds a disconnected client in the list of address's that is be used. To remove it from the list. Also, I'm using UDP for sending d...
checking for disconnected clients in a list? in python
Okay so this is what I'm trying to do in my python socket server. I'm trying to have a way for my server to send data. But if it finds a disconnected client in the list of address's that is be used. To remove it from the list. Also, I'm using UDP for sending data. As this is for a gaming server. Something sorta like: ...
[ "You can use enumerate to give you the index along with the item. But remember that lists are mutable; you need to be careful modifying the list you are iterating over.\n" ]
[ 0 ]
[]
[]
[ "blender", "python", "sockets", "socketserver", "udp" ]
stackoverflow_0007989117_blender_python_sockets_socketserver_udp.txt
Q: Django Internationalization I have a similar issue as found here Why doesn't Django produce locale files from template files in another directory? However I don't understand the solution. My structure: Project App1 locale templates App2 locale templates templates somefilethat...
Django Internationalization
I have a similar issue as found here Why doesn't Django produce locale files from template files in another directory? However I don't understand the solution. My structure: Project App1 locale templates App2 locale templates templates somefilethatneedstranslation.html Now when I...
[ "The full deprecation message (which is also explained in the translation docs) is:\n\nTranslations in the project directory aren't supported anymore. LOCALE_PATHS setting instead.\n\nThis message is perhaps a bit unclear. While automatic discovery of translations in the project directory is deprecated, the use of ...
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007965893_django_python.txt
Q: Comparing Values in List in For Loop; Python Working in Python 2.7. I have two different lists, A and B (simplified to make explanations more clear). A = [1, 2, 4, 3, 5] B = [2, 0, 3, 2, 1] I would like to be able to compare the positional values of each list ex- A[1] v B[1]- and total up the instances in which A...
Comparing Values in List in For Loop; Python
Working in Python 2.7. I have two different lists, A and B (simplified to make explanations more clear). A = [1, 2, 4, 3, 5] B = [2, 0, 3, 2, 1] I would like to be able to compare the positional values of each list ex- A[1] v B[1]- and total up the instances in which A is larger (A "wins"), the instances when the two ...
[ "Sounds like you want zip:\ndef compare(A,B):\n Awins = 0\n Aties = 0\n Alosses = 0\n for i in range(0, whatever):\n random.shuffle(listA)\n random.shuffle(listB)\n for a,b in zip(A,B):\n if a > b:\n Awins += 1\n elif a == b:\n Ati...
[ 4, 2, 2, 1, 0 ]
[]
[]
[ "if_statement", "list", "loops", "python", "random" ]
stackoverflow_0007989255_if_statement_list_loops_python_random.txt
Q: Use libraries installed by R for other programs? When R installs a package that contains other programs/libraries (e.g., hdf5, SQLite), can I use those in other programs? For instance, I have hdf5.so installed in /Library/Frameworks/R.framework/Versions/2.13/Resources/library/hdf5/libs/x86_64/ - can I use this ins...
Use libraries installed by R for other programs?
When R installs a package that contains other programs/libraries (e.g., hdf5, SQLite), can I use those in other programs? For instance, I have hdf5.so installed in /Library/Frameworks/R.framework/Versions/2.13/Resources/library/hdf5/libs/x86_64/ - can I use this instead of installing hdf5 for use by Python (h5py, etc.?...
[ "As a general rules, no. You also may be misreading this: hdf5.so is the binding from R to the hdf5 libraries. E.g. when (on a Linux box) I ask the linker what a given R library links to, I get something like\nedd@max:~$ ldd /usr/lib/R/site-library/XML/libs/XML.so \n linux-vdso.so.1 => (0x00007fffcbf75000...
[ 9 ]
[]
[]
[ "python", "r", "unix" ]
stackoverflow_0007989048_python_r_unix.txt
Q: Which is a better extension language for speed optimization for python c or c++ Would it be better to use c or c++ for handling computationally intensive tasks in a python program, where speed matters above all. Is there much of a difference between the two ? Which is more cleaner? A: Well, C++ is supposed to...
Which is a better extension language for speed optimization for python c or c++
Would it be better to use c or c++ for handling computationally intensive tasks in a python program, where speed matters above all. Is there much of a difference between the two ? Which is more cleaner?
[ "Well, C++ is supposed to be a superset of C. So you can write C programs in C++ and get the same amount of speed. It really depends on what you need to accomplish.\nIf you don't need any of C++'s features (OOP, templates, exceptions, etc), then C should be fine. \nOf course, if you're already comfortable writing i...
[ 1, 0, 0, 0 ]
[]
[]
[ "c", "c++", "python" ]
stackoverflow_0007989036_c_c++_python.txt
Q: custom pyramid_formalchemy forms I'm having problems creating custom forms in pyramid_formalchemy. I suspect there is a bug in the package and wanted to confirm I'm not missing anything. My setup looks like this: def includeme(config): config.include('pyramid_formalchemy') # Adding the jquery libraries ...
custom pyramid_formalchemy forms
I'm having problems creating custom forms in pyramid_formalchemy. I suspect there is a bug in the package and wanted to confirm I'm not missing anything. My setup looks like this: def includeme(config): config.include('pyramid_formalchemy') # Adding the jquery libraries config.include('fa.jquery') # A...
[ "pyramid_formalchemy makes certain, mostly undocumented assumptions, about how you setup your forms file. Here are the gotchas I hit and worked around...\n\nIf you have a model User for example, then you will need to have a FieldSet called UserFieldSet. \nUserFieldSet must be an instance and not a class.\nBe care...
[ 5 ]
[]
[]
[ "formalchemy", "pyramid", "python" ]
stackoverflow_0007936685_formalchemy_pyramid_python.txt
Q: Opening a process with Popen and getting the PID I'm working on a nifty little function: def startProcess(name, path): """ Starts a process in the background and writes a PID file returns integer: pid """ # Check if the process is already running status, pid = processStatus(name) if ...
Opening a process with Popen and getting the PID
I'm working on a nifty little function: def startProcess(name, path): """ Starts a process in the background and writes a PID file returns integer: pid """ # Check if the process is already running status, pid = processStatus(name) if status == RUNNING: raise AlreadyStartedError(p...
[ "From the documentation at http://docs.python.org/library/subprocess.html:\n\nPopen.pid The process ID of the child process.\nNote that if you set the shell argument to True, this is the process\nID of the spawned shell.\n\nIf shell is false, it should behave as you expect, I think.\nIf you were relying on shell be...
[ 54 ]
[]
[]
[ "popen", "python", "subprocess" ]
stackoverflow_0007989922_popen_python_subprocess.txt
Q: Numpy: need a hand in understanding what happens with the "in" operator I would appreciate if somebody could help me with this (and explaining what's going on). This works: >>> from numpy import array >>> a = array((2, 1)) >>> b = array((3, 3)) >>> l = [a, b] >>> a in l True But this does not: >>> c = array((2, 1...
Numpy: need a hand in understanding what happens with the "in" operator
I would appreciate if somebody could help me with this (and explaining what's going on). This works: >>> from numpy import array >>> a = array((2, 1)) >>> b = array((3, 3)) >>> l = [a, b] >>> a in l True But this does not: >>> c = array((2, 1)) >>> c in l Traceback (most recent call last): File "<stdin>", line 1, in...
[ "Python makes the choice that bool([False,True]) is True because (it says) any non-empy list has boolean value True.\nNumpy makes the choice that bool(np.array([False, True])) should raise a ValueError. Numpy was designed from the point of view that some users may want to know if any of the elements in the array ar...
[ 6 ]
[]
[]
[ "numpy", "python", "python_2.7" ]
stackoverflow_0007989676_numpy_python_python_2.7.txt
Q: Can I find the path to the python executable from inside python? Possible Duplicate: How to get current python interpreter path from inside a Python script? The title pretty much says it. I'd like to know which python executable is being used from inside python. Something like Python 2.7.2 (default, Nov 1 2011...
Can I find the path to the python executable from inside python?
Possible Duplicate: How to get current python interpreter path from inside a Python script? The title pretty much says it. I'd like to know which python executable is being used from inside python. Something like Python 2.7.2 (default, Nov 1 2011, 03:31:17) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits"...
[ "You can do this:\n>>> import sys\n>>> print sys.executable\n/usr/bin/python\n\nas described here: How to get the python.exe location programmatically?\n", "Why not just use the bash where command?\nAnyways, here is what you're looking for:\nimport sys\nsys.executable\n\n" ]
[ 12, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007990050_python.txt
Q: Error reading and writing csv files into python System info: Python 2.7.2 MAC OSX 10.7.2 Problem (+background): I have a large '.csv' file (~1 gig) which needs some minor editing. Every value in the 5th column needs to be 5 characters long (some are 4 characters long, and need a '0' placed in front of them). The ...
Error reading and writing csv files into python
System info: Python 2.7.2 MAC OSX 10.7.2 Problem (+background): I have a large '.csv' file (~1 gig) which needs some minor editing. Every value in the 5th column needs to be 5 characters long (some are 4 characters long, and need a '0' placed in front of them). The code (shown below) reports no errors when run, but st...
[ "Either close the output file after writing it, or write the output in a with context which will always close the file even if an error occurs:\nwith open('path + 'write_file.csv', 'wb') as f:\n writer = csv.writer(f)\n for line in r:\n ...\n\n", "Things to check:\n\nAre you examining this after your...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007987956_python.txt
Q: In python, how do you get it to input a keyboard press? When I push the print screen button on my keyboard, I would like to trigger an event, like this: if keyboard-print screen: print "5" A: Note that the tkinter solution does not work on Mac (at least it does not work on my Mac). I tested it with Python 3....
In python, how do you get it to input a keyboard press?
When I push the print screen button on my keyboard, I would like to trigger an event, like this: if keyboard-print screen: print "5"
[ "Note that the tkinter solution does not work on Mac (at least it does not work on my Mac). I tested it with Python 3.2.2 and Python 2.7.2. If the window is withdrawn, it will not get the focus and therefore it will not sense any of the key events.\n", "Tkinter has built-in keypress events.\nimport Tkinter as tk\...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005760620_python.txt
Q: Preventing a class from direct instantiation in Python I have a super class with a method that calls other methods that are only defined in its sub classes. That's why, when I create an instance of my super class and call its method, it cannot find the method and raises an error. Here is an example: class SuperCla...
Preventing a class from direct instantiation in Python
I have a super class with a method that calls other methods that are only defined in its sub classes. That's why, when I create an instance of my super class and call its method, it cannot find the method and raises an error. Here is an example: class SuperClass(object): def method_one(self): value = self.subcla...
[ "I would override __new__() in the base class and simply fail to instantiate at all if it's the base class.\nclass BaseClass: # Py3\n\n def __new__(cls, *args, **kwargs):\n if cls is BaseClass:\n raise TypeError(f\"only children of '{cls.__name__}' may be instantiated\")\n return obje...
[ 83, 29, 16, 11 ]
[]
[]
[ "class", "locking", "oop", "python", "superclass" ]
stackoverflow_0007989042_class_locking_oop_python_superclass.txt
Q: Finding unique points in numpy array What is a faster way of finding unique x,y points (removing duplicates) in a numpy array like: points = numpy.random.randint(0, 5, (10,2)) I thought of converting points to a complex numbers and then checking for unique, but that seems rather convoluted: b = numpy.unique(point...
Finding unique points in numpy array
What is a faster way of finding unique x,y points (removing duplicates) in a numpy array like: points = numpy.random.randint(0, 5, (10,2)) I thought of converting points to a complex numbers and then checking for unique, but that seems rather convoluted: b = numpy.unique(points[:,0] + 1j * points[:,1]) points = numpy....
[ "I would do it like this:\nnumpy.array(list(set(tuple(p) for p in points)))\nFor the fast solution in the most general case, maybe this recipe would interest you:\nhttp://code.activestate.com/recipes/52560-remove-duplicates-from-a-sequence/\n", "I think you have a very good idea here. Think about the underlying b...
[ 8, 7 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007989722_numpy_python.txt
Q: Pythonic way to append list of strings to an array I'm new to Python and come from a Java background. I'd like to know the most Pythonic way of writing this code: entry_list = [] for entry in feed.entry: entry_list.append(entry.title.text) Basically for each element in the feed, I'd like to append that eleme...
Pythonic way to append list of strings to an array
I'm new to Python and come from a Java background. I'd like to know the most Pythonic way of writing this code: entry_list = [] for entry in feed.entry: entry_list.append(entry.title.text) Basically for each element in the feed, I'd like to append that element's title to a list. I don't know if I should use a map...
[ "most pythonic code I can think of:\nentry_list = [entry.title.text for entry in feed.entry]\n\nThis is a list comprehension which will construct a new list out of the elements in feed.entry.title.text. \nTo append you will need to do:\nentry_list.extend([entry.title.text for entry in feed.entry])\n\nAs a side not...
[ 8, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007990235_python.txt
Q: Python - Mechanize : Why does it need CookieJar? In mechanize, we have : method : set_cookiejar() But, why do we need a cookie jar anyway, when we say that mechanize has automatic cookie handling ? Please help ! A: You don't need one -- if you don't specify one, Mechanize will just handle it. You might want to u...
Python - Mechanize : Why does it need CookieJar?
In mechanize, we have : method : set_cookiejar() But, why do we need a cookie jar anyway, when we say that mechanize has automatic cookie handling ? Please help !
[ "You don't need one -- if you don't specify one, Mechanize will just handle it. You might want to use cookies you have already stored in a jar, or save cookies in a jar for use with other scripts, so Mechanize lets you specify one.\n" ]
[ 3 ]
[]
[]
[ "browser", "mechanize", "python", "web_scraping" ]
stackoverflow_0007990321_browser_mechanize_python_web_scraping.txt
Q: Set range of allowed datatypes / type cast for values from file in python I am reading in a file line by line. Lines are delimited with "|". Since values are interpreted as string once they were read from the file I want to cast them to their correct representation (I now the datatype of each "column" value). Thus...
Set range of allowed datatypes / type cast for values from file in python
I am reading in a file line by line. Lines are delimited with "|". Since values are interpreted as string once they were read from the file I want to cast them to their correct representation (I now the datatype of each "column" value). Thus, I wrote a little "translate" method that looks like the following: def transl...
[ "Use a dictionary, e.g.\ndef translateType(t):\n return {\"INTEGER\": int, \"FLOAT\": float, \"STRING\": str}.get(t, None)\n\nOr, if performance is imperative (profile first), define the dict in the argument list so it doesn't need to be created each time the function is called:\ndef translateType(t, types={\"IN...
[ 2, 0 ]
[]
[]
[ "casting", "dynamic", "python", "types" ]
stackoverflow_0007990365_casting_dynamic_python_types.txt
Q: How does a permalink work? I have the following code in my models.py file and I'm wondering how it's used in the urls.py/rest of the django framework. What benefits does it give me? @models.permalink def get_absolute_url(self): return('catalog_category',(), {'category_slug':self.slug}) How do I us...
How does a permalink work?
I have the following code in my models.py file and I'm wondering how it's used in the urls.py/rest of the django framework. What benefits does it give me? @models.permalink def get_absolute_url(self): return('catalog_category',(), {'category_slug':self.slug}) How do I use this method?
[ "This can be used to return a url with your current object. If you have a model and url associated with your @models.permalink.\nAn example may be something like this\n{% for offer in offers %}\n{{offer.title}}\n{{offer.get_absolute_url}}\nIn the urls.py file look at your related_names there should be one in relate...
[ 2, 1 ]
[]
[]
[ "django", "permalinks", "python" ]
stackoverflow_0007990068_django_permalinks_python.txt
Q: Can I redirect all output to /dev/null from within python? I'm writing a Python script that'll fork a child process. The parent process should be able to write stuff like Started child at xxxxx, but the child process output should be redirected to /dev/null. How can I do that from within python? A: import sys ol...
Can I redirect all output to /dev/null from within python?
I'm writing a Python script that'll fork a child process. The parent process should be able to write stuff like Started child at xxxxx, but the child process output should be redirected to /dev/null. How can I do that from within python?
[ "import sys\nold_stdout, old_stderr = sys.stdout, sys.stderr\nsys.stdout = open('/dev/null', 'w')\nsys.stderr = open('/dev/null', 'w')\n\n" ]
[ 11 ]
[]
[]
[ "python" ]
stackoverflow_0007990414_python.txt
Q: python: How to decrement and update values for a field in delimited text I have a text file (bowtie alignment file) that looks like this: read_1 + 345995|PACid:16033981 599 AGTAGTAATCAGTCACCCGCAAGGTAGACAAGG qqqqqqqqqqqqqqqqqqqqq!!qqqqqqqqqq 0 read_2 + 949205|PACid:16054220 338 TACCAGCACTAATGCACCG...
python: How to decrement and update values for a field in delimited text
I have a text file (bowtie alignment file) that looks like this: read_1 + 345995|PACid:16033981 599 AGTAGTAATCAGTCACCCGCAAGGTAGACAAGG qqqqqqqqqqqqqqqqqqqqq!!qqqqqqqqqq 0 read_2 + 949205|PACid:16054220 338 TACCAGCACTAATGCACCGGATCCCATCAGATC qqqqqqqqqqqqqqqqqqqqqqqqqqqqqq!!q 0 31:A>T read_3 + 93...
[ "Use the csv module, informing it your field delimiter is a tab:\nfrom io import StringIO\n\nindata = StringIO(u\"\"\"read_1 + 345995|PACid:16033981 599 AGTAGTAATCAGTCACCCGCAAGGTAGACAAGG qqqqqqqqqqqqqqqqqqqqq!!qqqqqqqqqq 0\nread_2 + 949205|PACid:16054220 338 TACCAGCACTAATGCACCGGATCCCATCAGATC qqqqq...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007990471_python.txt
Q: Visual Editor for Django Templates? Is there a tool out there for visually building Django templates? Thanks A: I haven't tried it personally, but a co-worker uses the free ActiveState Komodo Edit to edit Django templates, and the page I linked claims support for Django template editing. There's also netbeans-dj...
Visual Editor for Django Templates?
Is there a tool out there for visually building Django templates? Thanks
[ "I haven't tried it personally, but a co-worker uses the free ActiveState Komodo Edit to edit Django templates, and the page I linked claims support for Django template editing.\nThere's also netbeans-django that is building a Django plugin for Netbeans, but no idea how complete or how well it works.\nI've read tha...
[ 6, 5, 2, 1, 1, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0000872065_django_django_templates_python.txt
Q: Calculating Correlation Coefficient with Numpy I have a list of values and a 1-d numpy array, and I would like to calculate the correlation coefficient using numpy.corrcoef(x,y,rowvar=0). I get the following error: Traceback (most recent call last): File "testLearner.py", line 25, in <module> corr = np.corrcoef(va...
Calculating Correlation Coefficient with Numpy
I have a list of values and a 1-d numpy array, and I would like to calculate the correlation coefficient using numpy.corrcoef(x,y,rowvar=0). I get the following error: Traceback (most recent call last): File "testLearner.py", line 25, in <module> corr = np.corrcoef(valuesToCompare,queryOutput,rowvar=0) File "/usr/local...
[ "I think you might have assumed that reshape modifies the value of the original array. It doesn't:\n>>> a = np.random.randn(5)\n>>> a.shape\n(5,)\n>>> b = a.reshape(5,1)\n>>> b.shape\n(5, 1)\n>>> a.shape\n(5,)\n\n\nnp.asarray treats a regular list as a 1d array, but your original numpy array that you said was 1d is...
[ 1 ]
[]
[]
[ "arrays", "list", "numpy", "python" ]
stackoverflow_0007989719_arrays_list_numpy_python.txt
Q: python logging.info does not print, logging.warn and logging.error does import logging if __name__ == "__main__": logging.info('info') logging.warn('warning') logging.error('error') Result: warning error Why does logging.info not report anything? A: Your log level is set so that 'info' won't pri...
python logging.info does not print, logging.warn and logging.error does
import logging if __name__ == "__main__": logging.info('info') logging.warn('warning') logging.error('error') Result: warning error Why does logging.info not report anything?
[ "Your log level is set so that 'info' won't print; by default it doesn't print anything less than WARNING. See Logger.setLevel.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0007990731_python.txt
Q: How do I define name 'feildNames1'? I've been googling and I cannot find a solution. Would someone please share a working example? import easygui #Multi Enter Box fieldNames1= ['Situation:(Example: Waiting for a friend who is late.)','Thoughts:(EXAMPLE: My friend Bob is always late!)','Emotions:(EXAMPLE: Mad & St...
How do I define name 'feildNames1'?
I've been googling and I cannot find a solution. Would someone please share a working example? import easygui #Multi Enter Box fieldNames1= ['Situation:(Example: Waiting for a friend who is late.)','Thoughts:(EXAMPLE: My friend Bob is always late!)','Emotions:(EXAMPLE: Mad & Stressed)','Behavior:(EXAMPLE: Arguing with...
[ "It's a spelling error.\nYou're setting the fieldNames1 variable, but calling repr() on feildNames1. Note the placement of the e and i\n" ]
[ 3 ]
[]
[]
[ "easygui", "nameerror", "python" ]
stackoverflow_0007990763_easygui_nameerror_python.txt
Q: What is the right way to organize a project with simple dependencies? While writing code, I often run into the problem of addressing trivial dependancies. For example, let's take the layout of a memoizer object I've recently written. My directory structure looks like this: memoizer/ memoizer.py tests.py stra...
What is the right way to organize a project with simple dependencies?
While writing code, I often run into the problem of addressing trivial dependancies. For example, let's take the layout of a memoizer object I've recently written. My directory structure looks like this: memoizer/ memoizer.py tests.py strategies/ __init__.py perfect.py mru.py queue.py README The ...
[ "I would suggest a variation of the second structure:\nmemoizer/\n memoizer.py\n tests.py\n strategies/\n __init__.py\n perfect.py\n mru/\n __init__.py <- This is what used to be mru.py\n queue.py\nREADME\n\nThen the user can just import memoizer.strategies.mru.\nThat's the quick and easy way ...
[ 3 ]
[]
[]
[ "file_structure", "python" ]
stackoverflow_0007990776_file_structure_python.txt
Q: How to get variable length placeholders in a Python call to SQLite3 Is there a way to use variable length placeholders in an SQL query? Right now with a 3-tuple, I write something like this: c.execute('SELECT * FROM table WHERE word IN (?, ?, ?)', tup) But what if the tup can be of differing lengths, perhaps a 4-...
How to get variable length placeholders in a Python call to SQLite3
Is there a way to use variable length placeholders in an SQL query? Right now with a 3-tuple, I write something like this: c.execute('SELECT * FROM table WHERE word IN (?, ?, ?)', tup) But what if the tup can be of differing lengths, perhaps a 4-tuple or 2-tuple? Is there a syntax for using placeholders in this situa...
[ "You'd have to do something like this (to use your example):\ntup = ... # some sequence/tuple of unknown length\nsql = 'SELECT * FROM table WHERE word IN (%s)' % ', '.join('?' for a in tup)\nc.execute(sql, tup)\n\nThis way you're dynamically creating the placeholder list and formatting the SQL string before the sql...
[ 13 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0007991183_python_sqlite.txt
Q: Line between current Python implementations and Compiled Languages My understanding C++ is compiled into machine code and executed. Python is compiled into bytecode This bytecode is then executed What does this execution step entail and how is it different for Cpython and PyPy? Where does the difference in perfor...
Line between current Python implementations and Compiled Languages
My understanding C++ is compiled into machine code and executed. Python is compiled into bytecode This bytecode is then executed What does this execution step entail and how is it different for Cpython and PyPy? Where does the difference in performance kick in? Where does the fact that Python is dynamically typed kick...
[ "C, C++, and other statically compiled languages are compiled into native machine code, which means the CPU of the computer can directly execute them. The code it compiles to is unintelligible binary data, but you can kind of imagine that a C code fragment like this:\nint x = 10;\nint y = x * 2;\n\nwill be compiled...
[ 8 ]
[]
[]
[ "c++", "compiler_construction", "cpython", "pypy", "python" ]
stackoverflow_0007990655_c++_compiler_construction_cpython_pypy_python.txt
Q: Blog Engine with text/html syntax and file-based input I am looking for a blog engine which has the following features: Should be able to accept posts in either pure text or HTML. I should be able to blog offline and then update the things online with a single command. This will most probably require git. The fi...
Blog Engine with text/html syntax and file-based input
I am looking for a blog engine which has the following features: Should be able to accept posts in either pure text or HTML. I should be able to blog offline and then update the things online with a single command. This will most probably require git. The files should be stored in "human-readable format" and I should...
[ "Try Blogofile.\n" ]
[ 1 ]
[]
[]
[ "blogs", "python" ]
stackoverflow_0007991735_blogs_python.txt
Q: Selenium Python sel.click("css=input.smthg")? I am writing a script in Python for Selenium but the action "sel.click" doesn't work when the selection is a CSS : def test_test_remote(self): sel = self.selenium sel.open("/fr") sel.click("id=flightFrom") sel.type("id=flightFrom", "Londres-Stansted") ...
Selenium Python sel.click("css=input.smthg")?
I am writing a script in Python for Selenium but the action "sel.click" doesn't work when the selection is a CSS : def test_test_remote(self): sel = self.selenium sel.open("/fr") sel.click("id=flightFrom") sel.type("id=flightFrom", "Londres-Stansted") sel.type("id=flightTo", "Dublin") sel.click(...
[ "This is most likely caused by behind-the-scenes Javascript code. Probably when you navigate the website with your browser, you can just click the element, and everything works as expected. Say that input.bookFlightButton actually handles the submit request on its mouseup handler for example: your click command cou...
[ 0 ]
[]
[]
[ "click", "css", "python", "selenium" ]
stackoverflow_0007991052_click_css_python_selenium.txt
Q: Replace multiple texts with their corresponding texts in XML using Python How can I replace Japanese texts between with their corresponding English texts? I have a hundreds of AliasName that I need to replace. Since I am new to python and XML, a step by step instruction would be greatly appreciated. Here is how ...
Replace multiple texts with their corresponding texts in XML using Python
How can I replace Japanese texts between with their corresponding English texts? I have a hundreds of AliasName that I need to replace. Since I am new to python and XML, a step by step instruction would be greatly appreciated. Here is how my xml file looks like: <Workspace> <Dataset> <DataElement> ...
[ "\nUse Unicode strings. Define source encoding at the top of the module.\nYou could use ElementTree instead of minidom. It has nicer API.\n\nExample\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport xml.etree.cElementTree as etree\n\nen2jp = {u\"State\": u\"州\", u\"City\": u\"都市\", u\"Town\": u\"町\"} # Englis...
[ 2, 0 ]
[]
[]
[ "dom", "python", "replace", "xml" ]
stackoverflow_0007991532_dom_python_replace_xml.txt
Q: Confluence XML-RPC: Set the "creation" date I am trying to migrate some existing blog entries into our confluence wiki using XML-RPC with Python. It is currently working with such things as title, content, space etc but will not work for created date. This is what was currently attempted import xmlrpclib proxy=xm...
Confluence XML-RPC: Set the "creation" date
I am trying to migrate some existing blog entries into our confluence wiki using XML-RPC with Python. It is currently working with such things as title, content, space etc but will not work for created date. This is what was currently attempted import xmlrpclib proxy=xmlrpclib.ServerProxy('<my_confluence>/rpc/xmlrpc')...
[ "If you would try to store the existing content as actual blog entries in Confluence, then you could use the \"publishDate\" parameter:\nimport xmlrpclib\nimport datetime\n\nproxy=xmlrpclib.ServerProxy('<my_confluence>/rpc/xmlrpc')\ntoken=proxy.confluence1.login('username', 'password')\n\nblogpost = {\n 'title' ...
[ 1, 0 ]
[]
[]
[ "confluence", "python", "xml_rpc" ]
stackoverflow_0007036429_confluence_python_xml_rpc.txt
Q: compare list(of integers) using id() in python I found a strange thing in Python when I tried to compare lists composed of integers. For example: In [35]: id(range(1,5)),id(range(1,15)),id(range(16,0,-1)) Out[35]: (155687404, 155687404, 155687404) Q1: Why their id() values are the same? And how can they be the sa...
compare list(of integers) using id() in python
I found a strange thing in Python when I tried to compare lists composed of integers. For example: In [35]: id(range(1,5)),id(range(1,15)),id(range(16,0,-1)) Out[35]: (155687404, 155687404, 155687404) Q1: Why their id() values are the same? And how can they be the same since they look different? Q2: How can I compare ...
[ "Directly from python's doc:\nReturn the “identity” of an object. This is an integer (or long integer) \nwhich is guaranteed to be unique and constant for this object during its lifetime. \nTwo objects with non-overlapping lifetimes may have the same id() value.\n\nYou could get the md5 hash to compare theese objec...
[ 7, 6, 5 ]
[]
[]
[ "compare", "hash", "list", "python" ]
stackoverflow_0007992105_compare_hash_list_python.txt
Q: Python - error when zipping files, 'L' format requires 0 <= number <= 4294967295 I run this code for zipping folders and files. def save_folder_as_zip(self, folder_to_zip, save_as): zipf = zipfile.ZipFile(str(save_as), mode="w", allowZip64=True) self.create_zip(zipf, folder_to_zip) zipf.close() re...
Python - error when zipping files, 'L' format requires 0 <= number <= 4294967295
I run this code for zipping folders and files. def save_folder_as_zip(self, folder_to_zip, save_as): zipf = zipfile.ZipFile(str(save_as), mode="w", allowZip64=True) self.create_zip(zipf, folder_to_zip) zipf.close() return zipf def create_zip(self, zipf, directory, folder=""): directory = director...
[ "I think it can be fixed applying the patch attached to this bug report:\nhttp://bugs.python.org/issue9720\nThe problem arises when the file you are trying to include in the zip file is larger than 2^32-1 bytes in original or compressed form. In this scenario the library need to store -1 as the file size/compressed...
[ 2 ]
[]
[]
[ "filenames", "python", "zip" ]
stackoverflow_0006911777_filenames_python_zip.txt
Q: Logarithmic scale in Tkinter scale Is it possible to create a Tkinter scale widget with logaritmic values? Or, kind of, set the ticks to the corresponding value? I need a scale in the range of 10^4 to 10^9, with the exponent in whole numbers. I was thinking about just labeling the "axis" accordingly, but a 10^x de...
Logarithmic scale in Tkinter scale
Is it possible to create a Tkinter scale widget with logaritmic values? Or, kind of, set the ticks to the corresponding value? I need a scale in the range of 10^4 to 10^9, with the exponent in whole numbers. I was thinking about just labeling the "axis" accordingly, but a 10^x depiction is really more practical and int...
[ "from Tkinter import *\n\nclass Slider(Frame):\n def __init__(self, parent=None ):\n Frame.__init__(self, parent)\n self.number = 0\n self.slide = Scale(self, orient=HORIZONTAL, command=self.setValue,\n length=200, sliderlength=20,\n showva...
[ 2 ]
[]
[]
[ "python", "tkinter", "tkinter_scale" ]
stackoverflow_0007160864_python_tkinter_tkinter_scale.txt
Q: classes in Python for a beginner Could you please help me to find the problem? Python code that works: class ParamWindow: def __init__(self, b): self.a = b print self.a params = ParamWindow(8) print params.a this prints 8 and 8. Ok. Then I do: class ParamWindow: def __init__(self, parent,...
classes in Python for a beginner
Could you please help me to find the problem? Python code that works: class ParamWindow: def __init__(self, b): self.a = b print self.a params = ParamWindow(8) print params.a this prints 8 and 8. Ok. Then I do: class ParamWindow: def __init__(self, parent, b): self = wx.Frame(parent = ...
[ "def __init__(self, parent, b):\n self = wx.Frame(parent = parent, id=-1, title=\"Parameters\")\n\nHere you reassign self, so you end up having no reference to the ParamWindow instance any more! You should never do that! What are you trying to achieve?\n self.a = b\n\nHere, you assign a to self, which is no...
[ 6 ]
[]
[]
[ "class", "python" ]
stackoverflow_0007993089_class_python.txt
Q: I want to take tagcleaned html source with turkish characters therefore i need to combine this code witth a charset # -*- coding: utf-8 -*- # -*- coding: iso-8859-9 -*- import urllib2 import urllib from lxml.html import fromstring from lxml.html.clean import Cleaner from formatter import NullFormatter from urllib...
I want to take tagcleaned html source with turkish characters therefore i need to combine this code witth a charset
# -*- coding: utf-8 -*- # -*- coding: iso-8859-9 -*- import urllib2 import urllib from lxml.html import fromstring from lxml.html.clean import Cleaner from formatter import NullFormatter from urllib2 import URLError import cookielib import urllib,time import urlparse import datetime import new from htmllib import HTML...
[ "good_stuff.encode('ascii', 'ignore') will delete your Turkish characters and anything else that's not ASCII. Don't do that. As you seem to be using ISO-8859-9, try using that to encode your Unicode characters.\nWhat operating system are you using?\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007992922_python.txt
Q: How can I stop the debugger server from pydev? I am using the pydev remote debugger feature for my application. When I try to stop the debugger server via the stop button it shows on the console that the server is successfully terminated but it isn't because it is still accepting new connections on its default por...
How can I stop the debugger server from pydev?
I am using the pydev remote debugger feature for my application. When I try to stop the debugger server via the stop button it shows on the console that the server is successfully terminated but it isn't because it is still accepting new connections on its default port (5678). Do you know how can I stop the server in a...
[ "This was a bug -- and it was fixed in the latest version (PyDev 2.2.4), so, please upgrade to the latest version and that should be working already.\n" ]
[ 0 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0007988856_eclipse_pydev_python.txt
Q: Cannot access AppStats on deployed version I have enabled appstats for my Python App Engine application, and I can access it locally under the /_ah/stats/ url but when I deploy the application and visit the appspot.com under my application in the UI there is no custom AppStats link as it should have. In my yaml fi...
Cannot access AppStats on deployed version
I have enabled appstats for my Python App Engine application, and I can access it locally under the /_ah/stats/ url but when I deploy the application and visit the appspot.com under my application in the UI there is no custom AppStats link as it should have. In my yaml file I define: builtins: - appstats: on I wrap my...
[ "There shouldn't be a link in the managment site (unless you add it using admin_console).\nThe stats should be available at your-app-id.appspot.com/_ah/stats\n" ]
[ 7 ]
[]
[]
[ "appstats", "google_app_engine", "python" ]
stackoverflow_0007992949_appstats_google_app_engine_python.txt
Q: Subclassing builtin types in Python 2 and Python 3 When subclassing builtin types, I noticed a rather important difference between Python 2 and Python 3 in the return type of the methods of the built-in types. The following code illustrates this for sets: class MySet(set): pass s1 = MySet([1, 2, 3, 4, 5]) s...
Subclassing builtin types in Python 2 and Python 3
When subclassing builtin types, I noticed a rather important difference between Python 2 and Python 3 in the return type of the methods of the built-in types. The following code illustrates this for sets: class MySet(set): pass s1 = MySet([1, 2, 3, 4, 5]) s2 = MySet([1, 2, 3, 6, 7]) print(type(s1.union(s2))) p...
[ "This isn't a general change for built-in types when moving from Python 2.x to 3.x -- list and int, for example, have the same behaviour in 2.x and 3.x. Only the set type was changed to bring it in line with the other types, as discussed in this bug tracker issue.\nI'm afraid there is no really nice way to make it...
[ 12, 0, 0 ]
[]
[]
[ "built_in_types", "python", "python_3.x", "subclass" ]
stackoverflow_0007983243_built_in_types_python_python_3.x_subclass.txt
Q: Get dictionary in python to store primitive type objects (memory location) instead of the value of those objects? I want to store attributes of an object in a dictionary so I can change those attributes later. The problem is that these attributes are booleans, so when I put them in a dictionary it stores the boole...
Get dictionary in python to store primitive type objects (memory location) instead of the value of those objects?
I want to store attributes of an object in a dictionary so I can change those attributes later. The problem is that these attributes are booleans, so when I put them in a dictionary it stores the boolean value, not the attribute variable. I.e. location_dict = { 'dorm_common':newnom.dorm_common, 'cafeteria':...
[ "This isn't something special about dictionaries. It's intrinsic to the Python programming language as a whole. You want either pass-by-reference or mutable booleans (and in any case you should review your understanding of Python's semantics and its implementation, you sound like you may be confusing some things), ...
[ 2, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007986371_dictionary_python.txt
Q: How to run commands in the none-working directory in python?(not by giving the pathway) What I want to do is to make a sub-directory in the working-directory, and I want to run some of my commands in the sub-directory which in result the new files made will be saved in that directory. I have different types of fil...
How to run commands in the none-working directory in python?(not by giving the pathway)
What I want to do is to make a sub-directory in the working-directory, and I want to run some of my commands in the sub-directory which in result the new files made will be saved in that directory. I have different types of file mainly bam sam and txt. This is my command: individual= raw_input("Please type the name o...
[ "Use os.chdir.\n", "Use os.makedirs to create folders recursively:\nfolder = r'folders/to/create'\nos.makedirs(folder)\nos.chdir(folder)\n# Your file saving code here\n\nAlternatively, you could just construct the full filename, and use that when saving:\nfolder = r'folders/to/create'\nos.makedirs(folder)\nfull_f...
[ 4, 1 ]
[]
[]
[ "directory", "python", "save" ]
stackoverflow_0007993515_directory_python_save.txt
Q: Is it possible to submit batch processing requests with the Python Youtube API? I'm writing an application using Python that adds videos to a user's playlist on Youtube. Doing this one at a time causes Youtube to start throttling my requests. There is a batch processing API that allows you to submit 50 requests at...
Is it possible to submit batch processing requests with the Python Youtube API?
I'm writing an application using Python that adds videos to a user's playlist on Youtube. Doing this one at a time causes Youtube to start throttling my requests. There is a batch processing API that allows you to submit 50 requests at once, but I can't find out from the docs how to submit a batch processing request. T...
[ "It looks like this is documented on the gdata-python-client wiki: http://code.google.com/p/gdata-python-client/wiki/UsingBatchOperations. While the examples on that page are for Base and Spreadsheets, not YouTube, it should be fairly straightforward to apply the same techniques to the YouTube API. You will, I beli...
[ 3, 3 ]
[]
[]
[ "batch_processing", "gdata_api", "playlist", "python", "youtube" ]
stackoverflow_0002180016_batch_processing_gdata_api_playlist_python_youtube.txt
Q: Streaming audio and video with Python I need to make an application which streams live multimedia. At present my application is taking image frames from a webcam (using OpenCV) and sending it to the client. It is also sending audio using pymedia module. The problem is that both the image and audio packets that arr...
Streaming audio and video with Python
I need to make an application which streams live multimedia. At present my application is taking image frames from a webcam (using OpenCV) and sending it to the client. It is also sending audio using pymedia module. The problem is that both the image and audio packets that arrive at the client are out of sync. So I hav...
[ "You can try gst-python module.\nrefer to the gstPython Documentation for more detail.\n", "You can use gstreamer's python module. I mean gst-python mentioned above. Use rtmp protocol to synchronize client/server videos. Last time I use gst-python, there was no support for rtmp. At the time, my solution was to li...
[ 3, 2, 0 ]
[]
[]
[ "ipv6", "live", "python", "streaming", "video" ]
stackoverflow_0007993624_ipv6_live_python_streaming_video.txt
Q: Python Printing from python32 I can't get Python to print a word doc. What I am trying to do is to open the Word document, print it and close it. I can open Word and the Word document: import win32com.client msword = win32com.client.Dispatch("Word.Application") msword.Documents.Open("X:\Backoffice\Adam\checklist...
Python Printing from python32
I can't get Python to print a word doc. What I am trying to do is to open the Word document, print it and close it. I can open Word and the Word document: import win32com.client msword = win32com.client.Dispatch("Word.Application") msword.Documents.Open("X:\Backoffice\Adam\checklist.docx") msword.visible= True I ha...
[ "msword.ActiveDocument gives you the current active document. The PrintOut method prints that document: it doesn't take a document filename as a parameter.\nFrom http://msdn.microsoft.com/en-us/library/aa220363(v=office.11).aspx:\nexpression.PrintOut(Background, Append, Range, OutputFileName, From, To, Item, \n Co...
[ 2, 1 ]
[]
[]
[ "python", "win32com" ]
stackoverflow_0007993387_python_win32com.txt
Q: Fast in-place replacement of some values in a numpy array There has got to be a faster way to do in place replacement of values, right? I've got a 2D array representing a grid of elevations/bathymetry. I want to replace anything over 0 with NAN and this way is super slow: for x in range(elevation.shape[0]): ...
Fast in-place replacement of some values in a numpy array
There has got to be a faster way to do in place replacement of values, right? I've got a 2D array representing a grid of elevations/bathymetry. I want to replace anything over 0 with NAN and this way is super slow: for x in range(elevation.shape[0]): for y in range(elevation.shape[1]): if elevation[x,y] >...
[ "The following will do it:\nelevation[elevation > 0] = numpy.NAN\n\nSee Indexing with Boolean Arrays in the NumPy tutorial.\n", "np.putmask(elevation, elevation > 0, np.nan)\n\n" ]
[ 21, 3 ]
[]
[]
[ "numpy", "performance", "python" ]
stackoverflow_0007994133_numpy_performance_python.txt
Q: Can someone write a simple example of python old style class and new style class? While there are several articles written about new classes versus old classed I wasn't able to see a basic example with old/new style. A: The only syntactic difference is that new style classes inherit from object: class Old: ...
Can someone write a simple example of python old style class and new style class?
While there are several articles written about new classes versus old classed I wasn't able to see a basic example with old/new style.
[ "The only syntactic difference is that new style classes inherit from object:\nclass Old:\n ...\n\nclass New(object):\n ....\n\n", "I believe this wiki post is what you are looking for:\n <snip> \n The minor syntactic difference is that New Style Classes happen\n to inherit from object.\n\n class Old1:\n ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007994230_python.txt
Q: Efficient thresholding filter of an array with numpy I need to filter an array to remove the elements that are lower than a certain threshold. My current code is like this: threshold = 5 a = numpy.array(range(10)) # testing data b = numpy.array(filter(lambda x: x >= threshold, a)) The problem is that this creates...
Efficient thresholding filter of an array with numpy
I need to filter an array to remove the elements that are lower than a certain threshold. My current code is like this: threshold = 5 a = numpy.array(range(10)) # testing data b = numpy.array(filter(lambda x: x >= threshold, a)) The problem is that this creates a temporary list, using a filter with a lambda function (...
[ "b = a[a>threshold] this should do\nI tested as follows:\nimport numpy as np, datetime\n# array of zeros and ones interleaved\nlrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()\n\nt0 = datetime.datetime.now()\nflt = lrg[lrg==0]\nprint datetime.datetime.now() - t0\n\nt0 = datetime.datetime.now()\nflt =...
[ 113 ]
[]
[]
[ "filter", "numpy", "python", "threshold" ]
stackoverflow_0007994394_filter_numpy_python_threshold.txt
Q: How to keep Django from escaping HTML in ModelAdmin I have this class to configure django.contrib.admin for my Stream model. class StreamAdmin(admin.ModelAdmin): def stream_title(instance): return instance.info.title def network_name(instance): return '<img src="%s" />' % instance.network....
How to keep Django from escaping HTML in ModelAdmin
I have this class to configure django.contrib.admin for my Stream model. class StreamAdmin(admin.ModelAdmin): def stream_title(instance): return instance.info.title def network_name(instance): return '<img src="%s" />' % instance.network.image_url fieldsets = ( (None, { ...
[ "Use allow_tags.\ndef network_name(instance):\n return '<img src=\"%s\" />' % instance.network.image_url\nnetwork_name.allow_tags = True\n\n", "You can use mark_safe:\nfrom django.utils.safestring import mark_safe\n\nclass StreamAdmin(admin.ModelAdmin):\n ...\n\n def network_name(instance):\n retu...
[ 5, 2 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0007994200_django_django_admin_python.txt
Q: Importing Modules that use MultiProcessing Python I am looking to use the multiprocessing module to speed up the run time of some Transport Planning models. I've optimized as much as I can via 'normal' methods but at the heart of it is an absurdly parallel problem. Eg Perform the same set of matrix operations fou...
Importing Modules that use MultiProcessing Python
I am looking to use the multiprocessing module to speed up the run time of some Transport Planning models. I've optimized as much as I can via 'normal' methods but at the heart of it is an absurdly parallel problem. Eg Perform the same set of matrix operations four 4 different sets of inputs, all independent informati...
[ "\nDoes this mean I can never use parallel processing on an imported module?\n\nNo, it doesn't. You can use multiprocessing anywhere in your code, provided that the program's main module uses the if __name__ == '__main__' guard.\nOn Unix systems, you won't even need that guard, since it features the fork() system ...
[ 13 ]
[]
[]
[ "import", "matrix", "multiprocessing", "parallel_processing", "python" ]
stackoverflow_0007989123_import_matrix_multiprocessing_parallel_processing_python.txt
Q: Python - Immutable type example Can someone please tell me how I can use this piece of code?. I'm not sure what question it is I want to ask, I just want to define the class needed to play with it along with other commands that I can give to the interpreter. This is really making my headspin, because there is no o...
Python - Immutable type example
Can someone please tell me how I can use this piece of code?. I'm not sure what question it is I want to ask, I just want to define the class needed to play with it along with other commands that I can give to the interpreter. This is really making my headspin, because there is no other supporting code for it and I thi...
[ "Nothing crazy going on here. I'll annoate with comments. Although it should be formatted like this:\n# Inherit from the built in type 'float', \n# so that this can be used anywhere a float can\nclass RoundFloat(float):\n # __new__ takes care of actually creating the object\n def __new__(cls, val):\n #...
[ 4, 4, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007992006_python.txt
Q: Preserving only domain-specific keywords? I am trying to determine the most popular keywords for certain class of documents in my collection. Assuming that the domain is "computer science" (which of course, includes networking, computer architecture, etc.) what is the best way to preserve these domain-specific key...
Preserving only domain-specific keywords?
I am trying to determine the most popular keywords for certain class of documents in my collection. Assuming that the domain is "computer science" (which of course, includes networking, computer architecture, etc.) what is the best way to preserve these domain-specific keywords from text? I tried using Wordnet but I am...
[ "You need a huge training set of documents. Small subset of this collection (but still large set of documents) should represent given domain. Using nltk calculate words statistics taking into account morphology, filter out stopwords. The good statistics is TF*IDF which is roughly a number of occurenses of a word in...
[ 6, 3 ]
[]
[]
[ "machine_learning", "nlp", "nltk", "python" ]
stackoverflow_0007986900_machine_learning_nlp_nltk_python.txt
Q: Learning Python/Apache/Linux Im currently a C# developer with a few years of experiance building websites with IIS/.net. I want to do a pet project using Python/Apache/Linux. Can anyone recomend some resources to help me pick up open source programming? In particular my knowledge of Apache and linux server adminis...
Learning Python/Apache/Linux
Im currently a C# developer with a few years of experiance building websites with IIS/.net. I want to do a pet project using Python/Apache/Linux. Can anyone recomend some resources to help me pick up open source programming? In particular my knowledge of Apache and linux server administration is very low. Setting up Ap...
[ "Also some useful links from me :\n1) Building LAMP (skip the PHP part)\n2) Setup Python on Linux\n3) Embedding Apache2 and Python\n4) Installing Django on Ubuntu\n5) Recommended: Official Django Complete Setup Guide\n", "A good resource for python learning are Google Lectures (link), also about Apache you should...
[ 2, 0, 0 ]
[]
[]
[ "apache", "linux", "python" ]
stackoverflow_0007993373_apache_linux_python.txt
Q: Parse CEST/CET time in python I have these date strings: Fri Oct 7 16:00:09 CEST 2011 I want to convert them to UTC. I have tried with this implementation: def LocalToUtc(localtime): return datetime.strptime(localtime, "%a %m %d %H:%M:%S %Z %Y").isoformat() + 'Z' But I get a ValueError: ValueError: time dat...
Parse CEST/CET time in python
I have these date strings: Fri Oct 7 16:00:09 CEST 2011 I want to convert them to UTC. I have tried with this implementation: def LocalToUtc(localtime): return datetime.strptime(localtime, "%a %m %d %H:%M:%S %Z %Y").isoformat() + 'Z' But I get a ValueError: ValueError: time data 'Fri Oct 7 16:00:09 CEST 2011' d...
[ "Use the parsedatetime library.\n", "There are two problems here:\n\nYou're using \"%m\" instead of \"%b\"\nThe standard lib can't parse \"CEST\", it understands only very few time zone names.\nSee also here: What possible values does datetime.strptime() accept for %Z?\n\n" ]
[ 2, 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0007992459_datetime_python.txt
Q: Numpy python find minimum value of each column and subtract this value from each column Can anyone help with a snippet of code using numpy and python? Given an numpy array such as a = array([[1,11], [3,9], [5,7]] I want to find the minimun value of each column, so 1 and 7 and then subtract this value from the re...
Numpy python find minimum value of each column and subtract this value from each column
Can anyone help with a snippet of code using numpy and python? Given an numpy array such as a = array([[1,11], [3,9], [5,7]] I want to find the minimun value of each column, so 1 and 7 and then subtract this value from the respective columns, a = array([[0,4], [2,2], [4,0]]
[ ">>> a - a.min(axis=0)\narray([[0, 4],\n [2, 2],\n [4, 0]])\n\nWhere axis=0 refers to columns.\n" ]
[ 42 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007994992_numpy_python.txt
Q: Why are templatetags stored in directories? I'm now working with template tags and one thing I haven't understood is why do template-tags have to be stored inside a templatetags directory in the app. Is there an underlying reason for this? Is it possible to store them in a templatetags.py file somehow so that I ca...
Why are templatetags stored in directories?
I'm now working with template tags and one thing I haven't understood is why do template-tags have to be stored inside a templatetags directory in the app. Is there an underlying reason for this? Is it possible to store them in a templatetags.py file somehow so that I can reduce the extra bloat around having extra dire...
[ "Django expects you to arrange your apps in certain ways. Requiring a templatetags directory in the app is not the exception. Some other requirements are:\n\nModelAdmin in admin.py (for autodiscovery)\nModels in models.py\nManagement commands in management/commands directory\nFixtures in the fixtures directory\n\nU...
[ 3, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0007993348_django_django_templates_python.txt
Q: Invalid namespace URI Using Python's lxml I have a scripts designed to access an online API (Google Search Appliance), which requires a specific xml format be posted. I have built an xml document using lxml, but my problem is that upon attempting to create the root node, I am given a ValueError: Invalid namespace...
Invalid namespace URI Using Python's lxml
I have a scripts designed to access an online API (Google Search Appliance), which requires a specific xml format be posted. I have built an xml document using lxml, but my problem is that upon attempting to create the root node, I am given a ValueError: Invalid namespace URI Exception. Here is the full example: gsa_...
[ "URIs of namespaces are never looked up by the parser, it doesn't matter if you're behind a proxy or not. But the parser in lxml 2.3 checks whether they are valid URIs. So it should be \nnsmap = {None: default_ns, \"gsa\": gsa_ns}\n\n" ]
[ 2 ]
[]
[]
[ "lxml", "namespaces", "python" ]
stackoverflow_0007994965_lxml_namespaces_python.txt
Q: Is asynchronous socket handling the way i need to go? In Python So i been readying for a awhile now. And it seems like asynchronous socket handling would be a better approach to dealing with what I'm trying to do. Right now I'm working on a gaming server. At the moment socket server will do ok with about 3 client...
Is asynchronous socket handling the way i need to go? In Python
So i been readying for a awhile now. And it seems like asynchronous socket handling would be a better approach to dealing with what I'm trying to do. Right now I'm working on a gaming server. At the moment socket server will do ok with about 3 clients or so. Sending data at the same exact time. But my problem is, af...
[ "Asynchronous sockets are more effective then synchronous. But if the game is lagging for 4+ clients, then your server/client system is badly written and it is not the matter of sockets imho.\n" ]
[ 1 ]
[]
[]
[ "asynchronous", "python", "sockets", "udp" ]
stackoverflow_0007995290_asynchronous_python_sockets_udp.txt
Q: Receiving non-ascii emails with App Engine Python results in strange character encoding I'm receiving emails with the Google App Engine Python and storing those in the datastore. class LogSenderHandler(InboundMailHandler): def receive(self, mail_message): logging.info("Received a message from: " + mail...
Receiving non-ascii emails with App Engine Python results in strange character encoding
I'm receiving emails with the Google App Engine Python and storing those in the datastore. class LogSenderHandler(InboundMailHandler): def receive(self, mail_message): logging.info("Received a message from: " + mail_message.sender) When I receive an email from an ASCII address, everything works fine: Me [m...
[ "The subject is encoded according to RFC 2047. See the Internationalized headers section of the email module.\nHere is an example decoding the subject to Unicode:\n>>> s='=?ISO-8859-1?Q?Mr_Kr=F6ber?= [mr.kroeber@gmail.com]'\n>>> from email.header import decode_header\n>>> decode_header(s)\n[('Mr Kr\\xf6ber', 'iso-8...
[ 6 ]
[]
[]
[ "ascii", "email", "encoding", "google_app_engine", "python" ]
stackoverflow_0007994347_ascii_email_encoding_google_app_engine_python.txt
Q: python screen-scraping to click a particular image in a html5 image map In a html5 page using image map, I would like to use python (or Perl, Ruby, C) to crawl it to find a particular image (those are separated by a transparency area) in another one and click it when this image is found. The image are the same all...
python screen-scraping to click a particular image in a html5 image map
In a html5 page using image map, I would like to use python (or Perl, Ruby, C) to crawl it to find a particular image (those are separated by a transparency area) in another one and click it when this image is found. The image are the same all the times. What is the best way to achieve this ? Edit: for french readers,...
[ "Sikuli might be a perfect for this. It is based on Jython, thus can be extended with Python or Java tools.\n\nSikuli is a visual technology to automate and test graphical user\n interfaces (GUI) using images (screenshots). Sikuli includes Sikuli\n Script, a visual scripting API for Jython, and Sikuli IDE, an\n ...
[ 1, 0 ]
[]
[]
[ "html", "image_processing", "python", "screen_scraping" ]
stackoverflow_0007825991_html_image_processing_python_screen_scraping.txt
Q: how to "conditionally compile" python Yes, I know, but it was the only way to summarize what I want to do. For opening a serial port I want to use: portfd = os.open(portname, os.O_RDWR | os.O_NONBLOCK) Problem is that O_NONBLOCK doesn't exist under windows, which means it blows up here. I'm testing under wind...
how to "conditionally compile" python
Yes, I know, but it was the only way to summarize what I want to do. For opening a serial port I want to use: portfd = os.open(portname, os.O_RDWR | os.O_NONBLOCK) Problem is that O_NONBLOCK doesn't exist under windows, which means it blows up here. I'm testing under windows for deployment under an OS that support...
[ "Another method nobody has yet suggested:\nportfd = os.open(portname, os.O_RDWR | getattr(os, 'O_NONBLOCK', 0))\n\nThis is the easy way to default any attribute that might not exist.\n", "You could use a try/except block e.g.\ntry:\n options = os.O_RDWR | os.O_NONBLOCK\nexcept NameError:\n options = os.O_RD...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0007996092_python_windows.txt
Q: pyparsing recursive does not throw exception I have the following snippet with recursive statement from a pyparsing parser: def parse_query(querystr): # <<other parsing stuff>> queryexpression = querycondition + ZeroOrMore(Word("and") + querycondition) try: return queryexpression.parseString(qu...
pyparsing recursive does not throw exception
I have the following snippet with recursive statement from a pyparsing parser: def parse_query(querystr): # <<other parsing stuff>> queryexpression = querycondition + ZeroOrMore(Word("and") + querycondition) try: return queryexpression.parseString(querystr) except ParseException as e: lo...
[ "\nqueryexpression = querycondition + ZeroOrMore(Word(\"and\") + querycondition)\n\nThis is not required to parse the entire line. ZeroOrMore means exactly that. It stops when it encounters something that fails to meet the definition. It will always succeed, because \"zero\" is a valid option for the number of time...
[ 1 ]
[]
[]
[ "parsing", "pyparsing", "python" ]
stackoverflow_0007996238_parsing_pyparsing_python.txt
Q: Python: Modifying a Function to Search Values in a Dictionary I wrote a simple function that receives a dictionary and a string as a parameter. The function uses the string to search the dictionary and then returns a new dictionary with results. Now i need some help modifying this code, or creating a new function...
Python: Modifying a Function to Search Values in a Dictionary
I wrote a simple function that receives a dictionary and a string as a parameter. The function uses the string to search the dictionary and then returns a new dictionary with results. Now i need some help modifying this code, or creating a new function, that when passed a string, searches values, in the key:value pair...
[ "def searchKeys(aDictionary,searchTerm):\n results = {}\n\n for k,v in aDictionary.iteritems():\n if searchTerm in k or searchTerm in v:\n results[k] = v\n return results\n\nor shorter:\nresults = dict((k,v) for k,v in a.iteritems() if searchItem in k or searchItem in v)\n\nIt will howeve...
[ 3, 1, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007996286_dictionary_python.txt
Q: Appending first value of a list into the first value of another list; python Working in python 2.7. I have two lists (simplified to make explanations clearer). T = [[1,0], [1,0], [0,5], [3, -1]] B = [[1], [3], [2], [2]] I would like to append the second list (B) so that the first value of the B list is appended t...
Appending first value of a list into the first value of another list; python
Working in python 2.7. I have two lists (simplified to make explanations clearer). T = [[1,0], [1,0], [0,5], [3, -1]] B = [[1], [3], [2], [2]] I would like to append the second list (B) so that the first value of the B list is appended to the first list in the T list and so on. Ex- I want the output to look like: T = ...
[ "map(list.extend, T, B)\n\nor, if you prefer an explicit loop\nfor t, b in zip(T, B):\n t.extend(b)\n\n", "Use zip\n>>> t = [[1,0], [1,0], [0,5], [3, -1]]\n... b = [[1], [3], [2], [2]]\n>>> [x + y for x, y in zip(t, b)]\n3: [[1, 0, 1], [1, 0, 3], [0, 5, 2], [3, -1, 2]]\n\n" ]
[ 5, 2 ]
[]
[]
[ "append", "list", "python" ]
stackoverflow_0007996379_append_list_python.txt
Q: Distributing python-written executable with veusz I would like to distribute an application written in python as a .exe file. I have already been able to do this using py2exe, but now I have incorporated the veusz library into my code. Ideally my program should open up a veusz plot (as it does on my computer, whic...
Distributing python-written executable with veusz
I would like to distribute an application written in python as a .exe file. I have already been able to do this using py2exe, but now I have incorporated the veusz library into my code. Ideally my program should open up a veusz plot (as it does on my computer, which has python, numpy, etc. all installed). However, I wa...
[ "Veusz runs its user interface in a separate python process so that it does not block python. If you look at veusz/embed.py, it tries to start up python or a veusz executable. You'd need to modify embed.py to start your .exe (sys.executable) if frozen instead of veusz and pass some special parameter which your prog...
[ 1 ]
[]
[]
[ "py2exe", "python", "veusz" ]
stackoverflow_0007961431_py2exe_python_veusz.txt
Q: iterate dictionary multiple values by keys in python I want to find most optimal way to iterate values in key in python. I have file with that structure: 17 key1 18 key1 45 key2 78 key2 87 key2 900 key3 92 key4 so I need to set the second column as key(with no repetition) and link to this key all the values (fi...
iterate dictionary multiple values by keys in python
I want to find most optimal way to iterate values in key in python. I have file with that structure: 17 key1 18 key1 45 key2 78 key2 87 key2 900 key3 92 key4 so I need to set the second column as key(with no repetition) and link to this key all the values (first column) corresponding to it. 'key1':['17','18'] 'key2...
[ "My advice is that, if you have to re-read the input file, you may as well re-create your dictionary, but that depends on the time needed for dictionary creation. As you request, maybe it's quicker to analyze differences in file, and to update the dictionary.\nYou can have a look at the difflib module, and then to ...
[ 1 ]
[]
[]
[ "dictionary", "iteration", "python" ]
stackoverflow_0007996349_dictionary_iteration_python.txt
Q: How to Collect Tweets More Quickly Using Twitter API in Python? For a research project, I am collecting tweets using Python-Twitter. However, when running our program nonstop on a single computer for a week we manage to collect about only 20 MB of data per week. I am only running this program on one machine so tha...
How to Collect Tweets More Quickly Using Twitter API in Python?
For a research project, I am collecting tweets using Python-Twitter. However, when running our program nonstop on a single computer for a week we manage to collect about only 20 MB of data per week. I am only running this program on one machine so that we do not collect the same tweets twice. Our program runs a loop th...
[ "How about using the streaming API? This is exactly the use-case it was created to address. With the streaming API you will not have any problems gathering megabytes of tweets. You still won't be able to access all tweets or even a statistically significant sample without being granted access by Twitter though.\n",...
[ 5, 1, 1 ]
[]
[]
[ "python", "python_twitter", "twitter" ]
stackoverflow_0004249684_python_python_twitter_twitter.txt