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: How to parse through script tag using python and beautifulsoup I am trying to extract the attributes of a frame tag which is inside document.write function on a page as follows: <script language="javascript"> . . . document.write('<frame name="nav" src="/nav/index_nav.html" marginwidth="0" marginheight="0" scrolli...
How to parse through script tag using python and beautifulsoup
I am trying to extract the attributes of a frame tag which is inside document.write function on a page as follows: <script language="javascript"> . . . document.write('<frame name="nav" src="/nav/index_nav.html" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" border = "no" noresize>'); if (anchor != ""...
[ "You can't do it with BeautifulSoup alone. BeautifulSoup parses HTML as it would arrive to the browser (before any rewriting or DOM manipulation), and it does not parse (let alone execute) Javascript. \nYou might want to use a simple regular expression in this special case.\n", "Pyparsing might help you bridge t...
[ 2, 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0001883273_beautifulsoup_python.txt
Q: How could I get a Frame with a scrollbar in Tkinter? I'd like to have a Frame, where the user could add as many textfields as needed by the application. The application starts with a textfield, and a button below that textfield. When the user presses the button, a new text entry will be added below the first one ...
How could I get a Frame with a scrollbar in Tkinter?
I'd like to have a Frame, where the user could add as many textfields as needed by the application. The application starts with a textfield, and a button below that textfield. When the user presses the button, a new text entry will be added below the first one ( this may be repeated countless times ). In the middle of...
[ "If you can use Tix, there is the ScrolledWindow widget which has a window Frame and one or two Scrollbar widgets:\nimport Tix as tk\n\nr= tk.Tk()\nr.title(\"test scrolled window\")\nsw= tk.ScrolledWindow(r, scrollbar=tk.Y) # just the vertical scrollbar\nsw.pack(fill=tk.BOTH, expand=1)\nfor i in xrange(10):\n e=...
[ 8, 7 ]
[]
[]
[ "frame", "python", "scrollbar", "tkinter" ]
stackoverflow_0001873575_frame_python_scrollbar_tkinter.txt
Q: Named parameters with Python C API? How can I simulate the following Python function using the Python C API? def foo(bar, baz="something or other"): print bar, baz (i.e., so that it is possible to call it via: >>> foo("hello") hello something or other >>> foo("hello", baz="world!") hello world! >>> foo("hello...
Named parameters with Python C API?
How can I simulate the following Python function using the Python C API? def foo(bar, baz="something or other"): print bar, baz (i.e., so that it is possible to call it via: >>> foo("hello") hello something or other >>> foo("hello", baz="world!") hello world! >>> foo("hello", "world!") hello, world! )
[ "See the docs: you want to use PyArg_ParseTupleAndKeywords, documented at the URL I gave.\nSo for example:\ndef foo(bar, baz=\"something or other\"):\n print bar, baz\n\nbecomes (roughly -- haven't tested it!):\n#include \"Python.h\"\n\nstatic PyObject *\nthemodule_foo(PyObject *self, PyObject *args, PyObject *k...
[ 12 ]
[]
[]
[ "c", "named_parameters", "python", "python_c_api" ]
stackoverflow_0001884327_c_named_parameters_python_python_c_api.txt
Q: AJAX URLs and GET requests Ok, a great example of what I am trying to achieve is at Google Translate. The URL: http://translate.google.com/#en|es|this is what I am trying to do makes a GET request using this URL: http://translate.google.com/translate_a/t?client=t&text=this%20is%20what%20I%20am%20trying%20to%20do&s...
AJAX URLs and GET requests
Ok, a great example of what I am trying to achieve is at Google Translate. The URL: http://translate.google.com/#en|es|this is what I am trying to do makes a GET request using this URL: http://translate.google.com/translate_a/t?client=t&text=this%20is%20what%20I%20am%20trying%20to%20do&sl=en&tl=es&otf=1&pc=0 I'm not tr...
[ "What you're looking for is JQuery's Serialization functionality.\n", "Hey, you can make a customized URL by getting the values of the input fields you wish and then just concatenate this with you url.\n$.getJSON(\"http://translate?lang=\" + $(\".lang\").attr(\"value\") + \"&text=bla\");\n\ni just simplized here ...
[ 1, 0, 0 ]
[]
[]
[ "ajax", "jquery", "python", "url" ]
stackoverflow_0001883626_ajax_jquery_python_url.txt
Q: Handling UTF-16 in a Django uploaded file In my Django webapp, in one location users can upload a text file where each line contains a string which will be operated on - the file isn't being stored on the server or anything like that. My code looks like this: roFile = request.FILES['uploadFileName'] ros = roFile.r...
Handling UTF-16 in a Django uploaded file
In my Django webapp, in one location users can upload a text file where each line contains a string which will be operated on - the file isn't being stored on the server or anything like that. My code looks like this: roFile = request.FILES['uploadFileName'] ros = roFile.read().strip() ros = ros.split('\n') ros = [t.st...
[ "This first part doesn't answer your question (I know nothing about django); I'd just like to point out that when you supply code that you say works or doesn't work, you should copy/past the actual code that you ran,; don't type it from memory.\nThis code:\nimport codecs\nfrom django.utils.encoding\nf = codecs.open...
[ 1 ]
[]
[]
[ "django", "python", "utf_8" ]
stackoverflow_0001884399_django_python_utf_8.txt
Q: How to transfer a file between two FTP servers? I have two ftp servers with fxp enabled on both, I'm just wondering how I would transfer a file between the two servers in Python? I was told curl wouldnt do it, but maybe ftplib will do. so, the file (file.txt) is in '/personal/' FTP1 and I want to transfer that to ...
How to transfer a file between two FTP servers?
I have two ftp servers with fxp enabled on both, I'm just wondering how I would transfer a file between the two servers in Python? I was told curl wouldnt do it, but maybe ftplib will do. so, the file (file.txt) is in '/personal/' FTP1 and I want to transfer that to FTP2 also to the same place, '/personal/' Any ideas o...
[ "You should use ftplib (http://docs.python.org/library/ftplib.html)\n", "The simplest thing to is call the shell from within python, and then scp your file from one computer to the other. It shouldn't be very costly, almost nothing compared with the transfer costs, so don't worry about performance. \nJust try \no...
[ 2, 0 ]
[]
[]
[ "ftp", "ftplib", "python" ]
stackoverflow_0001881752_ftp_ftplib_python.txt
Q: Removing custom widget from QVBoxLayout I've got a QFrame with a QVBoxLayout and I'm adding my own custom widgets to the layout to simulate a QListWidget but with more information/functionality in the items. I add the widget to the layout and keep a reference in a member variable (this is Python): self.sv_widge...
Removing custom widget from QVBoxLayout
I've got a QFrame with a QVBoxLayout and I'm adding my own custom widgets to the layout to simulate a QListWidget but with more information/functionality in the items. I add the widget to the layout and keep a reference in a member variable (this is Python): self.sv_widgets[purchase.id] = widget sel...
[ "You can do this:\nimport sip # you'll need this import (no worries, it ships with your pyqt install)\nsip.delete(self.sv_widgets[purchase.id])\n\nsip.delete(obj) explicitely calls the destructor on the corresponding C++ object. removeWidget does not cause this destructor to be called (it still has a parent at that...
[ 6, 1 ]
[]
[]
[ "layout", "pyqt", "python", "qt" ]
stackoverflow_0001869034_layout_pyqt_python_qt.txt
Q: When are property validations run in Google App Engine (GAE)? So I was reading the following documentation on defining your own property types in GAE. I noticed that I could also include a .validate() method when extending a new Property. This validate method will be called "when an assignment is made to a propert...
When are property validations run in Google App Engine (GAE)?
So I was reading the following documentation on defining your own property types in GAE. I noticed that I could also include a .validate() method when extending a new Property. This validate method will be called "when an assignment is made to a property to make sure that it is compatible with your assigned attributes"...
[ "Before put, and during the transaction, respectively (it may abort the transaction if validation fails of course). \"When an assignment is made\" to a property of your entity is when you write theentity.theproperty = somevalue (or when you perform it implicitly).\nI believe that queries of unrelated entities duri...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001884635_google_app_engine_python.txt
Q: An Exercise: map or reduce a map in Python without list comprehensions? When I started writing this question, I didn't think of the easy solution with nested lists, but now anyway want to find one. Here's an ugly code: fun0( fun1(fun2(fun3(arg1))), fun1(fun2(fun3(arg4))), fun1(fun2(fun3(arg4))), fu...
An Exercise: map or reduce a map in Python without list comprehensions?
When I started writing this question, I didn't think of the easy solution with nested lists, but now anyway want to find one. Here's an ugly code: fun0( fun1(fun2(fun3(arg1))), fun1(fun2(fun3(arg4))), fun1(fun2(fun3(arg4))), fun1(fun2(fun3(arg4)))) Ouch! Names are given for examples. In the real applic...
[ "your 3 examples do 3 different things.\nyour original is the same as\nfun0(map(lambda x:fun1(fun2(fun3(x))), [arg1,arg2,arg3,arg4])\n\nyour second example, if you absolutely want a functional form, is probably something like\nfun0(map(apply, itertools.product([fun1,fun2,fun3],[arg1,arg2,arg3,arg4])))\n\n", "def ...
[ 2, 1 ]
[ "The most functional way to rewrite your first code block would be to compose the three functions, map the composed function over the list of arguments, then apply fun0 to the list. Python doesn't really have a natural way to do function composition, so something like Jimmy's solution is where you'll end up.\nPytho...
[ -1 ]
[ "functional_programming", "map", "python" ]
stackoverflow_0001884682_functional_programming_map_python.txt
Q: Pinging first available host in network subnets I've written a small script in Python that pings all subnets of my school's wireless network and prints out the IP addresses and hostnames of computers that are connected to each subnet of the network. My current setup is that I'm relying on creating threads to handl...
Pinging first available host in network subnets
I've written a small script in Python that pings all subnets of my school's wireless network and prints out the IP addresses and hostnames of computers that are connected to each subnet of the network. My current setup is that I'm relying on creating threads to handle each of the ping requests. from threading import T...
[ "Simplest thing would be to have a thread work through a whole subnet and exit when it finds a host.\nUNTESTED\nfrom Queue import Queue\nimport time\nimport socket\n\n#wraps system ping command\ndef ping(i, q):\n \"\"\"Pings address\"\"\"\n while True:\n subnet = q.get()\n # each IP addresse in ...
[ 1, 0 ]
[]
[]
[ "networking", "python", "subnet" ]
stackoverflow_0001883136_networking_python_subnet.txt
Q: Should I take a Python CS class using Windows or Mac? I'll be taking a Python-based computer science class next semester using my MacBook Pro. It will be centered around a custom-designed package for this class. The problem is that this package is being sponsored by Microsoft Research, so it was obviously designed...
Should I take a Python CS class using Windows or Mac?
I'll be taking a Python-based computer science class next semester using my MacBook Pro. It will be centered around a custom-designed package for this class. The problem is that this package is being sponsored by Microsoft Research, so it was obviously designed with Windows in mind. Supposedly, it runs on Mac OS and Li...
[ "If the class expects the code to run on Windows then I would install a VM with Windows on it since it is possible that some things may not work quite the same way (especially if you are doing system-specific things like file-system access or executing OS commands).\nClasswork/homework always goes smoother when you...
[ 9, 4, 3, 3, 2, 0 ]
[]
[]
[ "compatibility", "macos", "python", "windows" ]
stackoverflow_0001878904_compatibility_macos_python_windows.txt
Q: Django loaddata error I created a "fixtures" folder in the app directory and put data1.json in there. This is what is in the file: [{"firm_url": "http://www.graychase.com/kadam", "firm_name": "Gray & Chase", "first": " Karin ", "last": "Adam", "school": "Ernst Moritz Arndt University Greifswald", "year_graduated"...
Django loaddata error
I created a "fixtures" folder in the app directory and put data1.json in there. This is what is in the file: [{"firm_url": "http://www.graychase.com/kadam", "firm_name": "Gray & Chase", "first": " Karin ", "last": "Adam", "school": "Ernst Moritz Arndt University Greifswald", "year_graduated": " 2004"} ] In the comman...
[ "it looks like you are not defining your fixtures properly. Take a look at the Django Documentation. You need to define the model that you are loading, then define the fields like this \n [\n {\n \"model\": \"myapp.person\",\n \"pk\": 1,\n \"fields\": {\n \"first_name\": \"John\",\n \"last_nam...
[ 11, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001884827_django_python.txt
Q: Liteweight CGI Server to use on local machine to serve KML to Google Earth via Python or similar? Greetings, I want to write a script that handles simple http requests from Google Earth and sends back KML to display map tiles that are stored locally. I would LIKE to use Python but any language is fine. I have no...
Liteweight CGI Server to use on local machine to serve KML to Google Earth via Python or similar?
Greetings, I want to write a script that handles simple http requests from Google Earth and sends back KML to display map tiles that are stored locally. I would LIKE to use Python but any language is fine. I have not ever done anything with CGI, but I think this is the simplest way to accomplish my task. This is wha...
[ "If I were you I'd use MapServer and Tilecache to do exactly that (serving up georeferenced raster imagery over http / python mapscript bindings available).\nIf you want plain cgi you can probably use lighthttpd or nxginx or similar.\nAlso note that scraping the google map tiles is very likely infringing their term...
[ 1, 1 ]
[]
[]
[ "cgi", "google_earth", "kml", "python" ]
stackoverflow_0001885113_cgi_google_earth_kml_python.txt
Q: Use Python's easy_install in intranet Increasingly I found myself using tools based upon python, particularly that use installation processes involving easy_install. The trouble for me is that I am On an intranet with no internet access On windows (which always complicates things a little!) Any advice on how t...
Use Python's easy_install in intranet
Increasingly I found myself using tools based upon python, particularly that use installation processes involving easy_install. The trouble for me is that I am On an intranet with no internet access On windows (which always complicates things a little!) Any advice on how to setup easy_install on my intranet to make...
[ "I think you can use .egg files with easy_install, you could host those on your intranet and point easy_install to it. See http://peak.telecommunity.com/DevCenter/EasyInstall#using-easy-install for a good reference.\n" ]
[ 3 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0001884791_easy_install_python.txt
Q: How slow are Python/django exceptions? is python exception slow? I'm kind using python exceptions to structure programm follow in my web application, and I'm wondering how throwing exceptions will affect performance of my application. what is your thoughts? which one of the following statements is less expensive ...
How slow are Python/django exceptions?
is python exception slow? I'm kind using python exceptions to structure programm follow in my web application, and I'm wondering how throwing exceptions will affect performance of my application. what is your thoughts? which one of the following statements is less expensive in terms of memory and cpu? try: artist ...
[ "Handling exceptions will be the least of your worries with regards to performance. I would suggest, however, that you use a shortcut provided by Django for you:\nfrom django.shortcuts import get_object_or_404\nartist = get_object_or_404(Artist, id=id)\n\nWhich either assigns the object to artist or returns a 404....
[ 15, 10, 8 ]
[]
[]
[ "django", "exception", "python" ]
stackoverflow_0001885292_django_exception_python.txt
Q: How to populate a Django sqlite3 database My plan is to collect lawyer biography data from websites in batches and convert each batch into a .csv file, then to json, and then load each into a Django database. Please let me know how to achieve this task the best way. A: Just load the database directly. Collect d...
How to populate a Django sqlite3 database
My plan is to collect lawyer biography data from websites in batches and convert each batch into a .csv file, then to json, and then load each into a Django database. Please let me know how to achieve this task the best way.
[ "Just load the database directly. Collect data from websites in batches, loading the SQlite3 directly. Just write simple batch applications that use the Django ORM. Collect data from websites and load SQLite3 immediately. Do not create CSV. Do not create JSON. Do not create intermediate results. Do not do an...
[ 7 ]
[]
[]
[ "csv", "django", "json", "python" ]
stackoverflow_0001884694_csv_django_json_python.txt
Q: Parsing multilevel text list I need to parse text lists: 1 List name 1 item 2 item 3 item 2 List name 1 item 2 item 3 item 3 List name 1 item 2 item 3 item I was trying to use regular expression to split first level list: import re def re_show(pat, s): print re.compile(pat, re.S).sub("{\g<0>}", s),'\n' s =...
Parsing multilevel text list
I need to parse text lists: 1 List name 1 item 2 item 3 item 2 List name 1 item 2 item 3 item 3 List name 1 item 2 item 3 item I was trying to use regular expression to split first level list: import re def re_show(pat, s): print re.compile(pat, re.S).sub("{\g<0>}", s),'\n' s = ''' 1 List name 1 item 2 item 3 ...
[ "Do you have control over the list format? With just a little editing, you could turn that into config file format, and use the ConfigParser module.\nOtherwise, how about with a little recursion?\nfrom collections import defaultdict\n\ndef fill_data(data, key, sequence, pred):\n \"\"\"Recursively fill the data d...
[ 2, 1, 1, 0 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0001885314_parsing_python_regex.txt
Q: Python 2.6: reading data from a Windows Console application. (os.system?) I have a Windows console application that returns some text. I want to read that text in a Python script. I have tried reading it by using os.system, but it is not working properly. import os foo = os.system('test.exe') Assuming that test....
Python 2.6: reading data from a Windows Console application. (os.system?)
I have a Windows console application that returns some text. I want to read that text in a Python script. I have tried reading it by using os.system, but it is not working properly. import os foo = os.system('test.exe') Assuming that test.exe returns "bar", I want the variable foo to be set to "bar". But what happens...
[ "Please use subprocess\nimport subprocess\nfoo = subprocess.Popen('test.exe',stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n\nhttp://docs.python.org/library/subprocess.html#module-subprocess\n", "WARNING: This only works on UNIX systems.\nI find that subprocess is overkill when all you want is output to be captu...
[ 8, 2 ]
[]
[]
[ "console", "exe", "python", "windows" ]
stackoverflow_0001885776_console_exe_python_windows.txt
Q: Converting a list of lists to a tuple in Python I have a list of lists (generated with a simple list comprehension): >>> base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)] >>> base_lists [[1,1],[1,2],[1,3],[1,4],[1,5],[2,1],[2,2],[2,3],[2,4],[2,5]] I want to turn this entire list into a tuple contai...
Converting a list of lists to a tuple in Python
I have a list of lists (generated with a simple list comprehension): >>> base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)] >>> base_lists [[1,1],[1,2],[1,3],[1,4],[1,5],[2,1],[2,2],[2,3],[2,4],[2,5]] I want to turn this entire list into a tuple containing all of the values in the lists, i.e.: resulting_...
[ "tuple(x for sublist in base_lists for x in sublist)\n\nEdit: note that, with base_lists so short, the genexp (with unlimited memory available) is slow. Consider the following file tu.py:\nbase_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]\n\ndef genexp():\n return tuple(x for sublist in base_lists f...
[ 11, 5, 3, 2, 0 ]
[]
[]
[ "list_comprehension", "python", "python_itertools", "tuple_packing" ]
stackoverflow_0001884323_list_comprehension_python_python_itertools_tuple_packing.txt
Q: Use pyExcelerator to generate dynamic Excel file with Django. Ensure unique temporary filename I'd like to generate a dynamic Excel file on request from Django. The library pyExcelerator does this, but I haven't found any way to use the contents of the Excel file without generating a server-side temporary Excel fi...
Use pyExcelerator to generate dynamic Excel file with Django. Ensure unique temporary filename
I'd like to generate a dynamic Excel file on request from Django. The library pyExcelerator does this, but I haven't found any way to use the contents of the Excel file without generating a server-side temporary Excel file, reading it, using its contents and deleting it. The problem is that pyExcelerator only way to ex...
[ "pyExcelerator is unmaintained, but it has a fork, xlwt, which is maintained and has more features, including allowing you to save to any file-like object. This includes saving straight to a Django HttpResponse:\nfrom django.http import HttpResponse\nimport xlwt\n\ndef my_view(request):\n response = HttpResponse...
[ 11, 3 ]
[]
[]
[ "django", "excel", "pyexcelerator", "python", "temporary_files" ]
stackoverflow_0001886744_django_excel_pyexcelerator_python_temporary_files.txt
Q: Unicode filenames on python 2.6 under Mac OS X I'm using os.walk to create a list of all music files under a folder. Some of these filenames are non-ascii, for example: 01 空即是色.mp3 I'm using the mutagen library to parse metadata for this file, and it professes complete unicode support. The filename is being ret...
Unicode filenames on python 2.6 under Mac OS X
I'm using os.walk to create a list of all music files under a folder. Some of these filenames are non-ascii, for example: 01 空即是色.mp3 I'm using the mutagen library to parse metadata for this file, and it professes complete unicode support. The filename is being retrieved as unicode, and can be printed as unicode. Ho...
[ "Note that walk(dir) returns the filename without path. If you want to open the file, you must prepend dir:\nfor dirpath, dirnames, filenames in os.walk(dir):\n for filename in filenames:\n path = os.path.join(dirpath, filename)\n\n" ]
[ 2 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0001887215_python_unicode.txt
Q: IronPython examples I have heard IronPython for a long time, but never seen a real-life application using it. Do you provide some examples to see its power? Thanks. A: How did you miss Resolver Systems? Their Rsolver One spreadsheet application is IronPython.
IronPython examples
I have heard IronPython for a long time, but never seen a real-life application using it. Do you provide some examples to see its power? Thanks.
[ "How did you miss Resolver Systems? Their Rsolver One spreadsheet application is IronPython.\n" ]
[ 4 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0001887290_ironpython_python.txt
Q: How to compare datetime in Django? Suppose I have: ds = datetime.datetime.now dd = Entry.objects.get(pk=id).pub_date How to compare 2 objects above? I want to get the time difference between them. Please help me solve this problem. Thank you very much ! A: I am assuming that pub_date is a django.db.models.DateF...
How to compare datetime in Django?
Suppose I have: ds = datetime.datetime.now dd = Entry.objects.get(pk=id).pub_date How to compare 2 objects above? I want to get the time difference between them. Please help me solve this problem. Thank you very much !
[ "I am assuming that pub_date is a django.db.models.DateField, which means you can treat it as a datetime.date object.\nIf you convert them to the same type (either datetime.datetime or datetime.date) and subtract one from the other, you will get an instance of datetime.timedelta.\nAs you are using datetime.datetim...
[ 19 ]
[]
[]
[ "datetime", "django", "django_views", "python" ]
stackoverflow_0001887354_datetime_django_django_views_python.txt
Q: How to do a string replace in a urlencoded string I have a string like x = "http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json" If I do x % 10 that fails as there are %20f etc which are being treated as format strings, so I have to do ...
How to do a string replace in a urlencoded string
I have a string like x = "http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json" If I do x % 10 that fails as there are %20f etc which are being treated as format strings, so I have to do a string conactination. How can I use normal string rep...
[ "urldecode the string, do the formatting, and then urlencode it again:\nimport urllib\n\nx = \"http://query.yahooapis.com/v1/public/yql?q=select%20owner%2Curls%20from%20flickr.photos.info%20where%20photo_id%3D'%s'&format=json\"\ntmp = urllib.unquote(x)\ntmp2 = tmp % (foo, bar)\nx = urllib.quote(tmp2)\n\nAs one comm...
[ 5, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001886660_python_string.txt
Q: Access to class attributes by using a variable in Python? In PHP I can access class attributes like this: <?php // very simple :) class TestClass {} $tc = new TestClass{}; $attribute = 'foo'; $tc->{$attribute} = 'bar'; echo $tc->foo // should echo 'bar' How can I do this in Python? class TestClass() tc = TestClas...
Access to class attributes by using a variable in Python?
In PHP I can access class attributes like this: <?php // very simple :) class TestClass {} $tc = new TestClass{}; $attribute = 'foo'; $tc->{$attribute} = 'bar'; echo $tc->foo // should echo 'bar' How can I do this in Python? class TestClass() tc = TestClass attribute = 'foo' # here comes the magic? print tc.foo # shou...
[ "This question has been asked several times. You can use getattr to get the attribute by name:\nprint getattr(tc, 'foo')\n\nThis works for methods as well:\ngetattr(tc, 'methodname')(arg1, arg2)\n\nTo set an attribute by name use setattr\nsetattr(tc, 'foo', 'bar')\n\nTo check if an attribute exists use hasattr\nhas...
[ 3, 0 ]
[]
[]
[ "attributes", "python" ]
stackoverflow_0001887509_attributes_python.txt
Q: How to convert string to hexadecimal integer in Python? hi I get user argv from command line as follows: '0x000aff00' and I want python to treat it as hex directly... str = sys.argv[1] how is it possible? thanks! A: Try: i = int(sys.argv[1], 16) A: try: i = int(sys.argv[1], 16) except Exception,e: pri...
How to convert string to hexadecimal integer in Python?
hi I get user argv from command line as follows: '0x000aff00' and I want python to treat it as hex directly... str = sys.argv[1] how is it possible? thanks!
[ "Try: i = int(sys.argv[1], 16)\n", "try:\n i = int(sys.argv[1], 16)\nexcept Exception,e:\n print e\nelse:\n # carry on\n\n" ]
[ 7, 0 ]
[]
[]
[ "hex", "integer", "python" ]
stackoverflow_0001887392_hex_integer_python.txt
Q: Python setuptools custom configuration I'm packaging up a Python module, and I would like users to be able to build the module with some custom options. Specifically, the package will do some extra magic if you provide it with certain executables that it can use. Ideally, users would run setup.py install or setup....
Python setuptools custom configuration
I'm packaging up a Python module, and I would like users to be able to build the module with some custom options. Specifically, the package will do some extra magic if you provide it with certain executables that it can use. Ideally, users would run setup.py install or setup.py install --magic-doer=/path/to/executable....
[ "It seems you can... read this.\nExtract from article:\n\nCommands are simple class that derives from setuptools.Command, and define some minimum elements, which are:\n\ndescription: describe the command\nuser_options: a list of options\ninitialize_options(): called at startup\nfinalize_options(): called at the end...
[ 6 ]
[]
[]
[ "python", "setup.py" ]
stackoverflow_0001887641_python_setup.py.txt
Q: Convert Python byte to "unsigned 8 bit integer" I am reading in a byte array/list from socket. I want Python to treat the first byte as an "unsigned 8 bit integer". How is it possible to get its integer value as an unsigned 8 bit integer? A: Use the struct module. import struct value = struct.unpack('B', data[...
Convert Python byte to "unsigned 8 bit integer"
I am reading in a byte array/list from socket. I want Python to treat the first byte as an "unsigned 8 bit integer". How is it possible to get its integer value as an unsigned 8 bit integer?
[ "Use the struct module.\nimport struct\nvalue = struct.unpack('B', data[0])[0]\n\nNote that unpack always returns a tuple, even if you're only unpacking one item.\nAlso, have a look at this SO question.\n", "bytes/bytearray is a sequence of integers. If you just access an element by its index you'll have an integ...
[ 23, 10, 7 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001887506_python_python_3.x.txt
Q: python string as hex terminated with null I receive strings in their hex format, i.e. s = "0x0ff" or s = "0fd" how can I check whether the above type of strings are null terminated or not? thanks! A: Try s[-2:] == "00" A: Why would you care wether python strings are null terminated? If you want to check wether...
python string as hex terminated with null
I receive strings in their hex format, i.e. s = "0x0ff" or s = "0fd" how can I check whether the above type of strings are null terminated or not? thanks!
[ "Try\ns[-2:] == \"00\"\n\n", "Why would you care wether python strings are null terminated?\nIf you want to check wether the strings start by \"0x\" you can just use\nx.startswith(\"0x\")\n\nas x cannot be located anywhere else in a hexstring.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001887707_python_python_3.x.txt
Q: How to redirect complete output of a cron script I have a simple cronjob running every day at 18:35: 05 18 * * * ~/job.sh 2>&1 >> ~/job.log So the output of ~/job.sh should be written into ~/job.log. In job.sh, there are some echo commands and a few python scripts are executed, e.g.: echo 'doing xyz' python doXYZ...
How to redirect complete output of a cron script
I have a simple cronjob running every day at 18:35: 05 18 * * * ~/job.sh 2>&1 >> ~/job.log So the output of ~/job.sh should be written into ~/job.log. In job.sh, there are some echo commands and a few python scripts are executed, e.g.: echo 'doing xyz' python doXYZ.py Now, whatever output the python scripts produce, ...
[ "Arkaitz has the simplest solution. However, to see what's wrong with your snippet we need to go into the bash manual:\n\nNote that the order of redirections is significant. For example, the\n command\n ls > dirlist 2>&1\n\ndirects both standard output and standard error to the file dirlist,\n while the co...
[ 17, 4, 2, 1 ]
[]
[]
[ "cron", "python", "shell" ]
stackoverflow_0001887618_cron_python_shell.txt
Q: Is this control structure a code smell? This code seems to smell: result = None for item in list: if result is None: result = item.foo(args) else: if ClassFred.objects.get(arg1=result) < ClassFred.objects.get(arg1=item.foo(args)): result = item.foo(args) The smelliest part is t...
Is this control structure a code smell?
This code seems to smell: result = None for item in list: if result is None: result = item.foo(args) else: if ClassFred.objects.get(arg1=result) < ClassFred.objects.get(arg1=item.foo(args)): result = item.foo(args) The smelliest part is the utility of 'result'. Would anyone be kind ...
[ "L = list # 'list' is a poor variable name, use something else\nresult = min((n.foo(args) for n in L),\n key=lambda x: ClassFred.objects.get(arg1=x))\n# if you don't have to use arg1 as a named parameter:\nresult = min((n.foo(args) for n in L), key=ClassFred.objects.get)\n\nThe min function compares the...
[ 3, 1, 1, 1, 0 ]
[]
[]
[ "controls", "python", "structure" ]
stackoverflow_0001886002_controls_python_structure.txt
Q: Python hexadecimal comparison I got a problem I was hoping someone could help me figure out! I have a string with a hexadecimal number = '0x00000000' which means: 0x01000000 = apple 0x00010000 = orange 0x00000100 = banana All combinations with those are possible. i.e., 0x01010000 = apple & orange How can I...
Python hexadecimal comparison
I got a problem I was hoping someone could help me figure out! I have a string with a hexadecimal number = '0x00000000' which means: 0x01000000 = apple 0x00010000 = orange 0x00000100 = banana All combinations with those are possible. i.e., 0x01010000 = apple & orange How can I from my string determine what frui...
[ "Convert your string to an integer, by using the int() built-in function and specifying a base:\n>>> int('0x01010000',16)\n16842752\n\nNow, you have a standard integer representing a bitset. use &, | and any other bitwise operator to test individual bits.\n>>> value = int('0x01010000',16)\n>>> apple = 0x01000000\...
[ 21, 2, 0 ]
[]
[]
[ "hex", "python" ]
stackoverflow_0001888114_hex_python.txt
Q: How to join lists element-wise in Python? l1 = [4, 6, 8] l2 = [a, b, c] result = [(4,a),(6,b),(8,c)] How do I do that? A: The zip standard function does this for you: >>> l1 = [4, 6, 8] >>> l2 = ["a", "b", "c"] >>> zip(l1, l2) [(4, 'a'), (6, 'b'), (8, 'c')] If you're using Python 3.x, then zip returns a genera...
How to join lists element-wise in Python?
l1 = [4, 6, 8] l2 = [a, b, c] result = [(4,a),(6,b),(8,c)] How do I do that?
[ "The zip standard function does this for you:\n>>> l1 = [4, 6, 8]\n>>> l2 = [\"a\", \"b\", \"c\"]\n>>> zip(l1, l2)\n[(4, 'a'), (6, 'b'), (8, 'c')]\n\nIf you're using Python 3.x, then zip returns a generator and you can convert it to a list using the list() constructor:\n>>> list(zip(l1, l2))\n[(4, 'a'), (6, 'b'), (...
[ 12, 11, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001885300_list_python.txt
Q: give an active to class to active link I am writing a python website built on the back of the django framework, I am looking for a way to highlight the current link the user is on depening on what the URL, I thought doing some thing like this would work. What I have done is create a new application called nav and ...
give an active to class to active link
I am writing a python website built on the back of the django framework, I am looking for a way to highlight the current link the user is on depening on what the URL, I thought doing some thing like this would work. What I have done is create a new application called nav and built some templatetags, like so, from djan...
[ "Some things to check:\nIs the request object actually in your context? Are you passing it in specifically, or are you using a RequestContext?\nWhy are you defining regexes in your templatetags, rather than using the built-in reverse function to look them up in the urlconf? \nDo the regexes here actually match the ...
[ 0 ]
[]
[]
[ "django", "django_templates", "python", "templatetags" ]
stackoverflow_0001888519_django_django_templates_python_templatetags.txt
Q: Integration Testing for a Web App I want to do full integration testing for a web application. I want to test many things like AJAX, positioning and presence of certain phrases and HTML elements using several browsers. I'm seeking a tool to do such automated testing. On the other hand; this is my first time using ...
Integration Testing for a Web App
I want to do full integration testing for a web application. I want to test many things like AJAX, positioning and presence of certain phrases and HTML elements using several browsers. I'm seeking a tool to do such automated testing. On the other hand; this is my first time using integration testing. Are there any spec...
[ "If you need to do full testing including exploiting browser features like AJAX then I would recomend Selenium. Selenium launches a browser and controls it to run the tests.\nIt supports all the major platforms and browsers. Selenium itself is implemented in Java but that is not really an issue if it is being used ...
[ 12, 12, 6, 4, 2, 2, 1, 1, 0 ]
[]
[]
[ "automated_tests", "integration_testing", "perl", "python", "ruby" ]
stackoverflow_0001747772_automated_tests_integration_testing_perl_python_ruby.txt
Q: Simplifying small code example Lets pretend I have the following code. num1 = 33 num2 = 45 num3 = 76 lst = ['one', 'two', 'three'] for item in lst: if item == 'one': print num1 elif item == 'two': print num2 elif item == 'three': print num3 Is there a way to make this more ele...
Simplifying small code example
Lets pretend I have the following code. num1 = 33 num2 = 45 num3 = 76 lst = ['one', 'two', 'three'] for item in lst: if item == 'one': print num1 elif item == 'two': print num2 elif item == 'three': print num3 Is there a way to make this more elegant when there is no correlation be...
[ "You can of course use a dictionary, to look up the response:\nlst = ['one', 'two', 'three']\nresp = { 'one': num1, 'two': num2, 'three': num3 }\n\nfor item in lst:\n print resp[item]\n\nThis is still pretty static, though. Another approach would be object-orienting it, so you get to implement a function in the ob...
[ 5, 5, 4, 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001887690_python.txt
Q: Python twisted: where to start I am trying to start learning twisted for socket servers creation. I want to add some useful features (like auth, and maybe some other). Maybe someone can point me to a good tutorial which will help me to start (+ maybe some other ideas) A: Look here: Twisted Web in 60 seconds. Th...
Python twisted: where to start
I am trying to start learning twisted for socket servers creation. I want to add some useful features (like auth, and maybe some other). Maybe someone can point me to a good tutorial which will help me to start (+ maybe some other ideas)
[ "Look here: Twisted Web in 60 seconds. That's a group of blog posts describing step by step how to do lots of common stuff with Twisted, all written by Jean-Paul Calderone, the biggest contributor of Twisted. It's really where you should start.\nAfter that, look at the Twisted core documentation then refer to the A...
[ 73, 70 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0001888139_python_twisted.txt
Q: Am I supposed to use PyQT4 for programming cross-platform software in Python? So a user suggested getting PyQT. A quick Google gave me this: Link Is this GUI Library for pay? If my development environment is Ubuntu Linux, what should I download on that site. I have no idea. Please provide links if the site I provi...
Am I supposed to use PyQT4 for programming cross-platform software in Python?
So a user suggested getting PyQT. A quick Google gave me this: Link Is this GUI Library for pay? If my development environment is Ubuntu Linux, what should I download on that site. I have no idea. Please provide links if the site I provided is not correct to what I need. Thank you.
[ "You may want to look at PySide which is sponsored by Nokia, who own QT. It's also LGPL, which is a bit better of a license than the PyQT bindings. It's also a bit more pythonic in how it works. Unfortunately, it's new, so there isn't as much documentation. On their download page you can find information about ...
[ 10, 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "cross_platform", "python", "qt" ]
stackoverflow_0001774487_cross_platform_python_qt.txt
Q: Python memchached client library with CAS support I need to use gets and cas (check and set) commands of memcached from Python application. The only Python client library supporting them I found is Twisted. But Twisted requires quite different design of application, so it's not an option. Is there any other full-f...
Python memchached client library with CAS support
I need to use gets and cas (check and set) commands of memcached from Python application. The only Python client library supporting them I found is Twisted. But Twisted requires quite different design of application, so it's not an option. Is there any other full-featured (not listed on official page) Python library fo...
[ "I don't see pylibmc listed there, but I have no idea if it supports those commands you need (edit: it doesn't, sorry).\n/edit: if everything else fails, you could perhaps use this patch for python-libmemcached, which adds support for cas and gets. \n/edit: The latest git version of pylibmc supports cas and gets\n"...
[ 2 ]
[]
[]
[ "memcached", "python" ]
stackoverflow_0001887431_memcached_python.txt
Q: How to Sort Arrays in Dictionary? I'm currently writing a program in Python to track statistics on video games. An example of the dictionary I'm using to track the scores : ten = 1 sec = 9 fir = 10 thi5 = 6 sec5 = 8 games = { 'adom': [ten+fir+sec+sec5, "Ancient Domain of Mysteries"], 'nethack': [f...
How to Sort Arrays in Dictionary?
I'm currently writing a program in Python to track statistics on video games. An example of the dictionary I'm using to track the scores : ten = 1 sec = 9 fir = 10 thi5 = 6 sec5 = 8 games = { 'adom': [ten+fir+sec+sec5, "Ancient Domain of Mysteries"], 'nethack': [fir+fir+fir+sec+thi5, "Nethack"] ...
[ "How about something like this:\nscores = games.items()\nscores.sort(key = lambda key, value: value[0])\nreturn scores[:10]\n\nThis will return the first 10 items, sorted by the first item in the array.\nI'm not sure if this is what you want though, please update the question (and fix the example link) if you need ...
[ 3, 2, 0 ]
[]
[]
[ "arrays", "dictionary", "logic", "python", "sorting" ]
stackoverflow_0001888910_arrays_dictionary_logic_python_sorting.txt
Q: IBoutlet with PyObjC and Interface Builder I'm writing a simple OSX app using Python and PyObjC. I designed the settings dialog using Interface Builder and I use ibtool to compile it, then load it from Python. The problem is how to access the controls I have in this window from the Python code? I played around wit...
IBoutlet with PyObjC and Interface Builder
I'm writing a simple OSX app using Python and PyObjC. I designed the settings dialog using Interface Builder and I use ibtool to compile it, then load it from Python. The problem is how to access the controls I have in this window from the Python code? I played around with iPhone development a bit before and I remember...
[ "First, the use of Xcode or not has nothing to do with NIB loading (beyond making it more convenient).\nAs Ole said, you can use IB to manually add the outlet's you need to file's owner or to the custom object instances that you have in the NIB file. By doing so, it will all \"just work\".\nHowever, this statemen...
[ 4, 1 ]
[]
[]
[ "cocoa", "interface_builder", "pyobjc", "python" ]
stackoverflow_0001887102_cocoa_interface_builder_pyobjc_python.txt
Q: numpy : How to convert an array type quickly I find the astype() method of numpy arrays not very efficient. I have an array containing 3 million of Uint8 point. Multiplying it by a 3x3 matrix takes 2 second, but converting the result from uint16 to uint8 takes another second. More precisely : print time.clock(...
numpy : How to convert an array type quickly
I find the astype() method of numpy arrays not very efficient. I have an array containing 3 million of Uint8 point. Multiplying it by a 3x3 matrix takes 2 second, but converting the result from uint16 to uint8 takes another second. More precisely : print time.clock() imgarray = np.dot(imgarray, M)/255 prin...
[ "When you use imgarray = imgarray.astype('B'), you get a copy of the array, cast to the specified type. This requires extra memory allocation, even though you immediately flip imgarray to point to the newly allocated array.\nIf you use imgarray.view('uint8'), then you get a view of the array. This uses the same dat...
[ 26 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001888870_numpy_python.txt
Q: Sending the variable's content to my mailbox in Python? I have asked this question here about a Python command that fetches a URL of a web page and stores it in a variable. The first thing that I wanted to know then was whether or not the variable in this code contains the HTML code of a web-page: from google.appe...
Sending the variable's content to my mailbox in Python?
I have asked this question here about a Python command that fetches a URL of a web page and stores it in a variable. The first thing that I wanted to know then was whether or not the variable in this code contains the HTML code of a web-page: from google.appengine.api import urlfetch url = "http://www.google.com/" resu...
[ "for info on sending Content-Type header, see here: http://code.google.com/appengine/docs/python/urlfetch/overview.html#Request_Headers\n", "If you look at the Google App Engine documentation for the response object, the result of urlfetch.fetch() contains the member headers which contains the HTTP response heade...
[ 1, 1 ]
[]
[]
[ "content_type", "google_app_engine", "header", "python", "url" ]
stackoverflow_0001889912_content_type_google_app_engine_header_python_url.txt
Q: List of dictionaries, in a dictionary - in Python I have a case where I need to construct following structure programmatically (yes I am aware of .setdefault and defaultdict but I can not get what I want) I basically need a dictionary, with a dictionary of dictionaries created within the loop. At the beginning the...
List of dictionaries, in a dictionary - in Python
I have a case where I need to construct following structure programmatically (yes I am aware of .setdefault and defaultdict but I can not get what I want) I basically need a dictionary, with a dictionary of dictionaries created within the loop. At the beginning the structure is completely blank. structure sample (pleas...
[ "Example, that you've posted is not a valid python code, I could only imagine that you're trying to do something like this:\nself.rules[a] = [{b:{'f_expr': c, 'c_expr': d}}]\n\nthis way self.rules is a dictionary of a list of a dictionary of a dictionary. I bet there is more sane way to do this.\n", "rules = {}\...
[ 5, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "list", "nested", "python" ]
stackoverflow_0001889385_dictionary_list_nested_python.txt
Q: Setting Python path while developing library module I am developing a library and an application that uses the library in Python 2.6. I've placed a "mylib.pth" file in "site-packages" so that I can import mylib from within my application. I am using a DVCS so when I want to fix a bug or add a feature to the lib...
Setting Python path while developing library module
I am developing a library and an application that uses the library in Python 2.6. I've placed a "mylib.pth" file in "site-packages" so that I can import mylib from within my application. I am using a DVCS so when I want to fix a bug or add a feature to the library I make a branch of the repository and work within th...
[ "Is virtualenv what you're looking for? From the description:\n\nImagine you have an application that\n needs version 1 of LibFoo, but another\n application requires version 2. How\n can you use both these applications?\n If you install everything into\n /usr/lib/python2.4/site-packages (or\n whatever your p...
[ 4, 4, 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001889967_python.txt
Q: Response Code 202, Not a Qualified Error Code I'm working with an API which I post files to. However, when I receive the response, the HTTP status code is a 202. This is to be expected, but in addition the API will also respond with XML content. So in my try/except block urllib2.urlopen will result in a raised url...
Response Code 202, Not a Qualified Error Code
I'm working with an API which I post files to. However, when I receive the response, the HTTP status code is a 202. This is to be expected, but in addition the API will also respond with XML content. So in my try/except block urllib2.urlopen will result in a raised urllib2.HTTPError and destroying the XML content. try:...
[ "Edit\nBeing silly, I forgot to inspect the exception that is returned by urllib2. It features all of the properties I've been waxing on about for httplib. This should do the trick for you:\ntry:\n urllib2.urlopen(req)\nexcept urllib2.HTTPError, e:\n print \"Response code\",e.code # prints 404\n print \"Re...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0001890216_python.txt
Q: How to replace models.py in Django app in the production server I have a simple django app that is using only the admin. This is the model as is now in the server: from django.db import models class School(models.Model): school = models.CharField(max_length=200) def __unicode__(self): return s...
How to replace models.py in Django app in the production server
I have a simple django app that is using only the admin. This is the model as is now in the server: from django.db import models class School(models.Model): school = models.CharField(max_length=200) def __unicode__(self): return self.school class Lawyer(models.Model): first = models.CharField(...
[ "No, you cannot just replace models.py.\nYou need some kind of schema migration.\nIf you don't use a tool like django south, you'll have to do it manually.\nLook at http://www.sqlite.org/lang_altertable.html\nYou can use manage.py sqlall to see which SQL statements you need.\n", "Since you're using a sqlite datab...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "django", "python", "sqlite" ]
stackoverflow_0001889622_django_python_sqlite.txt
Q: Problem creating N*N*N list in Python I'm trying to create a 3-dimensional NNN list in Python, like such: n=3 l = [[[0,]*n]*n]*n Unfortunately, this does not seem to properly "clone" the list, as I thought it would: >>> l [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]...
Problem creating N*N*N list in Python
I'm trying to create a 3-dimensional NNN list in Python, like such: n=3 l = [[[0,]*n]*n]*n Unfortunately, this does not seem to properly "clone" the list, as I thought it would: >>> l [[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]] >>> l[0][0][0]=1 >>> l [[[1, ...
[ "The problem is that * n does a shallow copy of the list. A solution is to use nested loops, or try the numpy library.\n", "If you want to do numerical processing with 3-d matrix you are better of using numpy. It is quite easy:\n>>> import numpy\n>>> numpy.zeros((3,3,3), dtype=numpy.int)\narray([[[0, 0, 0],\n ...
[ 5, 4, 3, 2, 2 ]
[]
[]
[ "list", "mutable", "python" ]
stackoverflow_0001889080_list_mutable_python.txt
Q: Having models' declarations at two folders in Django How can you have model declarations at two different directories in Django? I have the model at the directory Code which contains "init.py", "models.py" and "admin.py". It is working properly alone. I want to have the directory History which has the model of the...
Having models' declarations at two folders in Django
How can you have model declarations at two different directories in Django? I have the model at the directory Code which contains "init.py", "models.py" and "admin.py". It is working properly alone. I want to have the directory History which has the model of the revisions of the given questions. I have the similar file...
[ "Since it sounds like both of your directories are Django apps, and assuming you've put both of them in your INSTALLED_APPS list in settings.py you can refer to them using a string without having to import:\n# in code/models.py\n\nclass Questions(models.Model):\n histories = models.ManyToManyField('history.MyHis...
[ 2, 0, 0 ]
[]
[]
[ "django", "import", "models", "python" ]
stackoverflow_0001891139_django_import_models_python.txt
Q: Python Exception Propagation I'm building a tool where as exceptions propagate upwards, new data about the context of the exception gets added to the exception. The issue is, by the time the exception gets to the top level, all of the extra context data is there, but only the very latest stack trace is shown. Is t...
Python Exception Propagation
I'm building a tool where as exceptions propagate upwards, new data about the context of the exception gets added to the exception. The issue is, by the time the exception gets to the top level, all of the extra context data is there, but only the very latest stack trace is shown. Is there an easy way to have an except...
[ "Python exceptions are a bit like java, there is a way to cause the exception to be rethrown without truncating the stack.\nJust use raise without an argument. The result it:\nTraceback (most recent call last):\n File \"./exc.py\", line 11, in <module>\n b()\n File \"./exc.py\", line 7, in b\n a()\n File \...
[ 37 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0001891572_exception_python.txt
Q: Creating an Python/py2app application that simply opens a terminal on launch? I've written a nice Python application that is basically an HTTP proxy for SMS modems, and I'd like to make it a double-clickable application on Macs. So far I've been including a .commmand file which is double-clickable, which basically...
Creating an Python/py2app application that simply opens a terminal on launch?
I've written a nice Python application that is basically an HTTP proxy for SMS modems, and I'd like to make it a double-clickable application on Macs. So far I've been including a .commmand file which is double-clickable, which basically consists of cd `dirname $0` (sleep 8;open http://127.0.0.1:8080/)& mac/slingshotsm...
[ "If you're looking for 'easy', try just giving your python script a .command suffix, and make sure it's executable. For example:\n#!/usr/bin/env python\n# file: hello.command\n\nprint 'hello world'\n\nIf you're looking for 'polished', then you probably want to learn about Launch Services, PyObjC, Interface Builder...
[ 2, 1, 0 ]
[]
[]
[ "macos", "py2app", "python" ]
stackoverflow_0001882644_macos_py2app_python.txt
Q: Big List Of Portability in Python I thought it would be a good idea to compile a list of things to watch out for when making a Python app portable. There are a lot of subtle 'gotchas' in portability that are only discovered through experience and thorough testing; there needs to be some sort of list addressing the...
Big List Of Portability in Python
I thought it would be a good idea to compile a list of things to watch out for when making a Python app portable. There are a lot of subtle 'gotchas' in portability that are only discovered through experience and thorough testing; there needs to be some sort of list addressing the more common ones. Please post one gotc...
[ "If you deal with binary file formats in Python, note that the struct and array modules uses machine dependent size and endianness. struct can be used portably by always using < or > in the format string. array can't. It will probably be portable for arrays of bytes, but the documentation makes no such guarantee.\n...
[ 4, 3, 2, 2, 2, 1, 1 ]
[]
[]
[ "portability", "python" ]
stackoverflow_0001883118_portability_python.txt
Q: How do derived class constructors work in python? I have the following base class: class NeuralNetworkBase: def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs): self.inputLayer = numpy.zeros(shape = (numberOfInputs)) self.hiddenLayer = numpy.zeros(shape = (numberOfHiddenN...
How do derived class constructors work in python?
I have the following base class: class NeuralNetworkBase: def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs): self.inputLayer = numpy.zeros(shape = (numberOfInputs)) self.hiddenLayer = numpy.zeros(shape = (numberOfHiddenNeurons)) self.outputLayer = numpy.zeros(shape =...
[ "\nDoes python call by default the base\n class constructor's when running the\n derived class' one? Do I have to\n implicitly do it inside the derived\n class constructor?\n\nNo and yes.\nThis is consistent with the way Python handles other overridden methods - you have to explicitly call any method from the b...
[ 38, 7 ]
[]
[]
[ "base_class", "constructor", "derived_class", "python" ]
stackoverflow_0001892269_base_class_constructor_derived_class_python.txt
Q: Where to put a Django template's dependent files? My Django templates use a lot of related stuff: images, style sheets, etc. Where should I put these file, or how should I refer to them in the template itself? For now I'm using the development server. I know it's a really common thing, but I can't really figure it...
Where to put a Django template's dependent files?
My Django templates use a lot of related stuff: images, style sheets, etc. Where should I put these file, or how should I refer to them in the template itself? For now I'm using the development server. I know it's a really common thing, but I can't really figure it out.
[ "I put them inside a folder named static, which is in the web project's top level folder. \nExample: \n\n/static/img/\n /static/js/\n /static/css/\n /templates/\n urls.py\n settings.py \n\nI then have the following rule in my urls.py file:\n(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_ro...
[ 5, 2, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0001891884_django_django_templates_python.txt
Q: What does "result.status_code == 200" in Python mean? In this little piece of code, what is the fourth line all about? from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: doSomethingWithResult(result.content) A: It's a HTTP stat...
What does "result.status_code == 200" in Python mean?
In this little piece of code, what is the fourth line all about? from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: doSomethingWithResult(result.content)
[ "It's a HTTP status code, it means \"OK\" (EG: The server successfully answered the http request).\nSee a list of them here on wikipedia\n", "Whoever wrote that should have used a constant instead of a magic number. The httplib module has all the http response codes.\nE.g.:\n>>> import httplib\n>>> httplib.OK\n20...
[ 16, 8, 6 ]
[]
[]
[ "http", "python" ]
stackoverflow_0001892161_http_python.txt
Q: Web.py on shared hosting I just built a small app with the very cool and minimalistic web.py. I am using a cheap shared hosting package (at WebFaction) and have installed web.py via virtualenv. I cannot use the system python since I need additional packages which I'm not allowed to install into the system python....
Web.py on shared hosting
I just built a small app with the very cool and minimalistic web.py. I am using a cheap shared hosting package (at WebFaction) and have installed web.py via virtualenv. I cannot use the system python since I need additional packages which I'm not allowed to install into the system python. So now I start my app with ...
[ "Is there a reason you're not using fastcgi? That's probably considerably better than trying to use some high-numbered port, particularly since your webhost may not be very happy about that at all. There are a few notes on doing that (on dreamhost, but it should be similar for you) in this post:\nhttp://thefire.us/...
[ 2 ]
[]
[]
[ "performance", "python", "web.py" ]
stackoverflow_0001892805_performance_python_web.py.txt
Q: sending http request to apache through a python script All, How do we send a http request through a python script.which will login and in turn call another link? Thanks. A: I find that Urllib2 suffices in most cases. It has great support for passwords, authentication and cookies. Cookielib might help too. A:...
sending http request to apache through a python script
All, How do we send a http request through a python script.which will login and in turn call another link? Thanks.
[ "I find that Urllib2 suffices in most cases. It has great support for passwords, authentication and cookies. Cookielib might help too.\n", "Have you looked at httplib? urllib may also be worth looking at as it is a slightly higher level interface.\n" ]
[ 1, 0 ]
[]
[]
[ "httprequest", "python" ]
stackoverflow_0001892958_httprequest_python.txt
Q: Get window title with python? I'm trying to write a python program that checks every X seconds if the 'window title' for 'last.fm' (http://www.last.fm/download) changed, if it did (or it's the first time I run the program) it should use use the string captured from the window title to search for the song's lyrics ...
Get window title with python?
I'm trying to write a python program that checks every X seconds if the 'window title' for 'last.fm' (http://www.last.fm/download) changed, if it did (or it's the first time I run the program) it should use use the string captured from the window title to search for the song's lyrics and display them to the user. I'm ...
[ "You can use the wmctrl utility through the subprocess module. You can type wmctrl -l into a terminal and see the output you can get from it.\n", "I think by using a automation framework you may be able to achieve this as a subset.\ne.g. try dogtail(https://fedorahosted.org/dogtail/), it can focus on windows by n...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "kde_plasma", "python" ]
stackoverflow_0001541784_kde_plasma_python.txt
Q: Basic Python Numbers Why does 0.1 + 0.1 + 0.1 - 0.3 evaluate to 5.5511151231257827e-17 in Python? A: Because that's how floating point numbers work. If you want precise numbers, use the decimal module. If you want to use floating point numbers, you have to remember to round them to a specific precision when you ...
Basic Python Numbers
Why does 0.1 + 0.1 + 0.1 - 0.3 evaluate to 5.5511151231257827e-17 in Python?
[ "Because that's how floating point numbers work. If you want precise numbers, use the decimal module. If you want to use floating point numbers, you have to remember to round them to a specific precision when you are displaying them.\n>>> print '%.2f' % (0.1+0.1+0.1-0.3,)\n0.00\n\n", "This is a problem with float...
[ 15, 7, 4, 3, 2, 0 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0001893094_floating_point_python.txt
Q: How to implement a stdin, stdout wrapper? I have an interactive program that runs stdin and stdout. I need to create wrapper that will send X to it's stdin, check that it prints Y and then redirects wrapper's stdin and stdout to program's stdin and stdout just like program would be executed directly. How to implem...
How to implement a stdin, stdout wrapper?
I have an interactive program that runs stdin and stdout. I need to create wrapper that will send X to it's stdin, check that it prints Y and then redirects wrapper's stdin and stdout to program's stdin and stdout just like program would be executed directly. How to implement this ? X and Y can be hardcoded. Bash? Pyth...
[ "Expect is made for automating the running of other programs - essentially you write something like, in plain text,\nStart this program. When it prints out the word \"username\", send it my username. When it sends \"password\", send it my password.\nIt's really great for driving other programs.\n", "Assuming X an...
[ 3, 1, 0, 0 ]
[]
[]
[ "bash", "python", "stdin", "stdout", "wrapper" ]
stackoverflow_0001890803_bash_python_stdin_stdout_wrapper.txt
Q: Why import urlfetch from Google App Engines? Here in Google App Engines I got this code that would help fetch an HTML code of any web page by its URL: from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: doSomethingWithResult(result.con...
Why import urlfetch from Google App Engines?
Here in Google App Engines I got this code that would help fetch an HTML code of any web page by its URL: from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) if result.status_code == 200: doSomethingWithResult(result.content) I don't understand one thing here (among ma...
[ "Python has libraries such as urllib and httplib for fetching URLs, but on App Engine, all requests must go through the custom urlfetch library. App Engine includes stubs for urllib and httplib that cause them to use urlfetch internally, but if you have a choice, using urlfetch directly is more efficient and flexib...
[ 17, 6 ]
[]
[]
[ "google_app_engine", "import", "python", "urlfetch" ]
stackoverflow_0001893012_google_app_engine_import_python_urlfetch.txt
Q: Use Python to extract ListView items from another application I have an application with a ListView ('SysListView32') control, from which I would like to extract data. The control has 4 columns, only textual data. I have been playing around the following lines (found online somewhere): VALUE_LENGTH = 256 bufferlen...
Use Python to extract ListView items from another application
I have an application with a ListView ('SysListView32') control, from which I would like to extract data. The control has 4 columns, only textual data. I have been playing around the following lines (found online somewhere): VALUE_LENGTH = 256 bufferlength_int=struct.pack('i', VALUE_LENGTH) count = win32gui.SendMessage...
[ "Well, it turns out I was wrong on several points there. However it is possible to do by allocating memory inside the target process, constructing the required struct (LVITEM) there, sending the message and reading back the result from the buffer allocated in said process.\nFor the sake of completeness, I attach a ...
[ 7, 1 ]
[]
[]
[ "listview", "python", "pywin32", "syslistview32" ]
stackoverflow_0001872480_listview_python_pywin32_syslistview32.txt
Q: How to override ord behaivour in Python for str childs? I have this class: class STR(str): def __int__(self): return 42 If i use it in the promt like this: >>> a=STR('8') >>> ord(a) 56 >>> int(a) 42 >>> chr(a) '*' that's the behaivour. I'd like to ord(a) be 42. How can I do it? Which method should ...
How to override ord behaivour in Python for str childs?
I have this class: class STR(str): def __int__(self): return 42 If i use it in the promt like this: >>> a=STR('8') >>> ord(a) 56 >>> int(a) 42 >>> chr(a) '*' that's the behaivour. I'd like to ord(a) be 42. How can I do it? Which method should I override in the str class? Is all this documented anywhere?...
[ "Here's the C source for Python's builtin ord from the current SVN revision of bltinmodule.c:\nstatic PyObject *\nbuiltin_ord(PyObject *self, PyObject* obj)\n{\n long ord;\n Py_ssize_t size;\n\n if (PyString_Check(obj)) {\n size = PyString_GET_SIZE(obj);\n if (size == 1) {\n ord = ...
[ 3, 2, 0, 0 ]
[]
[]
[ "overriding", "python", "string" ]
stackoverflow_0001893816_overriding_python_string.txt
Q: Why am I getting a file permission error with Python I am working with a shared hosting environment which as well as other things supports Python. I have followed the examples and deployed my cgi file and then through chmod, gave it Read and Execute Permissions to the world and then Read, Write and Execute to the...
Why am I getting a file permission error with Python
I am working with a shared hosting environment which as well as other things supports Python. I have followed the examples and deployed my cgi file and then through chmod, gave it Read and Execute Permissions to the world and then Read, Write and Execute to the owner. The code is simply this: #!/usr/bin/python # Requ...
[ "the account the webserver is running as doesn't have privileges to execute the script, or a directory in the path leading to it.\n", "\nMake sure the python location is really /usr/bin/python\nGive read & execute permissions to all, and write permission to owner: chmod 755 file.py\n\nEDIT: are you getting the er...
[ 8, 3, 1, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0001893959_linux_python.txt
Q: Python random and int to string question I am using this line of code to generate a random list of integers: random.sample(range(2000), 100) With this code i know i wont have double value's with my result. Is their maybe a faster way to achieve the same results? Now i actually have to convert these int to string....
Python random and int to string question
I am using this line of code to generate a random list of integers: random.sample(range(2000), 100) With this code i know i wont have double value's with my result. Is their maybe a faster way to achieve the same results? Now i actually have to convert these int to string. Whats the fastest way to do this? Thanks
[ "Use xrange instead of range:\nlst = random.sample(xrange(10**9), 100)\n\nTo convert to a list of strings:\nstrings = map(str, lst)\n\nAs one string:\ns = ''.join(strings)\n\n", "random.sample chooses integers from the list without replacement. If you are trying to avoid duplicates then what you are doing is the ...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0001893867_python_random.txt
Q: Color a Button after subprocess has finished I have a Tk python program that creates a list of python files in the current directory and generates a button for each of them. When you click a button the corresponding python program is launched via subprocess in a new gnome-terminal. I'd like to switch the button's ...
Color a Button after subprocess has finished
I have a Tk python program that creates a list of python files in the current directory and generates a button for each of them. When you click a button the corresponding python program is launched via subprocess in a new gnome-terminal. I'd like to switch the button's color to red after the subprocess has finished exe...
[ "There are two questions here: what command line to use to launch a Python program in gnome-terminal, and how to use subprocess in a Tkinter app. I only know about the latter.\nsubprocess.Popen returns immediately, which is why the button is turning red immediately. I think you probably need to make a list of which...
[ 1, 1 ]
[]
[]
[ "gnome", "python", "subprocess", "tk_toolkit" ]
stackoverflow_0001893629_gnome_python_subprocess_tk_toolkit.txt
Q: csv2json.py error I am trying to run the script csv2json.py in the Command Prompt, but I get this error: C:\Users\A\Documents\PROJECTS\Django\sw2>csv2json.py csvtest1.csv wkw1.Lawyer Converting C:\Users\A\Documents\PROJECTS\Django\sw2csvtest1.csv from CSV to JSON as C:\Users\A\Documents\PROJECTS\Django\sw2csvtest...
csv2json.py error
I am trying to run the script csv2json.py in the Command Prompt, but I get this error: C:\Users\A\Documents\PROJECTS\Django\sw2>csv2json.py csvtest1.csv wkw1.Lawyer Converting C:\Users\A\Documents\PROJECTS\Django\sw2csvtest1.csv from CSV to JSON as C:\Users\A\Documents\PROJECTS\Django\sw2csvtest1.csv.json Traceback (m...
[ "from os import path\nin_file = path.join(dirname(__file__), input_file_name )\nout_file = path.join(dirname(__file__), input_file_name + \".json\" )\n[...]\n\n", "+ is used incorrectly here, the proper way to combine directory name and file name is using os.path.join(). But there is no need to combine directory ...
[ 1, 1, 0 ]
[]
[]
[ "csv", "django", "json", "python" ]
stackoverflow_0001894099_csv_django_json_python.txt
Q: setting XML value using xmlrpc & python I need to set the value of a field in an XML file which exists on a remote Linux box. How do I find out which port I should connect to ? But even a proper ping is not happening: import xmlrpclib server = xmlrpclib.ServerProxy('http://10.77.21.240:9000') print server.ping() ...
setting XML value using xmlrpc & python
I need to set the value of a field in an XML file which exists on a remote Linux box. How do I find out which port I should connect to ? But even a proper ping is not happening: import xmlrpclib server = xmlrpclib.ServerProxy('http://10.77.21.240:9000') print server.ping() print "I'm in hurray" bUT instead I got: Tr...
[ "A couple of things to try / think about:\n\nGo to a command prompt on the remote host and type \"netstat -nap | grep 9000\". If you don't get back something interesting it means that nothing is running at port 9000.\n\nYou show the remote host at 10.77.21.240. This is an unroutable address on the net (AKA Private ...
[ 2 ]
[]
[]
[ "python", "xml", "xml_rpc" ]
stackoverflow_0001889313_python_xml_xml_rpc.txt
Q: Write a data string to a NumPy character array? I want to write a data string to a NumPy array. Pseudocode: d = numpy.zeros(10, dtype = numpy.character) d[1:6] = 'hello' Example result: d= array(['', 'h', 'e', 'l', 'l', 'o', '', '', '', ''], dtype='|S1') How can this be done most naturally and efficien...
Write a data string to a NumPy character array?
I want to write a data string to a NumPy array. Pseudocode: d = numpy.zeros(10, dtype = numpy.character) d[1:6] = 'hello' Example result: d= array(['', 'h', 'e', 'l', 'l', 'o', '', '', '', ''], dtype='|S1') How can this be done most naturally and efficiently with NumPy? I don't want for loops, generators, o...
[ "Just explicitly make your text a list (rather than that it is iterable from Python) and NumPy will understand it automatically:\n>>> text = 'hello'\n>>> offset = 1\n>>> d[offset:offset+len(text)] = list(text)\n>>> d\n\narray(['', 'h', 'e', 'l', 'l', 'o', '', '', '', ''],\n dtype='|S1')\n\n", "There's little...
[ 3, 2, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001759208_numpy_python.txt
Q: How does incr work with expiry times? In memcached (appengine api implementation), how does expiration interact with incr()? There isn't a time argument for incr(), but what happens if I add the key with another call rather than using the initial_value param, like so: memcache.add('testcounter', 0, time=60*90) ...
How does incr work with expiry times?
In memcached (appengine api implementation), how does expiration interact with incr()? There isn't a time argument for incr(), but what happens if I add the key with another call rather than using the initial_value param, like so: memcache.add('testcounter', 0, time=60*90) newcnt = memcache.incr('testcounter') wil...
[ "In the memcache overview of GAE they say:\n\"The app can provide an expiration time when a value is stored, as either a number of seconds relative to when the value is added, or as an absolute Unix epoch time in the future (a number of seconds from midnight January 1, 1970). The value will be evicted no later than...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "memcached", "python" ]
stackoverflow_0001890682_google_app_engine_memcached_python.txt
Q: Processing output from cmdline via a Python script I'm trying to use the subprocess module with Python 2.6 in order to run a command and get its output. The command is typically ran like this: /usr/local/sbin/kamctl fifo profile_get_size myprofile | awk -F ':: ' '{print $2}' What's the best way to use the subproc...
Processing output from cmdline via a Python script
I'm trying to use the subprocess module with Python 2.6 in order to run a command and get its output. The command is typically ran like this: /usr/local/sbin/kamctl fifo profile_get_size myprofile | awk -F ':: ' '{print $2}' What's the best way to use the subprocess module in my script to execute that command with tho...
[ "Do you want the output, the return value (AKA status code), or both?\nIf the amount of data emitted by the pipeline on stdout and/or stderr is not too large, it's pretty simple to get \"all of the above\":\nimport subprocess\n\ns = \"\"\"/usr/local/sbin/kamctl fifo profile_get_size myprofile | awk -F ':: ' '{print...
[ 4, 2 ]
[]
[]
[ "process", "python", "scripting" ]
stackoverflow_0001894325_process_python_scripting.txt
Q: Should Pylons' development.ini be checked in? I'm learning about Pylons and I've read a few tutorials, but none of them have addressed collaboration practices. Starting on a practice project. I'd like to keep my code in a revision-control system (Git, specifically) as if it were an open-source project with multip...
Should Pylons' development.ini be checked in?
I'm learning about Pylons and I've read a few tutorials, but none of them have addressed collaboration practices. Starting on a practice project. I'd like to keep my code in a revision-control system (Git, specifically) as if it were an open-source project with multiple developers, in order to practice that aspect of ...
[ "You could check it in as sample.ini for example so that everyone can copy to their own development.ini and modify as needed\n", "On a team development, we make an effort to ensure everyone has a common development environment, or we make adjustments to things (like database URLs) to allow people on different env...
[ 2, 2, 0, 0 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0001886192_pylons_python.txt
Q: Is Pylons enterprise-ready? I am a developer who is looking for an Enterprise-ready web application framework for Python. My main concern is long-term support, extensive feature set and reliability. I have been experimenting with Pylons and after my horrendous experience with Ruby on Rails on Windows where I even ...
Is Pylons enterprise-ready?
I am a developer who is looking for an Enterprise-ready web application framework for Python. My main concern is long-term support, extensive feature set and reliability. I have been experimenting with Pylons and after my horrendous experience with Ruby on Rails on Windows where I even had to compile my own Postgres dr...
[ "When it comes to enterprise ready, I'm not sure how much more ready a stack using Pylons with SQLAlchemy can be in the Python world. You're ready for massive legacy databases with crazy schemas (totally common in large corporate worlds), something where Django just falls apart at the seams. Sure, in Django, you co...
[ 39, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "pylons", "python", "sqlalchemy", "web_applications" ]
stackoverflow_0001044667_pylons_python_sqlalchemy_web_applications.txt
Q: variable name introspection in Python Is it possible to dynamically determine the name of a variable in Python? For example, I sometimes have the following situation: name = foo if bar else baz type = alpha or bravo D = { "name": name, "type": type } It would be nice if duplication there could be reduced...
variable name introspection in Python
Is it possible to dynamically determine the name of a variable in Python? For example, I sometimes have the following situation: name = foo if bar else baz type = alpha or bravo D = { "name": name, "type": type } It would be nice if duplication there could be reduced with something like D = makedict(name, typ...
[ "In the general case, you cannot deduce the name from a value (there might be no name, there might be multiple ones, etc); when you call your hypothetical makedict(name), the value of name is what makedict receives, so (again, in the general case) it cannot discern what name (if any) the value came from. You could ...
[ 11, 4, 2, 2 ]
[]
[]
[ "metaprogramming", "python" ]
stackoverflow_0001894591_metaprogramming_python.txt
Q: Scaling an image to its parent button size in GTK? I have a GTK layout with a widget on the left of an HBox deciding the maximum height I want, and a VBox on the right containing three buttons, each containing only an image and no text. The images are a GTK stock icon, and so have the stock storage type. Using exp...
Scaling an image to its parent button size in GTK?
I have a GTK layout with a widget on the left of an HBox deciding the maximum height I want, and a VBox on the right containing three buttons, each containing only an image and no text. The images are a GTK stock icon, and so have the stock storage type. Using expand=True, fill=True packing the buttons without images a...
[ "There's no way to automatically do you want you want. You might want to subclass gtk.Image and in your subclass, scale a pixbuf to your widget's allocation size. The advantage of this is that you'll have a reusable widget and you'll be able to have it resize your image on the fly.\nThe downside is that you'll have...
[ 2, 1 ]
[]
[]
[ "gtk", "pygtk", "python", "user_interface" ]
stackoverflow_0001851862_gtk_pygtk_python_user_interface.txt
Q: How best to hold 1000 different data series using TimeSeries module in Python? I want to create a massive TimeSeries object which will hold 1000 different financial markets data series, each storing 1500 daily-data points. I'm quite new to the TimeSeries module and am a little confused as to how I would best go ab...
How best to hold 1000 different data series using TimeSeries module in Python?
I want to create a massive TimeSeries object which will hold 1000 different financial markets data series, each storing 1500 daily-data points. I'm quite new to the TimeSeries module and am a little confused as to how I would best go about it. So a few basic questions: 1) Should I use a huge numpy array of 1000x1500 an...
[ "1) i once implemented a pagerank algorithm for a small set (~10K) of linked documents, therefore in during the calculation a 10Kx10K matrix had to be handled, for which the numpy array implementation was - as i recall - blazingly fast.\n2) imho storing metadata like series name externally does not hurt that much ....
[ 1, 0 ]
[]
[]
[ "finance", "numpy", "python" ]
stackoverflow_0001894981_finance_numpy_python.txt
Q: What are the various popularity metrics and sites for programming languages such as Ruby, Python, Java, etc? What are the various sites that offer metrics that compare Ruby, Python, Perl, Smalltalk etc. What are their respective metrics? Do any of them control or account for the time that Rails was introduced, and...
What are the various popularity metrics and sites for programming languages such as Ruby, Python, Java, etc?
What are the various sites that offer metrics that compare Ruby, Python, Perl, Smalltalk etc. What are their respective metrics? Do any of them control or account for the time that Rails was introduced, and/or the adoption rates for various languages? Will someone please help me close this question? Clearly it was not ...
[ "I don't mean to be nasty but what you are saying sounds like this to me: \"I enjoy programming in Ruby and really don't want to learn another technology. Is there a site that can tell me that Ruby is not going away anytime soon to put my mind at ease?\".\nThere is nothing wrong with that attitude but you have to b...
[ 6, 4, 2, 1, 1, 1, 0 ]
[]
[]
[ "asp.net", "c#", "python", "ruby", "smalltalk" ]
stackoverflow_0001892254_asp.net_c#_python_ruby_smalltalk.txt
Q: Django loaddata ValidationError This thread got too confusing (for me) so I am asking the question again. I could not make the csv2json.py script mentioned in the original question work. I am just trying to find a way to import data to sqlite3 database. Here's the model I am working with: from django.db import mod...
Django loaddata ValidationError
This thread got too confusing (for me) so I am asking the question again. I could not make the csv2json.py script mentioned in the original question work. I am just trying to find a way to import data to sqlite3 database. Here's the model I am working with: from django.db import models class School(models.Model): ...
[ "\n(I'll fix the duplicate \"school\" later.)\n\nActually, that is your problem. The second definition of school as a foreign key will require it to be an integer, thus the error.\nYou can confirm this by dumping the schema of your table with \n\nsqlite3 <database-file> '.schema wkw2_Lawyer'\n\n" ]
[ 2 ]
[]
[]
[ "csv", "django", "json", "python" ]
stackoverflow_0001894628_csv_django_json_python.txt
Q: How to pass an instance's reference in a method? I have the following Bird definition: class Bird: def __init__(self, swarm, position = None): if (swarm == None): raise ValueError("swarm variable should not be None!") if (not(type(swarm)).__name__ == 'ParticleSwarmOptimization'): ...
How to pass an instance's reference in a method?
I have the following Bird definition: class Bird: def __init__(self, swarm, position = None): if (swarm == None): raise ValueError("swarm variable should not be None!") if (not(type(swarm)).__name__ == 'ParticleSwarmOptimization'): raise TypeError("swarm variable must be of ...
[ "use:\nassert isinstance(swarm, ParticleSwarmOptimization)\n\nThe culture of Python is to not do these sorts of defensive checks, instead to simply use the variable. If it is of the wrong type, an exception will eventually be raised.\n", "Other people have mentioned the correct way to do this, however the reason...
[ 4, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001895501_python.txt
Q: Emacs: Pymacs not loading ropemacs with Carbon Emacs I'm attempting to use Pymacs with rope/ropemacs for flymake syntax checking as described here: http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/ When I start Carbon Emacs "normally" it throws the error: error: Pymacs loading r...
Emacs: Pymacs not loading ropemacs with Carbon Emacs
I'm attempting to use Pymacs with rope/ropemacs for flymake syntax checking as described here: http://www.enigmacurry.com/2009/01/21/autocompleteel-python-code-completion-in-emacs/ When I start Carbon Emacs "normally" it throws the error: error: Pymacs loading ropemacs...failed I had this working on OSX 10.5 with Carbo...
[ "Chances are it is a path problem. When you start an emacs from the terminal, your PATH environment variable presumably includes the MacPorts bin directory /opt/local/bin because presumably you modified one of your shell profiles, probably .bash_profile, to include that directory on PATH.\nBut when you launch an a...
[ 1 ]
[]
[]
[ "emacs", "flymake", "pymacs", "python", "ropemacs" ]
stackoverflow_0001895459_emacs_flymake_pymacs_python_ropemacs.txt
Q: String representation of arrays in python Is there anything that performs the following, in python? Or will I have to implement it myself? array = [0, 1, 2] myString = SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT(array) print myString which prints (0, 1, 2) Thanks A: You're in luck, Python has a function for thi...
String representation of arrays in python
Is there anything that performs the following, in python? Or will I have to implement it myself? array = [0, 1, 2] myString = SOME_FUNCTION_THAT_TAKES_AN_ARRAY_AS_INPUT(array) print myString which prints (0, 1, 2) Thanks
[ "You're in luck, Python has a function for this purpose exactly. It's called join.\nprint \"(\" + \", \".join(array) + \")\"\n\nIf you're familiar with PHP, join is similar to implode. The \", \" above is the element separator, and can be replaced with any string. For example,\nprint \"123\".join(['a','b','c'])\n\n...
[ 5, 5, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001895539_python.txt
Q: How to filter data from a file using Python? I'm trying to filter certain data from an HTML file. For example, the HTML file is as follows: <tr><td valign="top"><img src="/icons/unknown.gif" alt="[ ]">software_0.1-0.log</td><td align="right">17-Nov-2009 13:46 </td><td align="right">186K</td></tr> I need to ext...
How to filter data from a file using Python?
I'm trying to filter certain data from an HTML file. For example, the HTML file is as follows: <tr><td valign="top"><img src="/icons/unknown.gif" alt="[ ]">software_0.1-0.log</td><td align="right">17-Nov-2009 13:46 </td><td align="right">186K</td></tr> I need to extract the software_0.1-0 part as well as the 17-Nov...
[ "It's quite easy with BeautifulSoup:\nhtml = '''<tr><td valign=\"top\"><img src=\"/icons/unknown.gif\" alt=\"[ ]\">software_0.1-0.log</td><td align=\"right\">17-Nov-2009 13:46 </td><td align=\"right\">186K</td></tr>'''\n\nimport BeautifulSoup\nsoup = BeautifulSoup.BeautifulSoup(html)\nprint soup.td.next.next\npr...
[ 6, 2, 0, 0 ]
[]
[]
[ "filter", "parsing", "python" ]
stackoverflow_0001894711_filter_parsing_python.txt
Q: How can I create a regular expression in Python? I'm trying to create regular expressions to filter certain text from a text file. What I want to filter has this format: word_*_word.word So for example, I would like the python code every match. Sample results would be: program1_0.0-1_log.build program2_0.1-3_log....
How can I create a regular expression in Python?
I'm trying to create regular expressions to filter certain text from a text file. What I want to filter has this format: word_*_word.word So for example, I would like the python code every match. Sample results would be: program1_0.0-1_log.build program2_0.1-3_log.build How can I do this? Thanks a lot for your help
[ "Try something like this:\nr'[a-zA-Z0-9]+_[^_]+_[a-zA-Z0-9]+\\.[a-zA-Z0-9]+'\n\n", "Looks like you want to use a pattern such as r'\\w+_.*_\\w+\\.\\w+' -- assuming that * you have does stand for \"zero or more totally arbitrary characters\" (if not, then the .* part in the middle needs to be changed accordingly)....
[ 3, 3, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001895026_python_regex.txt
Q: Persistent MySQL connections in Python PHP provides mysql_connect() and mysql_pconnect() which allow creating both temporary and persistent database connections. Is there a similar functionality in Python? The environment on which this will be used is lighttpd server with FastCGI. Thank you! A: If you're using F...
Persistent MySQL connections in Python
PHP provides mysql_connect() and mysql_pconnect() which allow creating both temporary and persistent database connections. Is there a similar functionality in Python? The environment on which this will be used is lighttpd server with FastCGI. Thank you!
[ "If you're using FastCGI, there's no need for \"persistent connections\", because if you create a connection it is by default persistent, since FastCGI python isn't request based, but constantly running.\nThis is how FastCGI works in python, to put it short:\n1. Run startup code\n2. Run request function\n3. Wait fo...
[ 5, 0 ]
[]
[]
[ "mysql", "python", "web_services" ]
stackoverflow_0001895089_mysql_python_web_services.txt
Q: Imports with Pydev/Eclipse I'm working with the interactive console in eclipse, and reload does not show updated functions in my code. My code was : def func1(): return 1 def func2(): return 2 but when I changed it to def afunc1(): return 1 def func2(): return 2 def func1(): ...
Imports with Pydev/Eclipse
I'm working with the interactive console in eclipse, and reload does not show updated functions in my code. My code was : def func1(): return 1 def func2(): return 2 but when I changed it to def afunc1(): return 1 def func2(): return 2 def func1(): return 3 and ran imp.rel...
[ "Turns out, eclipse was not saving the file (or not saving it to the correct location) when I hit ctl-s. To get it to work, I had to right click the file name in the Package Explorer and select open with PyDev and save it under that\n" ]
[ 0 ]
[]
[]
[ "eclipse", "import", "pydev", "python", "reload" ]
stackoverflow_0001895745_eclipse_import_pydev_python_reload.txt
Q: Inheritance and factory functions in Python and Django I'm creating a Django app that uses some inheritance in it's model, mainly because I need to assign everything a UUID and a reference so I know what class it was. Here's a simplified version of the base class: class BaseElement(models.Model): uuid = model...
Inheritance and factory functions in Python and Django
I'm creating a Django app that uses some inheritance in it's model, mainly because I need to assign everything a UUID and a reference so I know what class it was. Here's a simplified version of the base class: class BaseElement(models.Model): uuid = models.CharField(max_length=64, editable=False, blank=True, defau...
[ "If you make create() a @classmethod instead of @staticmethod, you'll have access to the class object, which you can use instead of referring to it by name:\n@classmethod\ndef create(cls, *args, **kwargs):\n obj = cls(*args, **kwargs)\n obj.set_defaults()\n return obj\n\nThis is now generic and can go on t...
[ 7, 2 ]
[]
[]
[ "django", "inheritance", "python" ]
stackoverflow_0001891004_django_inheritance_python.txt
Q: How to determine the datatype in Python? astring ('a','tuple') How do I determine if "x" is a tuple or string? A: if isinstance(x, basestring): # a string else: try: it = iter(x) except TypeError: # not an iterable else: # iterable (tuple, list, etc) @Alex Martelli's answer describes i...
How to determine the datatype in Python?
astring ('a','tuple') How do I determine if "x" is a tuple or string?
[ "if isinstance(x, basestring):\n # a string\nelse:\n try: it = iter(x)\n except TypeError:\n # not an iterable\n else:\n # iterable (tuple, list, etc)\n\n@Alex Martelli's answer describes in detail why you should prefer the above style when you're working with types in Python (thanks to @Mike Ho...
[ 8, 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001896261_python.txt
Q: Will this urllib2 python code download the page of the file? urllib2.urlopen(theurl).read() ...this downloads the file. urllib2.urlopen(theurl).geturl()...does this download the file? (how long does it take) A: From the documentation: The geturl() method returns the real URL of the page. In some cases, the ...
Will this urllib2 python code download the page of the file?
urllib2.urlopen(theurl).read() ...this downloads the file. urllib2.urlopen(theurl).geturl()...does this download the file? (how long does it take)
[ "From the documentation:\n\nThe geturl() method returns the real\n URL of the page. In some cases, the\n HTTP server redirects a client to\n another URL. The urlopen() function\n handles this transparently, but in\n some cases the caller needs to know\n which URL the client was redirected\n to. The geturl() ...
[ 5, 4, 3, 2, 1 ]
[]
[]
[ "http", "python", "urllib2" ]
stackoverflow_0001895949_http_python_urllib2.txt
Q: Pythonic way to write a for loop that doesn't use the loop index This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program. The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning b...
Pythonic way to write a for loop that doesn't use the loop index
This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program. The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev def RandomSample(count): pattern = [] fo...
[ "Just for reference for ignoring variables in PyDev\nBy default pydev will ignore following variables \n['_', 'empty', 'unused', 'dummy']\n\nYou can add more by passing supression parameters\n-E, --unusednames ignore unused locals/arguments if name is one of these values\n\nRef:\nhttp://eclipse-pydev.sourcearchive...
[ 18, 5, 4, 2, 1, 0, 0 ]
[]
[]
[ "eclipse", "for_loop", "python" ]
stackoverflow_0001895615_eclipse_for_loop_python.txt
Q: Special characters in OSX filename ? (Python os.rename) I am trying to rename some files automatically on OSX with a python script. But I fail to work with special characters like forward slash etc.: oldname = "/test" newname = "/test(1\/10)" os.rename(oldname, newname) I think I do have an encoding problem. But ...
Special characters in OSX filename ? (Python os.rename)
I am trying to rename some files automatically on OSX with a python script. But I fail to work with special characters like forward slash etc.: oldname = "/test" newname = "/test(1\/10)" os.rename(oldname, newname) I think I do have an encoding problem. But different tries with re.escape or using UTF-8 unicode encodin...
[ "What most of the file systems have in common is that they do not allow directory separators (slashes) in filenames.\nThat said, in Mac OS X you can have file names appear with slashes in finder, you can try replacing slashes with :.\n", "If you're trying to rename the folder '/test' you'll need to run python as ...
[ 2, 0 ]
[]
[]
[ "character_encoding", "filesystems", "macos", "path", "python" ]
stackoverflow_0001896442_character_encoding_filesystems_macos_path_python.txt
Q: Django form in Google App Engine unable to find module PIL There are actually a couple of questions here. For what I'm doing, I'm doing a basic image upload with Django 1.1 and Google App Engine. Here is my form class: class UploadPictureForm(forms.Form): picture = forms.ImageField() And then on submit, I h...
Django form in Google App Engine unable to find module PIL
There are actually a couple of questions here. For what I'm doing, I'm doing a basic image upload with Django 1.1 and Google App Engine. Here is my form class: class UploadPictureForm(forms.Form): picture = forms.ImageField() And then on submit, I have the following code: def handle_picture(request): form = ...
[ "For starters, you shouldn't use GAE with Python 2.6. Google App Engine is created with 2.5 in mind and it usually breaks in multiple ways on 2.6.\nMore, I'm not quite sure you can use PIL at all with GAE. It's a C-based library and therefore it's a no-no for GAE (which requires custom packages to be pure-Python on...
[ 3, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "python_imaging_library" ]
stackoverflow_0001894875_google_app_engine_python_python_imaging_library.txt
Q: How to return a float point number with a defined number of decimal places? So I know how to print a floating point number with a certain decimal places. My question is how to return it with a specified number of decimal places? Thanks. A: You could use the round() function The docs about it: round(x[, n]) x ro...
How to return a float point number with a defined number of decimal places?
So I know how to print a floating point number with a certain decimal places. My question is how to return it with a specified number of decimal places? Thanks.
[ "You could use the round() function\nThe docs about it:\nround(x[, n])\n\nx rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.\n", "In order to get two decimal places, multiply the number by 100, floor it, then divide by 100.\nAnd note that the number you will return will not really ha...
[ 6, 4, 4, 2 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0001896722_floating_point_python.txt
Q: Writing to stdout from within a Microsoft VBA macro I'm using Python (and the Win32 extensions) to execute macros in an Excel spreadsheet via the COM interface, as shown below: import win32com.client o = win32com.client.Dispatch("Excel.Application") o.Visible = 1 o.Workbooks.Open (r"C:\test.xls") o.Application.Run...
Writing to stdout from within a Microsoft VBA macro
I'm using Python (and the Win32 extensions) to execute macros in an Excel spreadsheet via the COM interface, as shown below: import win32com.client o = win32com.client.Dispatch("Excel.Application") o.Visible = 1 o.Workbooks.Open (r"C:\test.xls") o.Application.Run("macro1") What I'd like to do is have the Excel macro o...
[ "You can write to and read stdout with VB6 with a bit of drama.. but creating a console app with Excel and VBA? I'm not sure that is possible.\nI've found a simple Python COM example which you may have already investigated. Could you make your macro just create a sheet a write to a cell and have Python poll that ce...
[ 1, 1, 0 ]
[ "What happens if you write to stdout? Either:\nprint \"Hello, world!\"\n\nor:\nimport sys\nsys.stdout.write(\"Hello, world!\\n\")\n\nor even:\nimport sys\nsys.__stdout__.write(\"Hello, world!\\n\")\n\nsys.stdout is the current stdout file, __stdout__ is the original stdout when the Python interpreter started.\n" ]
[ -1 ]
[ "com", "excel", "python", "stdout", "vba" ]
stackoverflow_0001889175_com_excel_python_stdout_vba.txt
Q: Enable pylint in Netbeans How can I integrate pylint with netbeans? A: I haven't tried this myself, but this website: http://jpydbg.sourceforge.net/ seems to document a method to get it working. A: There's a PyLint plugin for Eric. It's a nice little open source IDE for aimed particularly for Python and Ruby. ...
Enable pylint in Netbeans
How can I integrate pylint with netbeans?
[ "I haven't tried this myself, but this website:\nhttp://jpydbg.sourceforge.net/\nseems to document a method to get it working.\n", "There's a PyLint plugin for Eric. It's a nice little open source IDE for aimed particularly for Python and Ruby. Perhaps you will find it useful. \n", "On the netbeans-python (nbpy...
[ 1, 0, 0 ]
[]
[]
[ "netbeans", "pylint", "python" ]
stackoverflow_0001817047_netbeans_pylint_python.txt
Q: Creating Regular Expressions in Python I'm trying to create regular expression that filters from the following partial text: amd64 build of software 1:0.98.10-0.2svn20090909 in archive what I want to extract is: software 1:0.98.10-0.2svn20090909 How can I do this?? I've been trying and this is what I have so fa...
Creating Regular Expressions in Python
I'm trying to create regular expression that filters from the following partial text: amd64 build of software 1:0.98.10-0.2svn20090909 in archive what I want to extract is: software 1:0.98.10-0.2svn20090909 How can I do this?? I've been trying and this is what I have so far: p = re.compile('([a-zA-Z0-9\-\+\.]+)\ ([0...
[ "This will work:\np = re.compile(r'([a-zA-Z0-9\\-\\+\\.]+)\\ ([0-9][0-9a-zA-Z\\:\\.\\-]+)')\niterator = p.finditer(\"amd64 build of dvdrip software 1:0.98.10-0.2svn20090909 in archive\")\nfor match in iterator:\n print match.group()\n# Prints: software 1:0.98.10-0.2svn20090909\n\nThat works by allowing the captu...
[ 3, 3, 0 ]
[]
[]
[ "expression", "python", "regex" ]
stackoverflow_0001897254_expression_python_regex.txt
Q: validating correct answer with loops in python Sorry for the non descriptive question I had no idea how to word it. I'm trying to write a program (GUI) where I ask the users questions and then in return they answer and see if they are correct however when I enter the correct answer it's still showing as being inco...
validating correct answer with loops in python
Sorry for the non descriptive question I had no idea how to word it. I'm trying to write a program (GUI) where I ask the users questions and then in return they answer and see if they are correct however when I enter the correct answer it's still showing as being incorrect. My code looks something like this. prompt for...
[ "The problem here seems to be that you're misunderstanding how GUIs work. It's not like the sequential print/read code that most programming instruction starts with. The GUI widgets only create themselves, draw to the screen and wait for events. \nThis line:\nAnswer1 = entAnswer.getText()\n\nwill end up setting Ans...
[ 4, 0, 0, 0 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0001897531_python_user_interface.txt
Q: Test if point is in some rectangle I have a large collection of rectangles, all of the same size. I am generating random points that should not fall in these rectangles, so what I wish to do is test if the generated point lies in one of the rectangles, and if it does, generate a new point. Using R-trees seem to wo...
Test if point is in some rectangle
I have a large collection of rectangles, all of the same size. I am generating random points that should not fall in these rectangles, so what I wish to do is test if the generated point lies in one of the rectangles, and if it does, generate a new point. Using R-trees seem to work, but they are really meant for rectan...
[ "This Reddit thread addresses your problem: \nI have a set of rectangles, and need to determine whether a point is contained within any of them. What are some good data structures to do this, with fast lookup being important?\nIf your universe is integer, or if the level of precision is well known and is not too hi...
[ 8, 4, 0, 0, 0 ]
[]
[]
[ "algorithm", "point", "python" ]
stackoverflow_0001897779_algorithm_point_python.txt
Q: How can you migrate Django models similar to Ruby on Rails migrations? Django has a number of open source projects that tackle one of the framework's more notable missing features: model "evolution". Ruby on Rails has native support for migrations, but I'm curious if anyone can recommend one of the following Djan...
How can you migrate Django models similar to Ruby on Rails migrations?
Django has a number of open source projects that tackle one of the framework's more notable missing features: model "evolution". Ruby on Rails has native support for migrations, but I'm curious if anyone can recommend one of the following Django "evolution" projects: South django-evolution dmigrations
[ "South has the most steam behind it. dmigrations is too basic IMO. django-evolution screams if you ever touch the db outside of it.\nSouth is the strongest contender by far. With the model freezing and auto-migrations it's come a long way.\n", "South and django-evolution are certainly the best options. South's ...
[ 10, 5, 2, 1 ]
[]
[]
[ "django", "migration", "python" ]
stackoverflow_0000853248_django_migration_python.txt
Q: lxml[.objectify] documentElement tagName I'm receiving data packets in XML format, each with a specific documentRoot tag, and I'd like to delegate specialized methods to take care of those packets, based on the root tag name. This worked with xml.dom.minidom, something like this: dom = minidom.parseString(the_data...
lxml[.objectify] documentElement tagName
I'm receiving data packets in XML format, each with a specific documentRoot tag, and I'd like to delegate specialized methods to take care of those packets, based on the root tag name. This worked with xml.dom.minidom, something like this: dom = minidom.parseString(the_data) root = dom.documentElement deleg = getattr(s...
[ "With the help of the lxml docs and the dir() built_in, I managed to produce this:\n>>> from lxml import objectify\n>>> import StringIO\n>>> tree = objectify.parse(StringIO.StringIO('<parent><child>Billy</child><child>Bob</child></parent>'))\n>>> root = tree.getroot()\n>>> root.tag\n'parent'\n>>> [(foo.tag, foo.tex...
[ 3, 0 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0001896628_lxml_python_xml.txt
Q: What is the difference between the __int__ and __index__ methods in Python 3? The Data Model section of the Python 3.2 documentation provides the following descriptions for the __int__ and __index__ methods: object.__int__(self) Called to implement the built-in [function int()]. Should return [an integer]. object...
What is the difference between the __int__ and __index__ methods in Python 3?
The Data Model section of the Python 3.2 documentation provides the following descriptions for the __int__ and __index__ methods: object.__int__(self) Called to implement the built-in [function int()]. Should return [an integer]. object.__index__(self) Called to implement operator.index(). Also called whenever Python ...
[ "See PEP 357: Allowing Any Object to be Used for Slicing.\n\nThe nb_int method is used for coercion and so means something\n fundamentally different than what is requested here. This PEP\n proposes a method for something that can already be thought of as\n an integer communicate that information to Python when ...
[ 20, 1 ]
[]
[]
[ "casting", "python" ]
stackoverflow_0001898310_casting_python.txt