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: Setting up Python on Apache/Windows; IDE question I am finally learning Python after putting it off for a long time. I am setting it up on Apache (XAMPP), which version of mod_python should I choose? If I get mod_python-3.3.1.win32-py2.5-Apache2.2.exe, does that mean I have to download Python 2.5 from here? EDIT: ...
Setting up Python on Apache/Windows; IDE question
I am finally learning Python after putting it off for a long time. I am setting it up on Apache (XAMPP), which version of mod_python should I choose? If I get mod_python-3.3.1.win32-py2.5-Apache2.2.exe, does that mean I have to download Python 2.5 from here? EDIT: I'll use this primarily for web development. Which IDE ...
[ "Do not use mod_python - it is now officially dead. You should use mod_wsgi instead. There are instructions for installing it on Windows.\n", "For an IDE that also plays well with web development, download Aptana Studio\nwhich is built upon eclipse and then get the pydev extension for it.\nAnd you will need the p...
[ 4, 1 ]
[]
[]
[ "python", "xampp" ]
stackoverflow_0003287347_python_xampp.txt
Q: python using post method for upload file I have a problem with importing file to calendar over wcap protocol. In documentation http://docs.sun.com/source/816-6416-10/pr10WCAP.html#26125 is said that i should use POST method. I have trayed but with no positiv result. I have no idea hov to forced it to work with pyt...
python using post method for upload file
I have a problem with importing file to calendar over wcap protocol. In documentation http://docs.sun.com/source/816-6416-10/pr10WCAP.html#26125 is said that i should use POST method. I have trayed but with no positiv result. I have no idea hov to forced it to work with python
[ "The wcap reference you provide contains example POST data.\nUsing the urllib2.urlopen() function with POST data is straightforward.\n\nurllib2.urlopen(url[, data][, timeout])\nOpen the URL url, which can be either a string or a Request object.\ndata may be a string specifying additional data to send to the server,...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003288745_python.txt
Q: the django template and combine {{ }} I start with django, and I have a little problem. Well, I have a tuple (top) and I wanted to display an element of it according to another template value (date, which is a datetime type). So, I did that : {{top.date.day}} Well it doesn't work, so I tried it : {{ top.{{date....
the django template and combine {{ }}
I start with django, and I have a little problem. Well, I have a tuple (top) and I wanted to display an element of it according to another template value (date, which is a datetime type). So, I did that : {{top.date.day}} Well it doesn't work, so I tried it : {{ top.{{date.day}} }} And it didn't work neither. So wh...
[ "Use the {% with %} tag to assign the intermediate value to another context variable first.\n" ]
[ 0 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0003288948_django_python_templates.txt
Q: How do I bind an event to the left mouse button being held down? I need a command to be executed as long as the left mouse button is being held down. A: If you want "something to happen" without any intervening events (ie: without the user moving the mouse or pressing any other buttons) your only choice is to p...
How do I bind an event to the left mouse button being held down?
I need a command to be executed as long as the left mouse button is being held down.
[ "If you want \"something to happen\" without any intervening events (ie: without the user moving the mouse or pressing any other buttons) your only choice is to poll. Set a flag when the button is pressed, unset it when released. While polling, check the flag and run your code if its set.\nHere's something to illus...
[ 9, 6, 2 ]
[]
[]
[ "event_binding", "python", "tkinter" ]
stackoverflow_0003288001_event_binding_python_tkinter.txt
Q: Formatting SQL query output in Python/SQLite 3 I use a simple SQL query in Python to grab records from a SQLite 3 database: cursor.execute ("SELECT due, task FROM tasks WHERE due <> '' ORDER BY due ASC") rows = cursor.fetchall() for row in rows: print '\n%s %s' % (row[0], row[1]...
Formatting SQL query output in Python/SQLite 3
I use a simple SQL query in Python to grab records from a SQLite 3 database: cursor.execute ("SELECT due, task FROM tasks WHERE due <> '' ORDER BY due ASC") rows = cursor.fetchall() for row in rows: print '\n%s %s' % (row[0], row[1]) The due field in the database is set to DATE type...
[ "I think row[0] is a datetime object. So the following should work:\nprint '\\n%s %s' % (row[0].strftime('%Y-%m-%d'), row[1])\n\n" ]
[ 3 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0003289317_python_sql_sqlite.txt
Q: How do I get mouse position relative to the parent widget in tkinter? I need to get the mouse position relative to the tkinter window. A: Generally speaking you should never need to "get" this information because it is given to you as part of the event object that is passed in. You probably only need this infor...
How do I get mouse position relative to the parent widget in tkinter?
I need to get the mouse position relative to the tkinter window.
[ "Generally speaking you should never need to \"get\" this information because it is given to you as part of the event object that is passed in. You probably only need this information when responding to an event, and the event gives you this information. \nPut more succinctly, to get the information you simply have...
[ 6, 3 ]
[]
[]
[ "mouse_position", "python", "tkinter" ]
stackoverflow_0003288047_mouse_position_python_tkinter.txt
Q: functions in python query def directionToVector(direction, speed = 1.0): dx, dy = Actions._directions[direction] return (dx * speed, dy * speed) def getCostOfActions(self, actions): """ Returns the cost of a particular sequence of actions. If those actions include an illegal move, return 999...
functions in python query
def directionToVector(direction, speed = 1.0): dx, dy = Actions._directions[direction] return (dx * speed, dy * speed) def getCostOfActions(self, actions): """ Returns the cost of a particular sequence of actions. If those actions include an illegal move, return 999999. This is implemented for y...
[ "The first argument, of course is self, since this is an instance method. This is passed implicitly.\nAccording to the docstring, the argument the callers should provide is 'actions: A list of actions to take'. \nE.g:\ninstance.getCostOfActions([North, East, South, West])\n\nN.B: You have two lines thus:\ndef getCo...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003289458_python.txt
Q: Improving performance of cgi I have 5 python cgi pages. I can navigate from one page to another. All pages get their data from the same database table just that they use different queries. The problem is that the application as a whole is slow. Though they connect to the same database, each page creates a new hand...
Improving performance of cgi
I have 5 python cgi pages. I can navigate from one page to another. All pages get their data from the same database table just that they use different queries. The problem is that the application as a whole is slow. Though they connect to the same database, each page creates a new handle every time I visit it and handl...
[ "cgi requires a new interpreter to start up for each request, and then all the resources such as db connections to be acquired and released.\nfastcgi or wsgi improve performance by allowing you to keep running the same process between requests\n", "Django and Pylons are both frameworks that solve this problem qui...
[ 2, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0003289330_cgi_python.txt
Q: Web-ifing a python command line script? This is my first questions here, so I hope it will be done correctly ;) I've been assigned the task to give a web interface to some "home made" python script. This script is used to check some web sites/applications availability, via curl commands. A very important aspect of...
Web-ifing a python command line script?
This is my first questions here, so I hope it will be done correctly ;) I've been assigned the task to give a web interface to some "home made" python script. This script is used to check some web sites/applications availability, via curl commands. A very important aspect of this script is that it gives its results in ...
[ "A sketch for a solution:\nCreate an HTML file which contains the layout for your web page, with a dedicated DIV for the output of the script:\n<html>\n<body>\n<div id=\"scriptoutput\"></div>\n<script type=\"text/javascript\" src=\"localhost:8000/runscript\"/>\n</body>\n</html>\n\nThis HTML file can be served using...
[ 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003289584_python.txt
Q: lists in python, with references How do I copy the contents of a list and not just a reference to the list in Python? A: Look at the copy module, and notice the difference between shallow and deep copies: The difference between shallow and deep copying is only relevant for compound objects (objects that contain...
lists in python, with references
How do I copy the contents of a list and not just a reference to the list in Python?
[ "Look at the copy module, and notice the difference between shallow and deep copies:\n\nThe difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):\n\nA shallow copy constructs a new compound object and then (to the exten...
[ 7, 5, 5, 2 ]
[]
[]
[ "copy", "list", "python", "reference" ]
stackoverflow_0003289822_copy_list_python_reference.txt
Q: Python decorator class to transform methods to dictionary items I wonder if there is a reasonable easy way to allow for this code (with minor modifications) to work. class Info(object): @attr("Version") def version(self): return 3 info = Info() assert info.version == 3 assert info["Version"] == 3 ...
Python decorator class to transform methods to dictionary items
I wonder if there is a reasonable easy way to allow for this code (with minor modifications) to work. class Info(object): @attr("Version") def version(self): return 3 info = Info() assert info.version == 3 assert info["Version"] == 3 Ideally, the code would do some caching/memoising as well, e.g. empl...
[ "If the attribute name (version) is always a lowercase version of the dict key (\"Version\"), then you could set it up this way:\nclass Info(object):\n @property\n def version(self):\n return 3\n def __getitem__(self,key):\n if hasattr(self,key.lower()):\n return getattr(self,key.l...
[ 1, 0 ]
[]
[]
[ "decorator", "properties", "python" ]
stackoverflow_0003289064_decorator_properties_python.txt
Q: Help with a custom GUI in wxpython I'm new to wxPython, so bear with me. I'm creating a custom GUI set up and need to get two attributes. Firstly I want to create an inner boarder of a different color (The single dark boarder looks too plain). Secondly, I need to bind the dragging attribute so that only the label ...
Help with a custom GUI in wxpython
I'm new to wxPython, so bear with me. I'm creating a custom GUI set up and need to get two attributes. Firstly I want to create an inner boarder of a different color (The single dark boarder looks too plain). Secondly, I need to bind the dragging attribute so that only the label will allow dragging as opposed to the wh...
[ "I'm not sure what border you want to change. Are you talking about the border of the selected object? As for dragging objects around, I would recommend looking at Whyteboard, a wxPython drawing program. It should how to select and drag objects around quite nicely and work on Windows and Linux. I'm not sure about M...
[ 0 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0003285296_python_user_interface_wxpython.txt
Q: python time problem I am using the exif.py library. After calling tags=exif.process_file(...) i want to retrieve the time the image was captured. so i continue with t =tags['Image DateTime'] if tags.has_key('Image DateTime') else time.time() now i want to store t in django's database. For that t must be in the f...
python time problem
I am using the exif.py library. After calling tags=exif.process_file(...) i want to retrieve the time the image was captured. so i continue with t =tags['Image DateTime'] if tags.has_key('Image DateTime') else time.time() now i want to store t in django's database. For that t must be in the form 2010-07-20 14:37:12 b...
[ "Use time.strptime() to parse the str() value, than format the time tuple to any desired form.\nAn example, using the 'Image DateTime' attribute returned by EXIF.\n>>> e1['Image DateTime']\n(0x0132) ASCII=2007:09:06 06:37:51 @ 176\n>>> str(e1['Image DateTime'])\n'2007:09:06 06:37:51'\n>>> \n>>> tag = time.strptime(...
[ 2, 1, 0, 0 ]
[]
[]
[ "django_models", "exif", "python", "time" ]
stackoverflow_0003289969_django_models_exif_python_time.txt
Q: Python Beautiful soup tag for table td Python Beautiful soup tag for table td <td class="result" valign="top" colspan="3"> At the moment, the following does not work: for header in soup('table', 'td .result'): Getting error: HTMLParser.HTMLParseError: malformed start tag A: As noted on their website, HTMLPar...
Python Beautiful soup tag for table td
Python Beautiful soup tag for table td <td class="result" valign="top" colspan="3"> At the moment, the following does not work: for header in soup('table', 'td .result'): Getting error: HTMLParser.HTMLParseError: malformed start tag
[ "As noted on their website, HTMLParser is quite fragile. You should use SGMLParser instead, as it's more robust against malformed HTML. \nUnfortunately, Python 3.0 has removed SGMLParser from the standard library. See the links above for suggested workarounds, such as using html5lib.\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003290062_beautifulsoup_python.txt
Q: reddit get_comments action, can someone clarify what is going on here? I'm trying to understand reddit's source, and I am looking at the get_comments action method of front.py This is the action that displays a story: http://code.reddit.com/browser/r2/r2/controllers/front.py#L139 Specifically, what is the top part...
reddit get_comments action, can someone clarify what is going on here?
I'm trying to understand reddit's source, and I am looking at the get_comments action method of front.py This is the action that displays a story: http://code.reddit.com/browser/r2/r2/controllers/front.py#L139 Specifically, what is the top part of the method doing where there is a @Validate marker? And on the bottom ne...
[ "\nSpecifically, what is the top part of the method doing where there is a @Validate marker?\n\n@validate is validation decorator, used to validate and process parameters from request.\nYou can see its sources at http code.reddit.com/browser/r2/r2/controllers/validator/validator.py#L129\n\nAnd on the bottom near th...
[ 2 ]
[]
[]
[ "pylons", "python", "reddit" ]
stackoverflow_0003283157_pylons_python_reddit.txt
Q: Good apps I could use to store a page locally? I really need to find a reliable way in order to store a web page locally, with all it's dependencies e.g. html, css stylesheets, javascript, etc... A python library would be awesome, a CLI would be great too. Also would this type of app/library have a standardized na...
Good apps I could use to store a page locally?
I really need to find a reliable way in order to store a web page locally, with all it's dependencies e.g. html, css stylesheets, javascript, etc... A python library would be awesome, a CLI would be great too. Also would this type of app/library have a standardized name? Any suggestions guys? =)
[ "I have used HTTrack in the past to good effect (available for Windows, Linux, & OS X). It has a C API and there is also a third-party Python wrapper available.\nAlso see this question: Any Python Script to Save Websites Like Firefox?\n", "you can try Scrapy which is fairly simple and efficient:\nit is a bit more...
[ 1, 0 ]
[]
[]
[ "caching", "html", "linux", "python", "screen_scraping" ]
stackoverflow_0003289816_caching_html_linux_python_screen_scraping.txt
Q: Method logging in Python I'd like something equivalent to calling method: $METHOD_NAME args: $ARGS output: $OUTPUT to be automatically logged to a file (via the logging module, possibly) for every (user-defined) method call. The best solution I can come up with is to write a decorator that will ...
Method logging in Python
I'd like something equivalent to calling method: $METHOD_NAME args: $ARGS output: $OUTPUT to be automatically logged to a file (via the logging module, possibly) for every (user-defined) method call. The best solution I can come up with is to write a decorator that will do this, and then add it to ev...
[ "You could look at the trace module in the standard library, which \n\nallows you to trace program execution, generate annotated statement coverage listings, print caller/callee relationships and list functions executed during a program run. It can be used in another program or from the command line.\n\nYou can als...
[ 6, 2, 1, 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0003290586_logging_python.txt
Q: Memory not released by python cherrypy application on linux I have a long running process that will fetch 100k rows from the db genrate a web page and then release all the small objets (list, tuples and dicts). On windows, after each request the memory is freed. Howerver, on linux, the memory of the server keeps g...
Memory not released by python cherrypy application on linux
I have a long running process that will fetch 100k rows from the db genrate a web page and then release all the small objets (list, tuples and dicts). On windows, after each request the memory is freed. Howerver, on linux, the memory of the server keeps growing. The following posts describes what the problem is and one...
[ "You may be able to compile Python in your own working directory rather than try to have the sysadmin replace the system Python.\nFirst you should confirm that the tcmalloc solution solves your problem and does not impact performance too much for your application\n" ]
[ 0 ]
[]
[]
[ "cherrypy", "memory", "python", "tcmalloc" ]
stackoverflow_0003290754_cherrypy_memory_python_tcmalloc.txt
Q: Running subprocess.call to run a Cocoa command-line application I have one piece of Cocoa code I wrote that takes in an XML file containing bounding boxes that are then drawn on top of a video (each box has an associated frame). The Cocoa program is meant to be run from the command line (and takes in all its param...
Running subprocess.call to run a Cocoa command-line application
I have one piece of Cocoa code I wrote that takes in an XML file containing bounding boxes that are then drawn on top of a video (each box has an associated frame). The Cocoa program is meant to be run from the command line (and takes in all its parameters as command line arguments) I can run program just fine with any...
[ "Because the code originally used temporary files, I couldn't close the file before passing it to the subprocess. However, what I should have done instead is to flush the file before subprocess.call was invoked. The inconsistent behavior likely resulted from the size of input causing automatic flushing at different...
[ 1, 0 ]
[]
[]
[ "cocoa", "python", "subprocess" ]
stackoverflow_0003283773_cocoa_python_subprocess.txt
Q: python , how to find class object from child entity? my code is following in python. class A(object): b = B() def d(self): print "Hi" class B(): def C(self): self.__self__.d()#edit ::: i need to call d() method here. i know __self__ is wrong # do knowledge for B being variable inside ob...
python , how to find class object from child entity?
my code is following in python. class A(object): b = B() def d(self): print "Hi" class B(): def C(self): self.__self__.d()#edit ::: i need to call d() method here. i know __self__ is wrong # do knowledge for B being variable inside object A needed ? i.e # passing parent object via init...
[ "See this previous answer. It's with a derived class instead, but it might be helpful to look into.\nYou could have A pass itself to B in the init method or as a separate method. As long as that was called before you had a call to B.c() it would work fine. It's not a perfect solution, but it works.\nclass B():\n ...
[ 2, 1 ]
[]
[]
[ "class", "object", "python" ]
stackoverflow_0003290950_class_object_python.txt
Q: Plone content type works as folder but not as event I have been trying to create a new content type for Plone based on the event type. I followed this tutorial for making content types and successfully created this code for my own content type called "Multimedia". My code works, however the type is based on the ...
Plone content type works as folder but not as event
I have been trying to create a new content type for Plone based on the event type. I followed this tutorial for making content types and successfully created this code for my own content type called "Multimedia". My code works, however the type is based on the folder type. My attempts to change this to be based on ...
[ "You can't extend ATEvent in that way and will have to use SchemaExtender to do so\n" ]
[ 1 ]
[]
[]
[ "plone", "python" ]
stackoverflow_0003125077_plone_python.txt
Q: Is there a Perl alternative to YSlow? I'd like to have a tool in Perl to gather useful statistics for page loads (eg, download time/speed, CDN information, headers, dns lookups, compressions) Does anyone know if one exists or if there's a place to learn about how to make one? A: You might want to try WWW::Mecha...
Is there a Perl alternative to YSlow?
I'd like to have a tool in Perl to gather useful statistics for page loads (eg, download time/speed, CDN information, headers, dns lookups, compressions) Does anyone know if one exists or if there's a place to learn about how to make one?
[ "You might want to try WWW::Mechanize::Timed, which extends the WWW::Mechanize module. The ::Timed features will allow you to collect information on how long your requests take. The underlying ::Mechanize module, which is itself a subclass of LWP::UserAgent, would give you access to your response, including headers...
[ 1, 0 ]
[]
[]
[ "firefox", "perl", "python", "yslow" ]
stackoverflow_0003175611_firefox_perl_python_yslow.txt
Q: xml parsing and reading the values in python I want to know how to read and store the xml data in an array.I m not sure which method to use or class Can anyone tell which xml lib to use for reading the xml A: That's quite a wide topic, and the best library depends on quite a few things, so it's not easy to answe...
xml parsing and reading the values in python
I want to know how to read and store the xml data in an array.I m not sure which method to use or class Can anyone tell which xml lib to use for reading the xml
[ "That's quite a wide topic, and the best library depends on quite a few things, so it's not easy to answer this very meaningfully with so little details.\nI'd suggest you look into xml.dom.minidom and see if it suits your needs.\n", "BeautifulSoup or xml\n", "If you're using Python 2.5+, xml.etree.ElementTree i...
[ 0, 0, 0, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002326601_python_xml.txt
Q: BaseHTTPServer not recognizing CSS files I'm writing a pretty basic webserver (well, trying) and while it's now serving HTML fine, my CSS files don't seem to be recognized at all. I have Apache2 running on my machine as well, and when I copy my files to the docroot, the pages are served correctly. I've also chec...
BaseHTTPServer not recognizing CSS files
I'm writing a pretty basic webserver (well, trying) and while it's now serving HTML fine, my CSS files don't seem to be recognized at all. I have Apache2 running on my machine as well, and when I copy my files to the docroot, the pages are served correctly. I've also checked permissions and they seems to be fine. He...
[ "You could add this to your if clause\n elif self.path.endswith(\".css\"):\n f = open(curdir+sep+self.path)\n self.send_response(200)\n self.send_header('Content-type', 'text/css')\n self.end_headers()\n self.wfile.write(f.re...
[ 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003291120_python.txt
Q: Dynamic Importing in Python (Dotted statments) I'm having trouble with the following code: def get_module(mod_path): mod_list = mod_path.split('.') mod = __import__(mod_list.pop(0)) while mod_list: mod = getattr(mod, mod_list.pop(0)) return mod When I do get_module('qmbpmn.common.db_pars...
Dynamic Importing in Python (Dotted statments)
I'm having trouble with the following code: def get_module(mod_path): mod_list = mod_path.split('.') mod = __import__(mod_list.pop(0)) while mod_list: mod = getattr(mod, mod_list.pop(0)) return mod When I do get_module('qmbpmn.common.db_parsers') I get the error message: AttributeError: 'modu...
[ "When using __import__ to import submodules, you must pass the parent package as the fromlist argument:\n>>> __import__(\"os.path\")\n<module 'os' from '/usr/lib/python2.6/os.pyc'>\n>>> __import__(\"os.path\", fromlist=[\"os\"])\n<module 'posixpath' from '/usr/lib/python2.6/posixpath.pyc'>\n\n", "__import__ works...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003291204_python.txt
Q: Pass QuerySet object in template. Django How can i pass QuerySet object in to template. And then Iterate through it in tempalte. If ican do it....? Example queryset =MyModel.objects.all() return render_to_response('template.html',{'queryset':queryset}) How it'll looks in template? Can I show field of foreigne k...
Pass QuerySet object in template. Django
How can i pass QuerySet object in to template. And then Iterate through it in tempalte. If ican do it....? Example queryset =MyModel.objects.all() return render_to_response('template.html',{'queryset':queryset}) How it'll looks in template? Can I show field of foreigne key object in this template?
[ "{% for each_model in model %}\n #Do Something with model\n {{each_model.name}}\n{% endfor %}\n\n" ]
[ 7 ]
[]
[]
[ "django_templates", "python" ]
stackoverflow_0003291469_django_templates_python.txt
Q: Shared memory and comunication between programs I read this: python singleton into multiprocessing but I didn't find the solution of my problem. I have to run the same program (not process) many times in one time. Programs work in the same electronic devices. I must synchronized this programs. Only one program can...
Shared memory and comunication between programs
I read this: python singleton into multiprocessing but I didn't find the solution of my problem. I have to run the same program (not process) many times in one time. Programs work in the same electronic devices. I must synchronized this programs. Only one program can use device in the moment. Have you got any suggesti...
[ "You could use lockfiles in the filesystem.\n" ]
[ 0 ]
[]
[]
[ "python", "shared_memory", "synchronization" ]
stackoverflow_0003289040_python_shared_memory_synchronization.txt
Q: Multiple assignments under 'if' statement Why can't I make multiple assignments under an if statement in python? Is there some syntax I am missing? I want to do this: files = ["file1", "file2", "file3"] print "\nThe following files are available: \n" i = 0 for file in files: i = i + 1 print i, file cho...
Multiple assignments under 'if' statement
Why can't I make multiple assignments under an if statement in python? Is there some syntax I am missing? I want to do this: files = ["file1", "file2", "file3"] print "\nThe following files are available: \n" i = 0 for file in files: i = i + 1 print i, file choice = int(raw_input("\Enter a file number: ")) ...
[ "Both variables file and time must be defined at an higher block level than your if statement.\nBe careful with \"time\", as it is the name of a python module. You should use a variation of this name (time_ for example).\n", "You are not using any other choice except for 1 and it will give error if choice is not ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003291997_python.txt
Q: Django mod_wsgi PicklingError while saving object Do you know any solution to this: [Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] mod_wsgi (pid=3072): Exception occurred processing WSGI script '/home/www/shop/django.wsgi'., referer: http://shop.domain.com/accounts/checkout/? [Thu Jul 08 19:15:38 2010] ...
Django mod_wsgi PicklingError while saving object
Do you know any solution to this: [Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] mod_wsgi (pid=3072): Exception occurred processing WSGI script '/home/www/shop/django.wsgi'., referer: http://shop.domain.com/accounts/checkout/? [Thu Jul 08 19:15:38 2010] [error] [client 79.162.31.162] Traceback (most recent c...
[ "See this answer. Does that help?\nEDIT (responding to your comment):\nI'm afraid I don't know either django or your code well enough to give you a fix. I do have a clearer idea of the underlying error, though: Before this error occurred, an instance of decimal.Decimal was created, and then for some reason the clas...
[ 2 ]
[]
[]
[ "django", "django_models", "pickle", "python" ]
stackoverflow_0003292383_django_django_models_pickle_python.txt
Q: lapack import error with NumPy Trying to import numpy in Python 2.6 I run into: from numpy.linalg import lapack_lite ImportError: libmkl_lapack.so: cannot open shared object file: No such file or directory There are multiple instances of Intel's Math Kernel Library on the machine providing libmkl_lapack.so and I'm...
lapack import error with NumPy
Trying to import numpy in Python 2.6 I run into: from numpy.linalg import lapack_lite ImportError: libmkl_lapack.so: cannot open shared object file: No such file or directory There are multiple instances of Intel's Math Kernel Library on the machine providing libmkl_lapack.so and I'm pointing at them with every relevan...
[ "you can try \nstrace python your_script.py\n\nto see what it is trying.\nThat will trace all syscalls, therefore showing you the underlying open made by python.\n" ]
[ 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0003292396_linux_python.txt
Q: Sending email from my domain vs from the admin google account? I have a domain xyz.com and right now it is pointing to my app in appspot. I want to send email alerts to users for various events. However, appengine restricts email sender to admin email address which was used to create the google app engine account....
Sending email from my domain vs from the admin google account?
I have a domain xyz.com and right now it is pointing to my app in appspot. I want to send email alerts to users for various events. However, appengine restricts email sender to admin email address which was used to create the google app engine account. Can I send emails on behalf of user@xyz.com using app engine? If no...
[ "According to the documentation about sending mail from within Google App Engine, the email sender has to be either:\n\nthe email address of an admin account associated with the application OR\nthe Google Account email address of the current signed-in user OR\na valid app email address (string @ appid.appspotmail.c...
[ 2, 2 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0003292238_email_google_app_engine_python.txt
Q: uploading data using Numpy.genfromtxt with multiple formats I have a file with a time stamp as a column, and numbers in all the rest. I can either load one or the other correctly, but not both. Frustrating the heck out of me... This is what I am doing: import numpy as np file = np.genfromtxt('myfile.dat', skip_...
uploading data using Numpy.genfromtxt with multiple formats
I have a file with a time stamp as a column, and numbers in all the rest. I can either load one or the other correctly, but not both. Frustrating the heck out of me... This is what I am doing: import numpy as np file = np.genfromtxt('myfile.dat', skip_header = 1, usecols = (0,1,2,3), dtype = (str, float), delimiter ...
[ "Perhaps try this:\nimport numpy as np\n\ndata = np.genfromtxt('myfile.dat',\n skiprows=1,\n usecols = (0,1,2,3),\n dtype = '|S10,<f8,<f8,<f8',\n delimiter = '\\t')\nprint(data)\n# [('2010-1-1', 1.2, 2.2999999999999998, 3.39999999999999...
[ 3, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003291670_numpy_python.txt
Q: How to get accurate window information (dimensions, etc.) in Linux (X)? How can I get accurate window information in Linux? I know that I can use wmctrl to get a window's size, but the actual size of the window can vary due to window decorations. I need the following information and methods: precise window dimens...
How to get accurate window information (dimensions, etc.) in Linux (X)?
How can I get accurate window information in Linux? I know that I can use wmctrl to get a window's size, but the actual size of the window can vary due to window decorations. I need the following information and methods: precise window dimensions precise available screen space (excluding panels like gnome-panel) the a...
[ "The best way is to use X11/xlib directly (Documentation: http://tronche.com/gui/x/xlib/ )\nBeginning from the Root you can walk through a tree via XQueryTree() and get the window Attributes via XGetWindowAttributes () / XGetGeometry ().\nOk, this is a C-Library, but there is also a Python Port: http://python-xlib....
[ 2 ]
[]
[]
[ "linux", "python", "xserver" ]
stackoverflow_0003233660_linux_python_xserver.txt
Q: .NET equivalents of Some Python Functions I am trying to port some Python code to .NET, and I was wondering if there were equivalents of the following Python functions in .NET, or some code snippets that have the same functionality. os.path.split() os.path.basename() Edit os.path.basename() in Python returns the ...
.NET equivalents of Some Python Functions
I am trying to port some Python code to .NET, and I was wondering if there were equivalents of the following Python functions in .NET, or some code snippets that have the same functionality. os.path.split() os.path.basename() Edit os.path.basename() in Python returns the tail of os.path.split, not the result of System...
[ "You're looking for the System.IO.Path Class.\nIt has many functions you can use to get the same functionality.\n\nPath.GetDirectoryName(string)\nFor split, you'll probably want to use String.Split(...) on the actual path name. You can get the OS Dependant seperator by Path.PathSeparator.\nIn the case that im missi...
[ 7, 1, 0, 0 ]
[]
[]
[ "c#", "porting", "python" ]
stackoverflow_0003291970_c#_porting_python.txt
Q: My function takes negative time to complete. What in the world happened? I'm posing this question mostly out of curiosity. I've written some code that is doing some very time intensive work. So, before executing my workhorse function, I wrapped it up in a couple of calls to time.clock(). It looks something like th...
My function takes negative time to complete. What in the world happened?
I'm posing this question mostly out of curiosity. I've written some code that is doing some very time intensive work. So, before executing my workhorse function, I wrapped it up in a couple of calls to time.clock(). It looks something like this: t1 = time.clock() print this_function_takes_forever(how_long_parameter = 2...
[ "The Python docs say:\n\nOn Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name\n\nThe manpage of the referenced C function then explains the iss...
[ 17, 2, 1 ]
[]
[]
[ "python", "time", "timing" ]
stackoverflow_0003292865_python_time_timing.txt
Q: define *struct in ctypes I need to convert regexitem *regex to ctype variable, any ideas? C function expects func(regexitem *regex) char *regex1Groups[] = { "a","b","x","s" ,NULL}; char *regex2Groups[] = { "l" ,NULL}; regexitem regex[] = { {"bla", regex1Groups,4 }, {"bla2",reg...
define *struct in ctypes
I need to convert regexitem *regex to ctype variable, any ideas? C function expects func(regexitem *regex) char *regex1Groups[] = { "a","b","x","s" ,NULL}; char *regex2Groups[] = { "l" ,NULL}; regexitem regex[] = { {"bla", regex1Groups,4 }, {"bla2",regex2Groups,1 } }; First i ...
[ "Structs can only contain variable-length arrays at their ends, and on top of that when you assign an array variable to something you aren't copying it, you're assigning the memory location of the first element of the array. So I'm betting that your regexitem struct contains a pointer to the array of char pointers ...
[ 2 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003292840_ctypes_python.txt
Q: python dbus problem I have a problem with dbus and python. Running python from the command line, telling it import dbus and then systembus = dbus.SystemBus() results in no errors, nor does running a program written by a friend which also uses the exact same code. However, when running a program I'm trying to write...
python dbus problem
I have a problem with dbus and python. Running python from the command line, telling it import dbus and then systembus = dbus.SystemBus() results in no errors, nor does running a program written by a friend which also uses the exact same code. However, when running a program I'm trying to write, I get this error: Trace...
[ "The obvious problem is that when you are importing dbus, it is not getting all the methods with it.\nIn both your program and your friend's, do print dbus.__file__. This will show what .pyc it is using. If they are different, you are not importing the correct dbus module.\nI'm going to guess that you are actually...
[ 10 ]
[]
[]
[ "dbus", "python" ]
stackoverflow_0003293172_dbus_python.txt
Q: Accessing only part of a dictionary in a for using Python My example dictionary is this data_dictionary = {1:'blue',2:'green',3:'red',4:'orange',5:'purple',6:'mauve'} The data_dictionary can have more elements depending on the incoming data . The first value is what we call a payload_index. I always get payload_...
Accessing only part of a dictionary in a for using Python
My example dictionary is this data_dictionary = {1:'blue',2:'green',3:'red',4:'orange',5:'purple',6:'mauve'} The data_dictionary can have more elements depending on the incoming data . The first value is what we call a payload_index. I always get payload_index 1 to 4 . I need to assemble a list from this. Pretty easy...
[ "inefficient? That seems like a premature optimisation! Just use normal code:\nfor payload_index in data_dictionary:\n if payload_index != 3:\n assembled_packet.append(data_dictionary[payload_index])\n\nor even better:\nassembled_packet = [data_dictionary[index] for index in data_dictionary if index != 3]...
[ 6, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003292509_python.txt
Q: django forms into database hey guys, im trying to make a volunteer form, that takes info such as name, last name, etc. and i want to save that info into my database (MySQL), so that it can be retrieved later on . A: So first you'll need to define a model that will hold this information, in the models.py file som...
django forms into database
hey guys, im trying to make a volunteer form, that takes info such as name, last name, etc. and i want to save that info into my database (MySQL), so that it can be retrieved later on .
[ "So first you'll need to define a model that will hold this information, in the models.py file something like:\nclass Volunteer(models.Model):\n def __unicode__(self):\n return self.fname + self.lname\n fname = models.CharField(max_length=200)\n lname = models.CharField(max_length=200)\n bio = mo...
[ 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003293316_django_django_forms_python.txt
Q: Command Line in R code Let me start by saying I am new to programming. I am hoping to run a python script from the command line within an R script. I am running windows xp but also have a machine that runs Windows 7. I can run the following code without error for the dos-prompt. cd C:\Documents and Settings\USER...
Command Line in R code
Let me start by saying I am new to programming. I am hoping to run a python script from the command line within an R script. I am running windows xp but also have a machine that runs Windows 7. I can run the following code without error for the dos-prompt. cd C:\Documents and Settings\USER\workspace\UGA - Website pyt...
[ "Thanks for the help everyone. My issue was a combination of things, but this chunk of code worked.\nshell(paste(\"python\", shQuote(\"C:\\\\Documents and Settings\\\\USER\\\\Desktop\\\\UGA New Website\\\\metrics_get.py\")))\n\nMany thanks\n", "Add a / after C:, which would make it look like this:\ncmd.1 <- shQu...
[ 2, 1, 1 ]
[]
[]
[ "command_line", "python", "r" ]
stackoverflow_0003284301_command_line_python_r.txt
Q: Python utf-8 handling I am using Python 2.6.1 and am having utf-8 related problem with my code. This problem is reproducible with this code: # -*- coding: utf-8 -*- import os, sys import string, time import codecs, re bDATA='"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankolé","John Hawkes"' print (bDATA) fil...
Python utf-8 handling
I am using Python 2.6.1 and am having utf-8 related problem with my code. This problem is reproducible with this code: # -*- coding: utf-8 -*- import os, sys import string, time import codecs, re bDATA='"Domenick Lombardozzi","Eddie Marsan","Isaach De Bankolé","John Hawkes"' print (bDATA) fileObj = codecs.open("btvresp...
[ "It looks like the contents of your file are not encoded in UTF-8. Are you sure you didn't save it in some other encoding? When you cat the file, the terminal displays a ? instead of the é, which would also hint at an encoding problem in the file, since your terminal seems to use UTF-8.\nAlso you have two files, bt...
[ 2, 1 ]
[]
[]
[ "python", "python_2.x", "unicode", "utf_8" ]
stackoverflow_0003293055_python_python_2.x_unicode_utf_8.txt
Q: How to walk a tar.gz file that contains zip files without extraction I have a large tar.gz file to analyze using a python script. The tar.gz file contains a number of zip files which might embed other .gz files in it. Before extracting the file, I would like to walk through the directory structure within the compr...
How to walk a tar.gz file that contains zip files without extraction
I have a large tar.gz file to analyze using a python script. The tar.gz file contains a number of zip files which might embed other .gz files in it. Before extracting the file, I would like to walk through the directory structure within the compressed files to see if certain files or directories are present. By looking...
[ "You can't get at it without extracting the file. However, you don't need to extract it to disk if you don't want to. You can use the tarfile.TarFile.extractfile method to get a file-like object that you can then pass to tarfile.open as the fileobj argument. For example, given these nested tarfiles:\n$ cat bar/baz....
[ 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003293809_python.txt
Q: algorithm design in python I need to know about the uniform cost search algorithm. In the uniform cost solution, we find a node that has the lowest cost. But there can be other nodes that have less cost than the previous one.Do we need use some buffer to keep the lowest value in that , so that we can get the lowe...
algorithm design in python
I need to know about the uniform cost search algorithm. In the uniform cost solution, we find a node that has the lowest cost. But there can be other nodes that have less cost than the previous one.Do we need use some buffer to keep the lowest value in that , so that we can get the lowest cost from the whole tree??I n...
[ "You can use the built in function min()\n>>min([3, 2, 4, 1])\n1\n\n", "How is tree built, is lowest cost some function of traversing the tree or only dependent of leaf values? Example input and output would be nice.\nThis Guido's document could be good starting point:\nhttp://python.org/doc/essays/graphs.html\n"...
[ 3, 0, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0003293686_algorithm_python.txt
Q: Problem with nested for loops I have to read two csv file, combine the row and write the result in a third csv file. first csv file have five row with user name in the first colunm.( 25 colunm in total) second csv file have five row with user name in the first colunm and user id in second colunm.(only 2 colunm) ...
Problem with nested for loops
I have to read two csv file, combine the row and write the result in a third csv file. first csv file have five row with user name in the first colunm.( 25 colunm in total) second csv file have five row with user name in the first colunm and user id in second colunm.(only 2 colunm) the third csv file will contain use...
[ "It's because you read off the entire contents of your StringIO object in the first pass, leaving the cursor at the end of the string. On the second pass, there's nothing left to read, so you end up with an empty reader.\nAlso, it's probably not a great idea to call csv.reader() for every inner iteration of your lo...
[ 6, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003292563_python.txt
Q: How to insert dynamic string in wxpython html window? (wx.html.htmlwindow) I am making a html window in wxpython and want to print it. Before that I need to enter user input (such as his name or such things ) in the html page. How to do that nicely? Thanks in advance, A: Use Jinja2. Create an HTML template with...
How to insert dynamic string in wxpython html window? (wx.html.htmlwindow)
I am making a html window in wxpython and want to print it. Before that I need to enter user input (such as his name or such things ) in the html page. How to do that nicely? Thanks in advance,
[ "Use Jinja2.\nCreate an HTML template with variables in the places where you need to display user-entered data. Then render the template with a dictionary containing that data.\nHere, I'll write you a helper module.\n# templates.py\nimport jinja2 as jinja\n\ndef create_env():\n loader = jinja.FileSystemLoader(P...
[ 1, 0 ]
[]
[]
[ "python", "tags", "wxpython" ]
stackoverflow_0003287455_python_tags_wxpython.txt
Q: Multiple select() syscalls from one thread in Python I'm using a couple of Python libraries, and they both use a select() syscall. I was wondering if it was safe to have two select() syscalls from within the same thread (assuming there are no shared descriptors between them)? A: Well, within a single thread you...
Multiple select() syscalls from one thread in Python
I'm using a couple of Python libraries, and they both use a select() syscall. I was wondering if it was safe to have two select() syscalls from within the same thread (assuming there are no shared descriptors between them)?
[ "Well, within a single thread you can't really have \"two select() syscalls\", because the first call has to end before you can start the second call. But yes, it's perfectly safe, even if they do share descriptors: both calls create new objects to return, there's no variable re-use that might affect them (like it ...
[ 2, 0 ]
[]
[]
[ "python", "select", "system_calls" ]
stackoverflow_0003294349_python_select_system_calls.txt
Q: Reading files and writing to database in django I have a Django app that opens a file, continuously reads it, and at the same time writes data to a Postgres database. My issue is that whenever I open a file, file = open(filename, 'r') I am unable to also create new things in the database, Message.objects.create...
Reading files and writing to database in django
I have a Django app that opens a file, continuously reads it, and at the same time writes data to a Postgres database. My issue is that whenever I open a file, file = open(filename, 'r') I am unable to also create new things in the database, Message.objects.create_message(sys, msg) That should create a database ent...
[ "try this:\nfile = open(filename, 'r')\nfileContents = file.read()\nfile.close()\n\n", "Have you tried linecache? Something like this might work (not tested).\nimport linecache\n\ni = 0\ngo = True\nfile = ...\nwhile (go == True):\n out = linecache.getline(file,i)\n ...process out...\n i = i+1\n if i % 100...
[ 3, 2 ]
[]
[]
[ "database", "django", "file", "file_io", "python" ]
stackoverflow_0003293951_database_django_file_file_io_python.txt
Q: Facebook Connect via Javascript doesn't close and doesn't pass session id I'm trying to authenticate users via Facebook Connect using a custom Javascript button: <form> <input type="button" value="Connect with Facebook" onclick="window.open('http://www.facebook.com/login.php?api_key=XXXXX&extern=1&fbconnect=1&req_...
Facebook Connect via Javascript doesn't close and doesn't pass session id
I'm trying to authenticate users via Facebook Connect using a custom Javascript button: <form> <input type="button" value="Connect with Facebook" onclick="window.open('http://www.facebook.com/login.php?api_key=XXXXX&extern=1&fbconnect=1&req_perms=publish_stream,email&return_session=0&v=1.0&next=http%3A%2F%2Fwww.example...
[ "Looks like you might be using the old JS SDK (your code sample is confusing, but the onlogin handler makes me think you are using some SDK). Do yourself a favor and switch to the new JS SDK. Then use XFBML and the <fb:login-button>:\n<fb:login-button perms=\"read_stream\"></fb:login-button>\n\nIt will make your li...
[ 1, 0, 0, 0 ]
[]
[]
[ "facebook", "javascript", "python" ]
stackoverflow_0002715826_facebook_javascript_python.txt
Q: Using csv modele to extract specific lines of text from a larger file So I'm extracting the lines that I want from this larger file using this program: import csv name = ['NAMETHEFIRST,' 'NAMEANOTHERNAME '] data = csv.reader(open('C:\\bigfile.csv')) with open('C:\\smalldataset.xcl','w') as outf: csv.writer(o...
Using csv modele to extract specific lines of text from a larger file
So I'm extracting the lines that I want from this larger file using this program: import csv name = ['NAMETHEFIRST,' 'NAMEANOTHERNAME '] data = csv.reader(open('C:\\bigfile.csv')) with open('C:\\smalldataset.xcl','w') as outf: csv.writer(outf).writerows(l for l in data if l[0] in name) The program runs. However ...
[ "This is a list with one string:\n['NAMETHEFIRST,' 'NAMEANOTHERNAME ']\n\nThis is a list with two strings:\n['NAMETHEFIRST', 'NAMEANOTHERNAME ']\n\nNote the placement of the comma.\nAlso note that your second string has a space at the end.\n", "This line of code\nname = ['NAMETHEFIRST,' 'NAMEANOTHERNAME ']\n\nis ...
[ 1, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0003292488_csv_python.txt
Q: simulate private variables in python Possible Duplicate: private members in python I've got few variables I really want to hide because they do not belong outside my class. Also all such non-documented variables render inheritance useless. How do you hide such variables you don't want to show outside your object...
simulate private variables in python
Possible Duplicate: private members in python I've got few variables I really want to hide because they do not belong outside my class. Also all such non-documented variables render inheritance useless. How do you hide such variables you don't want to show outside your object? To clarify why I need private variables...
[ "Private variables is covered in the Python documentation:\n\n9.6. Private Variables\n“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should b...
[ 15, 11 ]
[]
[]
[ "oop", "private", "python" ]
stackoverflow_0003294764_oop_private_python.txt
Q: Display custom labels for values in the Django Admin Site One of my models has a 'status' field which is only ever modified in code. It is an integer from 1 to 6 (although this may change in the future). However, in the Admin site, I would like to display a label for this data. So, instead of displaying '5', I wou...
Display custom labels for values in the Django Admin Site
One of my models has a 'status' field which is only ever modified in code. It is an integer from 1 to 6 (although this may change in the future). However, in the Admin site, I would like to display a label for this data. So, instead of displaying '5', I would like it to say 'Error'. This means I would be able to easily...
[ "Consider to use choices. Anyway you can customize lots of things in django-admin, just read the docs:\nhttp://docs.djangoproject.com/en/1.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display\nhttp://docs.djangoproject.com/en/1.2/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form\n", "You could ...
[ 4, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0003294855_django_django_admin_django_models_python.txt
Q: Browser-based MMO best-practice I am developing an online browser game, based on google maps, with Django backend, and I am getting close to the point where I need to make a decision on how to implement the (backend) timed events - i.e. NPC possession quantity raising (e.g. city population should grow based on som...
Browser-based MMO best-practice
I am developing an online browser game, based on google maps, with Django backend, and I am getting close to the point where I need to make a decision on how to implement the (backend) timed events - i.e. NPC possession quantity raising (e.g. city population should grow based on some variables - city size, application ...
[ "Running a scheduled task to perform updates in your game, at any interval, will give you a spike of heavy database use. If your game logic relies on all of those database values to be up to date at the same time (which is very likely, if you're running an interval based update), you'll have to have scheduled downt...
[ 5, 2 ]
[]
[]
[ "cron", "django", "python" ]
stackoverflow_0003294682_cron_django_python.txt
Q: Calling a python function over the web using AJAX? I want to send a string to a python function I have written and want to display the return value of that function on a web page. After some initial research, WSGI sounds like the way to go. Preferably, I don't want to use any fancy frameworks. I'm pretty sure some...
Calling a python function over the web using AJAX?
I want to send a string to a python function I have written and want to display the return value of that function on a web page. After some initial research, WSGI sounds like the way to go. Preferably, I don't want to use any fancy frameworks. I'm pretty sure some one has done this before. Need some reassurance. Thanks...
[ "You can try Flask, it's a framework, but tiny and 100% WSGI 1.0 compliant.\nfrom flask import Flask\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n return \"Hello World!\"\n\nif __name__ == \"__main__\":\n app.run()\n\nNote: Flask sits on top of Werkzeug and may need other libraries like sqlalche...
[ 5, 3, 3 ]
[]
[]
[ "ajax", "python", "wsgi" ]
stackoverflow_0003294929_ajax_python_wsgi.txt
Q: modwsgi - Precompiled Binaries for Python 2.4? I'm trying to install Django using Apache and modwsgi on Windows XP. The problem is our whole development environment uses Python 2.4. This page explains how to install modwsgi on Windows but it doesn't link to any precompiled binaries for Python 2.4. Anyone know of ...
modwsgi - Precompiled Binaries for Python 2.4?
I'm trying to install Django using Apache and modwsgi on Windows XP. The problem is our whole development environment uses Python 2.4. This page explains how to install modwsgi on Windows but it doesn't link to any precompiled binaries for Python 2.4. Anyone know of anything, or a workaround?
[ "Follow the instructions in that page about compiling from source code. Simply copy the makefile for 'win32-ap22py26.mk', calling it 'win32-ap22py24.mk' and make changes to paths to the compiler. This is required as Python 2.4 requires an ancient version of Microsoft C/C++ compiler (VS2003 I think). If you don't al...
[ 1 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python", "windows_xp" ]
stackoverflow_0003293194_apache_django_mod_wsgi_python_windows_xp.txt
Q: color plot animation with play, pause, stop cabability using Tkinter with pylab/matplotlib embedding: can't update figure/canvas? I've looked but didn't find previous questions specific enough, so sorry if this is repeated. Goal: GUI to continuously update figure with different matrix data plotted by pylab's pcolo...
color plot animation with play, pause, stop cabability using Tkinter with pylab/matplotlib embedding: can't update figure/canvas?
I've looked but didn't find previous questions specific enough, so sorry if this is repeated. Goal: GUI to continuously update figure with different matrix data plotted by pylab's pcolor such that there is a running animation. But user should be able to play, pause, stop animation by Tkinter widget buttons. Before I ge...
[ "In your blink function, add a self.canvas.show() before calling idle tasks:\nself.canvas.show() # insert this line\nself.canvas.get_tk_widget().update_idletasks()\n\n" ]
[ 2 ]
[]
[]
[ "ipython", "matplotlib", "python", "tkinter" ]
stackoverflow_0003294989_ipython_matplotlib_python_tkinter.txt
Q: How to do this (PHP) in python or ruby? My app takes a loooong list of urls, and split it in X (where X = $threads) so then I can start a thread.php and calculate the urls for it. Then it does GET and POST request to retrieve data I am using this: for($x=1;$x<=$threads;$x++){ $pid[] = exec("/path/bin/php thre...
How to do this (PHP) in python or ruby?
My app takes a loooong list of urls, and split it in X (where X = $threads) so then I can start a thread.php and calculate the urls for it. Then it does GET and POST request to retrieve data I am using this: for($x=1;$x<=$threads;$x++){ $pid[] = exec("/path/bin/php thread.php <options> > /dev/null & echo \$!"); } ...
[ "You don't want threading. You want a work queue like Gearman that you can send jobs to asynchronously. \nIt's worth noting that this is a cross-platform, cross-language solution. There are bindings for many languages (including Python and PHP) provided officially, and many more unofficially with a bit of work w...
[ 1, 1 ]
[]
[]
[ "multithreading", "php", "python", "ruby" ]
stackoverflow_0003294917_multithreading_php_python_ruby.txt
Q: How to install Bazaar to a shared server via SSH? If I have SSH access to a shared server (running centOS) and I want to install Bazaar. I do not have root access, but Python is already installed on the server, so that shouldn't be a problem. I really don't know where to begin after logging into the server. I'm as...
How to install Bazaar to a shared server via SSH?
If I have SSH access to a shared server (running centOS) and I want to install Bazaar. I do not have root access, but Python is already installed on the server, so that shouldn't be a problem. I really don't know where to begin after logging into the server. I'm assuming the first step is to copy the Bazaar application...
[ "From the Installation FAQ:\n\nInstall in home directory\nYou can install Bazaar into home directory, in ~/bin. This method requires that ~/bin is in your $PATH and that ~/lib/python is in your $PYTHONPATH.\n% python setup.py install --home $HOME\n\n\nHowever, if you are truly only using it as a repository, there's...
[ 2 ]
[]
[]
[ "bazaar", "installation", "python" ]
stackoverflow_0003295678_bazaar_installation_python.txt
Q: Create an instance that represents the average of multiple instances I have a Review Model like the one defined below (I removed a bunch of the fields in REVIEW_FIELDS). I want to find the average of a subset of the attributes and populate a ModelForm with the computed information. REVIEW_FIELDS = ['noise'] clas...
Create an instance that represents the average of multiple instances
I have a Review Model like the one defined below (I removed a bunch of the fields in REVIEW_FIELDS). I want to find the average of a subset of the attributes and populate a ModelForm with the computed information. REVIEW_FIELDS = ['noise'] class Review(models.Model): notes = models.TextField(null=True, blank=True) ...
[ "After looking at the docs, I pass a dictionary to the ReviewForm when instantiating it:\nf = ReviewForm(stats)\n\nIt seems to work pretty well! If anyone has any suggestions on a better way to do this, I'm all ears!\n" ]
[ 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003295843_django_django_forms_python.txt
Q: Any good recursive tutorials? Python? Wondering if anyone could point me towards a good recursion tutorial. I am a bit rusty on it as I learned about it in my Data Structures class first semester. Would like to brush up on my recursion...any help? A: Consider this. More seriously… Recursion is a way of solving ...
Any good recursive tutorials? Python?
Wondering if anyone could point me towards a good recursion tutorial. I am a bit rusty on it as I learned about it in my Data Structures class first semester. Would like to brush up on my recursion...any help?
[ "Consider this.\nMore seriously…\nRecursion is a way of solving problems that have a clearly defined base case (or cases, btu I'm keeping it simple here.)\nFor examples, the commonly cited factorial problem is a great one. \nWhat does factorial do? Let's see some examples: \nfactorial(0) = 1\nfactorial(1) = 1\nfact...
[ 11, 5 ]
[]
[]
[ "c++", "python", "recursion" ]
stackoverflow_0003295817_c++_python_recursion.txt
Q: Is there a way to fix vim not-noticing python if statements that have comments? Consider the following block of code- if (1==1):#Go forever print "Wooo." Vim doesn't see the :, due to the comment, so it insists that the print should be at the same indent level as the "if" using http://www.vim.org/scripts/scri...
Is there a way to fix vim not-noticing python if statements that have comments?
Consider the following block of code- if (1==1):#Go forever print "Wooo." Vim doesn't see the :, due to the comment, so it insists that the print should be at the same indent level as the "if" using http://www.vim.org/scripts/script.php?script_id=974 Any thoughts would be appreciated.
[ "Find this in the .vim file:\n\" If the previous line ended with a colon, indent relative to\n\" statement start.\nif pline =~ ':\\s*$'\n\nchange it to...\n\" If the previous line ended with a colon, indent relative to\n\" statement start.\nif pline =~ ':\\s*\\(#.*\\)\\?$'\n\nThat will make it also match lines that...
[ 1 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0003296104_python_vim.txt
Q: Improve performance of self join in sqlite I have a table with 21 columns (all integers) id, c1 , c2 ... c20 and what to fetch ids for rows that have the same values in the columns ... so row 1 will match row 10 if row 1 c1 = row 10 c1 and row 1 c2 = row 10 c2 ... and so on. This is what the query looks like: se...
Improve performance of self join in sqlite
I have a table with 21 columns (all integers) id, c1 , c2 ... c20 and what to fetch ids for rows that have the same values in the columns ... so row 1 will match row 10 if row 1 c1 = row 10 c1 and row 1 c2 = row 10 c2 ... and so on. This is what the query looks like: select r1.id, r2.id from tbl r1, tbl r2 where...
[ "Have you tried a single index on all 20 columns?\n", "You may want to create an extra column, where you can store a hash of all the values in the row. Then simply index that column and filter the rows that match the hash of the 20 values you are searching for.\n" ]
[ 1, 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0003296511_python_sqlite.txt
Q: Rich text to be stored using django If csv file has rich text in it. Using csv.reader() can the same format stored in the Mysql database using django and retrieved back to html pages? Thanks.. A: Text or data has no color or creed. If you have data as text, just store it in text field, if it is binary store it a...
Rich text to be stored using django
If csv file has rich text in it. Using csv.reader() can the same format stored in the Mysql database using django and retrieved back to html pages? Thanks..
[ "Text or data has no color or creed.\nIf you have data as text, just store it in text field, if it is binary store it as a blob. It doesn't matter what that data represents, it can be richtext, pdf, a flash file etc database doesn't care.\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0003296268_django_django_models_django_views_python.txt
Q: Convert a Python snippet to PHP? Can anyone translate my small Python snippet to PHP? I'm not a familiar with both languages. :( matches = re.compile("\"cap\":\"(.*?)\"") totalrewards = re.findall(matches, contents) print totalrewards Thank you for those who'd help! :( A: This is a direct translation of the cod...
Convert a Python snippet to PHP?
Can anyone translate my small Python snippet to PHP? I'm not a familiar with both languages. :( matches = re.compile("\"cap\":\"(.*?)\"") totalrewards = re.findall(matches, contents) print totalrewards Thank you for those who'd help! :(
[ "This is a direct translation of the code above, with \"contents\" populated for demonstration purposes:\n<?php\n$contents = '\"cap\":\"foo\" \"cap\":\"wahey\"';\nif (preg_match_all('/\"cap\":\"(.*?)\"/', $contents, $matches, PREG_SET_ORDER)) {\n var_dump($matches);\n}\n\nThe output:\narray(2) {\n [0]=>\n arra...
[ 1 ]
[]
[]
[ "code_snippets", "php", "python" ]
stackoverflow_0003296592_code_snippets_php_python.txt
Q: GAE WSGIApplication and multiple request In dev_appserver class MainPage(webapp.RequestHandler): def get(self): self.response.out.write("Hello MainPage") class TestPage(webapp.RequestHandler): def get(self): # 10 seconds i = 1 while True: if i == 10: break time.sleep(1) ...
GAE WSGIApplication and multiple request
In dev_appserver class MainPage(webapp.RequestHandler): def get(self): self.response.out.write("Hello MainPage") class TestPage(webapp.RequestHandler): def get(self): # 10 seconds i = 1 while True: if i == 10: break time.sleep(1) i = i + 1 application = webapp.WSGIApplic...
[ "The actual GAE web servers on Google's servers in the clouds support multiple requests easily (indeed their scalability is one of their strengths!), typically by using multiple processes and possibly multiple computers to divide up the load during periods of time in which many requests are coming in fast and furio...
[ 1, 1, 0 ]
[]
[]
[ "google_app_engine", "python", "request" ]
stackoverflow_0003284196_google_app_engine_python_request.txt
Q: Why do I get an error in python saying that a method cannot be found even though I previously defined the method? index = 0 def changeColor(): global index if index%2==0: label.configure(bg = "purple") else: label.configure(bg = "blue") index+=1 label.after(1000, changeColor) ...
Why do I get an error in python saying that a method cannot be found even though I previously defined the method?
index = 0 def changeColor(): global index if index%2==0: label.configure(bg = "purple") else: label.configure(bg = "blue") index+=1 label.after(1000, changeColor) def Start (self): # command when start button is clicked in GUI self.root = Tk() self.root.geometry("500x300"...
[ "It looks to me like the problem might be what's not in the snippet. Are both of these functions part of a class definition? From the use of self as an argument in Start, and label in changeColor, it looks like it might be.\nIf so, let's say it's class Foo, then changeColor is really Foo.changeColor. To use it, you...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003296609_python.txt
Q: many-to-one attributes in Storm My schema looks something like this: CREATE TABLE plans ( id SERIAL PRIMARY KEY, description text ); CREATE TABLE projects ( id SERIAL PRIMARY KEY, project_id character varying(240) UNIQUE, plan_id integer REFERENCES plans(id) ON DELETE CASCADE ); And I want to...
many-to-one attributes in Storm
My schema looks something like this: CREATE TABLE plans ( id SERIAL PRIMARY KEY, description text ); CREATE TABLE projects ( id SERIAL PRIMARY KEY, project_id character varying(240) UNIQUE, plan_id integer REFERENCES plans(id) ON DELETE CASCADE ); And I want to do Storm queries along the lines of ...
[ "For the given SQL, there isn't much reason to use a left join, since your where clause won't match any rows where there isn't a corresponding project. You could get the results with:\nresult = store.find(Plan, Plan.id == Project.plan_id, Project.project_id == \"alpha\")\n\nThis will give you a ResultSet object. ...
[ 2 ]
[]
[]
[ "python", "storm_orm" ]
stackoverflow_0003294975_python_storm_orm.txt
Q: Python: How to call unbound method with other type parameter? Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class A(object): ... def f(self): ... print self.k ... >>> class B(object):pass ... >>> a=A...
Python: How to call unbound method with other type parameter?
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class A(object): ... def f(self): ... print self.k ... >>> class B(object):pass ... >>> a=A() >>> b=B() >>> a.k="a.k" >>> b.k="b.k" >>> a.f() a.k >>> A.f(a) a...
[ "Use the im_func attribute of the method.\nA.f.im_func(b)\n\n" ]
[ 9 ]
[]
[]
[ "methods", "python" ]
stackoverflow_0003296993_methods_python.txt
Q: Python: Xlib -- How can I raise(bring to top) windows? I've tried using: win.configure(stack_mode=X.TopIf) win.set_input_focus(X.RevertToParent, X.CurrentTime) However even without any focus loss prevention on my window manager this does not work, does anyone know of another way to do this? Xlib or not. A:...
Python: Xlib -- How can I raise(bring to top) windows?
I've tried using: win.configure(stack_mode=X.TopIf) win.set_input_focus(X.RevertToParent, X.CurrentTime) However even without any focus loss prevention on my window manager this does not work, does anyone know of another way to do this? Xlib or not.
[ "There is a command-line tool called wmctrl which allows you to interact with EWMH/NetWM-compatible X window managers.\nFor example,\nwmctrl -l\n\nlists all the windows managed by the window manager, and\nwmctrl -a Mozilla \n\nmakes active the first window in the list which has the string \"Mozilla\" in its title.\...
[ 3, 3, 1 ]
[]
[]
[ "linux", "python", "xlib" ]
stackoverflow_0001616628_linux_python_xlib.txt
Q: Where can I find getLevel()? In the code below is using getLevel(). where can I find it (it is about sound, and it run with pyaudio library) # this is the threshold that determines whether or not sound is detected THRESHOLD = 0 #open your audio stream # wait until the sound data breaks some level threshold w...
Where can I find getLevel()?
In the code below is using getLevel(). where can I find it (it is about sound, and it run with pyaudio library) # this is the threshold that determines whether or not sound is detected THRESHOLD = 0 #open your audio stream # wait until the sound data breaks some level threshold while True: data = stream.read(...
[ "You could have a look at https://docs.python.org/library/audioop.html\nThis is another python module to handle audio, but that one does seem to have a method to get the audio level ( max(fragment, width) ).\n", "Look at the imports that have been executed. You'll either find from someModule import getLevel, or f...
[ 2, 0 ]
[]
[]
[ "pyaudio", "python" ]
stackoverflow_0003297354_pyaudio_python.txt
Q: Audio waveform visualisation in Python/Django I've looked around Stack Overflow for an answer to this, but nowhere seems to give the correct answer or direction... My project will allow a user to upload a WAV, which ultimately will be converted to a low quality MP3 using FFmpeg on the server and it'll all be store...
Audio waveform visualisation in Python/Django
I've looked around Stack Overflow for an answer to this, but nowhere seems to give the correct answer or direction... My project will allow a user to upload a WAV, which ultimately will be converted to a low quality MP3 using FFmpeg on the server and it'll all be stored and served on Amazon S3. The next obstacle is wor...
[ "This one (uses audiolab, PIL and numpy) is decent: http://www.freesound.org/blog/?p=10\n", "To make a graph or plot of the waveform, the usual Python appoach is to get the waveform into a numpy array, and then use matplotlib to make the plot. \nThe easiest way to read the data into a numpy array is to use scipy...
[ 8, 6, 3 ]
[]
[]
[ "audio", "django", "python", "visualization", "waveform" ]
stackoverflow_0003290054_audio_django_python_visualization_waveform.txt
Q: Appengine and GWT - feeding the python some java I realize this is a dated question since appengine now comes in java, but I have a python appengine app that I want to access via GWT. Python is just better for server-side text processing (using pyparsing of course!). I have tried to interpret GWT's client-side R...
Appengine and GWT - feeding the python some java
I realize this is a dated question since appengine now comes in java, but I have a python appengine app that I want to access via GWT. Python is just better for server-side text processing (using pyparsing of course!). I have tried to interpret GWT's client-side RPC and that is convoluted since there is no python cou...
[ "The only alternative (if you can call it that) that I'm familiar with is Pyjamas. Obviously, this is more of a GWT replacement than a GWT-RPC replacement. Beyond that, I think you would be stuck with writing your own communications layer using some sort of REST-type protocol.\n", "You can maybe have a look at ...
[ 1, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "gwt", "java", "python" ]
stackoverflow_0001186155_google_app_engine_gwt_java_python.txt
Q: basic http authentication with django-piston I'm a newb to this. I've seen the code snippet at the official site (pasted below). The problem is how do I deploy this to the server ? Where do I set the username and password credentials ? In the httpd.conf file for Apache ? from django.conf.urls.defaults import * f...
basic http authentication with django-piston
I'm a newb to this. I've seen the code snippet at the official site (pasted below). The problem is how do I deploy this to the server ? Where do I set the username and password credentials ? In the httpd.conf file for Apache ? from django.conf.urls.defaults import * from piston.resource import Resource from piston.au...
[ "By default piston.authenticate.HttpBasicAuthentication uses \ndjango.contrib.auth.authenticate to check credentials.\nIn other words: you \"set username and password credentials\" simply by creating normal Django Users.\n" ]
[ 3 ]
[]
[]
[ "django", "django_piston", "python" ]
stackoverflow_0003297125_django_django_piston_python.txt
Q: What's the equivalent of C#'s GetBytes() in Python? I have byte[] request = UTF8Encoding.UTF8.GetBytes(requestParams); in a C# AES encryption only class that I'm converting to Python. Can anyone tell me the Python 2.5 equivalent(I'm using this on google app engine? Example inputs: request_params: &r=p&playerid=...
What's the equivalent of C#'s GetBytes() in Python?
I have byte[] request = UTF8Encoding.UTF8.GetBytes(requestParams); in a C# AES encryption only class that I'm converting to Python. Can anyone tell me the Python 2.5 equivalent(I'm using this on google app engine? Example inputs: request_params: &r=p&playerid=6263017 (or a combination of query strings) dev_key: GK1F...
[ "Don't know where you got the following code from\ndata_bytes = str.encode(request_params)\nkey_bytes = str.encode(dev_key)\niv_bytes = str.encode(dev_iv)\n\nbut you should know that it is equivalent to the following:\ndata_bytes = request_params.encode(\"ascii\")\nkey_bytes = dev_key.encode(\"ascii\")\niv_bytes = ...
[ 2 ]
[ " buffer = file.read(bytes)\n\n" ]
[ -1 ]
[ "aes", "c#", "encryption", "python" ]
stackoverflow_0003297030_aes_c#_encryption_python.txt
Q: File upload with django What is wrong with the following code for file uploading.The request.FILES['file'] looks empty Models: from django.db import models from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField(label="Your file"...
File upload with django
What is wrong with the following code for file uploading.The request.FILES['file'] looks empty Models: from django.db import models from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField(label="Your file") Views: def index(request):...
[ "You need to set enctype attribute on your form:\n<form enctype=\"multipart/form-data\" method=\"post\" action=\"/foo/\">\n\nLike they say in the docs.\n" ]
[ 7 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0003298176_django_django_models_django_templates_django_views_python.txt
Q: Forcing a variable to be an integer errors = int(0) for i in range(len(expectedData)): if data[i] != expectedData[i]: errors += int(binary_compare(data[i], expectedData[i])) return errors I have the above code which I am trying to use to calculate some integer (number of errors) for some data. I have...
Forcing a variable to be an integer
errors = int(0) for i in range(len(expectedData)): if data[i] != expectedData[i]: errors += int(binary_compare(data[i], expectedData[i])) return errors I have the above code which I am trying to use to calculate some integer (number of errors) for some data. I have casted everything I can see possible as ...
[ "python is not javascript\nit's no way to get concatenated strings instead of math sum, when you do count += value starting with count = 0. if you try to add a string to integer, exception is raised:\n>>> x = 0\n>>> x += \"1\"\nTypeError: unsupported operand type(s) for +=: 'int' and 'str'\n\nto compare values of w...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003292718_python.txt
Q: trickle down unit tests If I'm writing a library in C that includes a Python interface, is it OK to just write unit tests for the functions, etc in the Python interface? Assuming the Python interface is complete, it should imply the C code works. Mostly I'm being lazy in that the Python unit test thing takes almos...
trickle down unit tests
If I'm writing a library in C that includes a Python interface, is it OK to just write unit tests for the functions, etc in the Python interface? Assuming the Python interface is complete, it should imply the C code works. Mostly I'm being lazy in that the Python unit test thing takes almost zero effort to use. thanks,...
[ "Tests through the Python interface will be valuable acceptance tests for your library. They will not however be unit tests.\nUnit tests are written by the same coders, in the same language, on the same platform as the unit which they test. These should be written too!\nYou're right, though, unit testing in Python ...
[ 5, 1, 0, 0 ]
[]
[]
[ "c", "python", "unit_testing" ]
stackoverflow_0003294526_c_python_unit_testing.txt
Q: How do I get a windows border like this in Tkinter? Is there any way to get a border like this in Tkinter? Notice how it lacks the buttons on the top right. Also I don't want this program to show in the task bar. This is in windows 7, btw. A: Tk (and thus, Tkinter) has a command for removing all window manager...
How do I get a windows border like this in Tkinter?
Is there any way to get a border like this in Tkinter? Notice how it lacks the buttons on the top right. Also I don't want this program to show in the task bar. This is in windows 7, btw.
[ "Tk (and thus, Tkinter) has a command for removing all window manager decoration. This command in tkinter is the \"wm_overrideredirect\" method of toplevel windows. Pass it a parameter of True to remove the window manager decorations. You can then draw whatever borders you want, usually by packing a canvas over the...
[ 2, 1 ]
[]
[]
[ "python", "tkinter", "user_interface", "windows_7" ]
stackoverflow_0003295659_python_tkinter_user_interface_windows_7.txt
Q: sort a dictionary according to their values in python Possible Duplicate: Sort by key of dictionary inside a dictionary in Python I have a dictionary: d={'abc.py':{'map':'someMap','distance':11}, 'x.jpg':{'map':'aMap','distance':2},....} Now what I need is: I need to sort d according to their distances? I tr...
sort a dictionary according to their values in python
Possible Duplicate: Sort by key of dictionary inside a dictionary in Python I have a dictionary: d={'abc.py':{'map':'someMap','distance':11}, 'x.jpg':{'map':'aMap','distance':2},....} Now what I need is: I need to sort d according to their distances? I tried sorted(d.items(),key=itemgetter(1,2), but it's not wor...
[ "You cannot (really) influence the order in which your dict keys appear. If you want to iterate over the sorted keys, you could for instance use\nsorted(d.keys(), key=lambda x: d[x]['distance'])\n\n", "A dictonary can't be sorted. So you have to convert your data to a list and sort this list.\nMaybe you convert y...
[ 4, 3, 1 ]
[]
[]
[ "dictionary", "key", "python", "sorting" ]
stackoverflow_0003298629_dictionary_key_python_sorting.txt
Q: Delete an item from a list Hey, I was trying to delete an item form a list (without using set): list1 = [] for i in range(2,101): for j in range(2,101): list1.append(i ** j) list1.sort() for k in range(1,len(list1) - 1): if (list1[k] == list1[k - 1]): list1.remove(list1[k]) print "length = ...
Delete an item from a list
Hey, I was trying to delete an item form a list (without using set): list1 = [] for i in range(2,101): for j in range(2,101): list1.append(i ** j) list1.sort() for k in range(1,len(list1) - 1): if (list1[k] == list1[k - 1]): list1.remove(list1[k]) print "length = " + str(len(list1)) The set fun...
[ "Your code doesn't work because in your loop, you are iterating over all the indexes in the original list, but shortening the list as you go. At the end of the iteration, you will be accessing indexes that no longer exist:\nfor k in range(1,len(list1) - 1):\n if (list1[k] == list1[k - 1]):\n list1.remove...
[ 5, 3, 2, 1 ]
[]
[]
[ "list", "python", "unique" ]
stackoverflow_0003299128_list_python_unique.txt
Q: Django admin style application for Java I'm looking for a web framework or an application in Java that does what Django admin does - provides a friendly user interface for editing data in a relational database. I know it's possible to run Django on Jython and that way achieve a somewhat Java-based solution, but I'...
Django admin style application for Java
I'm looking for a web framework or an application in Java that does what Django admin does - provides a friendly user interface for editing data in a relational database. I know it's possible to run Django on Jython and that way achieve a somewhat Java-based solution, but I'd prefer something pure-Java to keep the high...
[ "Try Grails. It's a framework modeled after Django, written in Groovy. Groovy is a JVM based language, source-compatible with Java.\nTo get a Django-like admin interface, you write your models, let Grails generate all the rest (controllers and views), and you're done.\nSome resources:\n\nQuick Start Tutorial\nScree...
[ 4, 4, 0 ]
[]
[]
[ "django", "java", "python" ]
stackoverflow_0000706405_django_java_python.txt
Q: How do I make a nasty C++ program scriptable with Python and/or Lua? I'm confronted with the task of making a C++ app scriptable by users. The app has been in development for several years with no one wasting a thought on this before. It contains all sorts of niceties like multithreading, template wizardry and mul...
How do I make a nasty C++ program scriptable with Python and/or Lua?
I'm confronted with the task of making a C++ app scriptable by users. The app has been in development for several years with no one wasting a thought on this before. It contains all sorts of niceties like multithreading, template wizardry and multiple inheritance. As the scripting language, Python is preferred, but Lua...
[ "I wouldn't recommend swig as it's hard to get it to generate satisfactory binding in complex situations: been there, done that. I had to write a horrible script that \"parsed\" the original C++ code to generate some acceptable C++ code that swig could chew and generate acceptable bindings. So, in general: avoid ...
[ 12, 1, 1, 0, 0 ]
[]
[]
[ "binding", "c++", "lua", "python", "scriptable" ]
stackoverflow_0003299067_binding_c++_lua_python_scriptable.txt
Q: adding 2 1/2 hours to a time object in python I need to be able to convert time on an time object I recieve from a sql database into python. Here is the current python code I am using without any conversions. I need to add 2 and 1/2 hours to the time. def getLastReport(self, sql): self.connectDB() cursor....
adding 2 1/2 hours to a time object in python
I need to be able to convert time on an time object I recieve from a sql database into python. Here is the current python code I am using without any conversions. I need to add 2 and 1/2 hours to the time. def getLastReport(self, sql): self.connectDB() cursor.execute(sql) lastReport = cursor.fetchall() ...
[ "Have you looked at the datetime module? http://docs.python.org/library/datetime.html\nConvert your SQL time into a datetime, and make a timedelta object of 2.5 hours. Then add the two.\nfrom datetime import datetime\n\ndt = datetime.strptime( date, '%Y-%m-%d %H:%M' )\ndt_plus_25 = dt + datetime.timedelta( 0, 2*6...
[ 3, 1, 1, 0 ]
[]
[]
[ "mysql", "python", "time" ]
stackoverflow_0003298935_mysql_python_time.txt
Q: how to move all those imports to standalone file Imagine situation: I have view directory with tons of different views. all views have about 6 lines with imports - in the beginning of the file. it's pretty damn hard copy paste those 6 lines every time I create new view. I usually using all those imports. from dja...
how to move all those imports to standalone file
Imagine situation: I have view directory with tons of different views. all views have about 6 lines with imports - in the beginning of the file. it's pretty damn hard copy paste those 6 lines every time I create new view. I usually using all those imports. from django.contrib.auth.models import User from django.contri...
[ "You could put them in a module, say imports.py, and then do this in your views:\nfrom imports import *\n\nBut I think most Python programmers would argue (and I'd agree) that it's probably better to list your imports at the top of the module file where you actually use them, like you're already doing. It may seem ...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003300568_django_python.txt
Q: SQLAlchemy truncating Column=(Integer) weird issue here: I have a reflected SQL alchemy class that looks like this: class Install(Base): __tablename__ = 'install' id = Column(Integer, primary_key=True) ip_address = Column(Integer) I convert the string representation ("1.2.3.4") to int using: struct.un...
SQLAlchemy truncating Column=(Integer)
weird issue here: I have a reflected SQL alchemy class that looks like this: class Install(Base): __tablename__ = 'install' id = Column(Integer, primary_key=True) ip_address = Column(Integer) I convert the string representation ("1.2.3.4") to int using: struct.unpack('!L', socket.inet_aton(ip_address))[0] ...
[ "Fixed it!\nFor MySQL:\nMake sure you are using unsigned INTs, and then use the mysql.MSInteger(unsigned=True) type:\nfrom sqlalchemy.databases import mysql\n[..]\nclass Install(Base):\n __tablename__ = 'install'\n id = Column(Integer, primary_key=True)\n ip_address = Column(mysql.MSInteger(unsigned=True))...
[ 3 ]
[]
[]
[ "integer", "mysql", "python", "sqlalchemy" ]
stackoverflow_0003300406_integer_mysql_python_sqlalchemy.txt
Q: How do I set a breakpoint in a module other than the one I am running in Python IDLE? If I edit two modules, eggs and ham, and module eggs imports ham, how do I run module eggs such that IDLE stops at breakpoints set in ham? So far, I have only been able to get IDLE to recognize breakpoints set in the module actua...
How do I set a breakpoint in a module other than the one I am running in Python IDLE?
If I edit two modules, eggs and ham, and module eggs imports ham, how do I run module eggs such that IDLE stops at breakpoints set in ham? So far, I have only been able to get IDLE to recognize breakpoints set in the module actually being run, not those being imported.
[ "\nstart IDLE\nopen eggs, open ham\nset desired breakpoints in both files\ngo to IDLE's shell, select Debug=>Debugger\ngo back to eggs and to run.\n\nYou should stop at break points in each file. (It works, I just tested it.)\n" ]
[ 8 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0003300665_python_python_idle.txt
Q: Mapping python tuple and R list with rpy2? I'm having some trouble to understand the mapping with rpy2 object and python object. I have a function(x) which return a tuple object in python, and i want to map this tuple object with R object list or vector. First, i'm trying to do this : # return a python tuple into ...
Mapping python tuple and R list with rpy2?
I'm having some trouble to understand the mapping with rpy2 object and python object. I have a function(x) which return a tuple object in python, and i want to map this tuple object with R object list or vector. First, i'm trying to do this : # return a python tuple into this r object tlist robjects.r.tlist = get_max_t...
[ "Use globalEnv:\nimport rpy2.robjects as ro\nr=ro.r\n\ndef get_max_ticks():\n return (1,2)\nro.globalEnv['tlist'] = ro.FloatVector(get_max_ticks())\nr('x <- as.data.frame(tlist,row.names=c(\"seed\",\"ticks\"))')\nprint(r['x'])\n# tlist\n# seed 1\n# ticks 2\n\nIt may be possible to access symbols i...
[ 3, 0 ]
[]
[]
[ "mapping", "python", "r", "rpy2", "tuples" ]
stackoverflow_0003300671_mapping_python_r_rpy2_tuples.txt
Q: Have well-defined, narrowly-focused classes ... now how do I get anything done in my program? I'm coding a poker hand evaluator as my first programming project. I've made it through three classes, each of which accomplishes its narrowly-defined task very well: HandRange = a string-like object (e.g. "AA"). getHands...
Have well-defined, narrowly-focused classes ... now how do I get anything done in my program?
I'm coding a poker hand evaluator as my first programming project. I've made it through three classes, each of which accomplishes its narrowly-defined task very well: HandRange = a string-like object (e.g. "AA"). getHands() returns a list of tuples for each specific hand within the string: [(Ad,Ac),(Ad,Ah),(Ad,As),(Ac,...
[ "Don't make a fetish of object orientation -- Python supports multiple paradigms, after all! Think of your user-defined types, AKA classes, as building blocks that gradually give you a \"language\" that's closer to your domain rather than to general purpose language / library primitives.\nAt some point you'll want...
[ 3, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003300575_oop_python.txt
Q: @StaticMethod or @ClassMethod decoration on magic methods I am trying to decorate the magic method __getitem__ to be a classmethod on the class. Here is a sample of what I tried. I don't mind using either classmethod or staticmethod decoration, but I am not too sure how to do it. Here is what I tried: import Confi...
@StaticMethod or @ClassMethod decoration on magic methods
I am trying to decorate the magic method __getitem__ to be a classmethod on the class. Here is a sample of what I tried. I don't mind using either classmethod or staticmethod decoration, but I am not too sure how to do it. Here is what I tried: import ConfigParser class Settings(object): _env = None _config = No...
[ "Python always looks up __getitem__ and other magic methods on the class, not on the instance. So, for example, defining a __getitem__ in a metaclass means that you can index the class (but you can't define it by delegating to a non-existent __getitem__ in type -- just as you can never define anything by delegating...
[ 6, 1 ]
[]
[]
[ "decorator", "magic_methods", "python", "static_methods" ]
stackoverflow_0003301220_decorator_magic_methods_python_static_methods.txt
Q: Using Web2Py in Making a blog in Python (Google App Engine)? Is it a good Idea? I know there are tons of blogging platforms out there (Wordpress,Drupal,etc) but I want to make my own blog engine or blog platform from scratch using python as a learning tool. The idea of using Google App Engine solves the issues in ...
Using Web2Py in Making a blog in Python (Google App Engine)? Is it a good Idea?
I know there are tons of blogging platforms out there (Wordpress,Drupal,etc) but I want to make my own blog engine or blog platform from scratch using python as a learning tool. The idea of using Google App Engine solves the issues in hosting. Blogs relatively consumes less amount of disk space and If it scales then th...
[ "You can use this to build a blogging platform on Google App Engine with web2py. You may want to customize the layout using this.\n", "Learning exercises, like the one you want to undertake, are just about the only good reason to reinvent the wheel -- and using a very lightweight framework can be more instructive...
[ 5, 2 ]
[]
[]
[ "blogs", "google_app_engine", "python", "web2py" ]
stackoverflow_0003276194_blogs_google_app_engine_python_web2py.txt
Q: How to check for EOF when using pipe file descriptors in Python? I have 2 threads, Thread A and Thread B. Thread A takes data from either sys.stdin or from the read end of a pipe (using os.pipe()). Whatever data gets read (from either sys.stdin or from the read end of the pipe) gets sent out on a TCP socket. Thr...
How to check for EOF when using pipe file descriptors in Python?
I have 2 threads, Thread A and Thread B. Thread A takes data from either sys.stdin or from the read end of a pipe (using os.pipe()). Whatever data gets read (from either sys.stdin or from the read end of the pipe) gets sent out on a TCP socket. Thread A uses select.select() to determine whether it should read from sy...
[ "The only way to check for EOF on the pipe is to read from it. In fact, when you close the write-end of the pipe, select.select() will say the socket is ready for reading, even if there's no actual data to be read. When you read from the read-end, the empty string ('') will indicate EOF. This won't block your read ...
[ 7 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0003301253_linux_python.txt
Q: PyDev Setting breakpoints in doctests Is it possible to set breakpoints in doctests, using PyDev (i.e. eclipse)? I found that while I am seemingly able to do so, the breakpoints do not work at all. To have some code in the question, and to clarify, say I have def funct(): """ >>> funct() Whatever """ pr...
PyDev Setting breakpoints in doctests
Is it possible to set breakpoints in doctests, using PyDev (i.e. eclipse)? I found that while I am seemingly able to do so, the breakpoints do not work at all. To have some code in the question, and to clarify, say I have def funct(): """ >>> funct() Whatever """ print "Whatever" and that I set a breakpoint...
[ "I don't think you can set breakpoints in strings. \ndoctest is a module for automated testing. If you need to debug your doctest code, why not run it normally and verify the output, then once you know it works, throw it into a docstring?\n" ]
[ 0 ]
[]
[]
[ "breakpoints", "doctest", "eclipse", "pydev", "python" ]
stackoverflow_0003301514_breakpoints_doctest_eclipse_pydev_python.txt
Q: Verifying constructor parameters in Python What is the best-practice method for verifying constructor params in Python? I am new to the language, and am using raise: class Breakfast(object): def __init__(self, spam=None, eggs=0): if not spam: raise Error("Error: no spam") Is this stupid, o...
Verifying constructor parameters in Python
What is the best-practice method for verifying constructor params in Python? I am new to the language, and am using raise: class Breakfast(object): def __init__(self, spam=None, eggs=0): if not spam: raise Error("Error: no spam") Is this stupid, or what? Thanks!
[ "If you are just trying to make sure that required parameters are passed, just leave off the default value. Python will then automatically throw a TypeError if a parameter is missing.\ndef __init__( self, spam, eggs=0 )\n\n", "If the argument isn't optional, why are you providing a default argument for it? The P...
[ 4, 3, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003301745_python.txt
Q: best scripting language to develop rational clearcase plugin to extract some functionalities I just want to know about clearcase. Basically i want to write some application which will extract some files from clearcase vobs. Right now i am not getting any clue that which scripting language like python or perl i sho...
best scripting language to develop rational clearcase plugin to extract some functionalities
I just want to know about clearcase. Basically i want to write some application which will extract some files from clearcase vobs. Right now i am not getting any clue that which scripting language like python or perl i should use. basically i am looking for perl scripting for that. I also want to know is there any prop...
[ "The official API is cleartool, the command line interface which contains all ClearCase commands.\nYou can call cleartool commands from a Perl script (like in this question)\nAn example of a Perl library able to call cleartool command is here.\nThe other scripting interface is ClearCase Automation Library (CAL).\nS...
[ 1 ]
[]
[]
[ "clearcase", "perl", "python" ]
stackoverflow_0003301579_clearcase_perl_python.txt
Q: Python cached list I have a module which supports creation of geographic objects using a company-standard interface. After these objects are created, the update_db() method is called, and all objects are updated into a database. It is important to have all objects inserted in one session, in order to keep counters...
Python cached list
I have a module which supports creation of geographic objects using a company-standard interface. After these objects are created, the update_db() method is called, and all objects are updated into a database. It is important to have all objects inserted in one session, in order to keep counters and statistics before u...
[ "Use shelve. Your keys are the indices to your list. \n", "I think your first question is answered. On the second, forcing GC: use gc.collect. http://docs.python.org/library/gc.html. \n" ]
[ 5, 2 ]
[]
[]
[ "caching", "data_structures", "list", "python" ]
stackoverflow_0003301789_caching_data_structures_list_python.txt
Q: Import module CairoPlot fails in Python I'm using cairo plot to draw charts with python. I followed the instruction as stated on the website to install Cairplot, http://linil.wordpress.com/2008/09/16/cairoplot-11/ : sudo apt-get install bzr bzr branch lp:cairoplot/1.1 The installation completes successfully. I t...
Import module CairoPlot fails in Python
I'm using cairo plot to draw charts with python. I followed the instruction as stated on the website to install Cairplot, http://linil.wordpress.com/2008/09/16/cairoplot-11/ : sudo apt-get install bzr bzr branch lp:cairoplot/1.1 The installation completes successfully. I then try to import the modules in python: >>...
[ "bzr branch lp:cairoplot/1.1 creates a directory called 1.1 in your current working directory. Inside you'll find CairoPlot.py. Move CairoPlot.py into a directory which is listed in your PYTHONPATH, or edit your PYTHONPATH to include (the unfortunately named) 1.1.\n", "Is the directory where CairoPlot is installe...
[ 2, 0 ]
[]
[]
[ "cairoplot", "python" ]
stackoverflow_0003301846_cairoplot_python.txt
Q: Using Python property() inside a method Assuming you know about Python builtin property: http://docs.python.org/library/functions.html#property I want to re-set a object property in this way but, I need to do it inside a method to be able to pass to it some arguments, currently all the web examples of property() a...
Using Python property() inside a method
Assuming you know about Python builtin property: http://docs.python.org/library/functions.html#property I want to re-set a object property in this way but, I need to do it inside a method to be able to pass to it some arguments, currently all the web examples of property() are defining the property outside the methods,...
[ "Properties work using the descriptor protocol, which only works on attributes of a class object. The property object has to be stored in a class attribute. You can't \"override\" it on a per-instance basis.\nYou can, of course, provide a property on the class that gets an instance attribute or falls back to some d...
[ 5, 1 ]
[]
[]
[ "decorator", "properties", "python" ]
stackoverflow_0003302020_decorator_properties_python.txt
Q: Anjuta IDE - Simple Python Question I'm new to Linux, Python and the Anjuta IDE. I have created a new file called hello.py. This is the contents of that file: #!/usr/bin/env python print "Hello World!" All I want to do is run this in the terminal. I go to Run > Execute but I get the following error message: Prog...
Anjuta IDE - Simple Python Question
I'm new to Linux, Python and the Anjuta IDE. I have created a new file called hello.py. This is the contents of that file: #!/usr/bin/env python print "Hello World!" All I want to do is run this in the terminal. I go to Run > Execute but I get the following error message: Program 'home/joe/Programming/Python//hello.p...
[ "open a shell, cd to the folder where the file is located and execute chmod +x hello.py.\n", "ZeissS' solution will work and is generally preferred to this, but for the sake of completeness, you could also open a shell, cd to the appropriate directory, and type:\n\npython hello.py\n\n" ]
[ 4, 2 ]
[]
[]
[ "linux", "permissions", "python", "ubuntu" ]
stackoverflow_0003302071_linux_permissions_python_ubuntu.txt
Q: Foreign key relationships missing when reflecting db in SqlAlchemy I am attempting to use SqlAlchemy (0.5.8) to interface with a legacy database declaratively and using reflection. My test code looks like this: from sqlalchemy import * from sqlalchemy.orm import create_session from sqlalchemy.ext.declarative impor...
Foreign key relationships missing when reflecting db in SqlAlchemy
I am attempting to use SqlAlchemy (0.5.8) to interface with a legacy database declaratively and using reflection. My test code looks like this: from sqlalchemy import * from sqlalchemy.orm import create_session from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() engine = create_engine('or...
[ "After debugging the script + SqlAlchemy code with Eclipse, I found that the list of tables/columns is kept internally in lower case. As such, there was never any possibility of a match between EXPRESSION.foreignkey and expression.foreignkey. Hence the error message.\nDigging deep into the SqlAlchemy documentation ...
[ 6 ]
[]
[]
[ "oracle10g", "python", "sqlalchemy" ]
stackoverflow_0003301139_oracle10g_python_sqlalchemy.txt
Q: Writing file line to Django model field I can't seem to write a line from a file to a field of a Django model. The field is described in the model as: text = models.TextField(null=True, blank=True, help_text='A status message.') However, when I attempt to create a new object I cannot fill this field using the re...
Writing file line to Django model field
I can't seem to write a line from a file to a field of a Django model. The field is described in the model as: text = models.TextField(null=True, blank=True, help_text='A status message.') However, when I attempt to create a new object I cannot fill this field using the readline function: file = open(filename, 'r') s...
[ "Don't create variable names which conflict with python built in types. \"str\" is the string type.Python interpreter:\n>> str\n<type 'str'>\n\n", "I think you're not calling the create_message method properly. Shouldn't you just call it like this\ncreate_message(sys, str)\n\ninstead of this\nMessage.objects.crea...
[ 2, 0 ]
[]
[]
[ "database", "django", "file", "file_io", "python" ]
stackoverflow_0003301988_database_django_file_file_io_python.txt
Q: reordering list of dicts arbitrarily in python I have a list of 4 dicts (always 4) that look something like this: [{'id':'1','name':'alfa'},{'id':'2','name':'bravo'},{'id':'3','name':'charlie'},{'id':'4','name':'delta'}] I know exactly the order I want them in, which is: 2, 3, 1, 4 what's the simplest way of reo...
reordering list of dicts arbitrarily in python
I have a list of 4 dicts (always 4) that look something like this: [{'id':'1','name':'alfa'},{'id':'2','name':'bravo'},{'id':'3','name':'charlie'},{'id':'4','name':'delta'}] I know exactly the order I want them in, which is: 2, 3, 1, 4 what's the simplest way of reordering them?
[ "If it's always four, and you always know the order, just simply like this:\nlst = [{...},{...},{...},{...}]\nordered = [lst[1],lst[2],lst[0],lst[3]]\n\nIf you meant to sort them by 'id', in that order:\nordered = sorted(lst, key=lambda d: [2,3,1,4].index(int(d['id'])))\n\nNote that index() is O(n) but doesn't requ...
[ 4, 3, 2, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003301406_list_python.txt