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: Performance issues using Tesseract OCR from a Python application I recently put together an interface for scanning and uploading searchable documents to KnowledgeTree, our document management system. We have access to plenty of separate tools for different parts of this process, but I wanted to combine everything...
Performance issues using Tesseract OCR from a Python application
I recently put together an interface for scanning and uploading searchable documents to KnowledgeTree, our document management system. We have access to plenty of separate tools for different parts of this process, but I wanted to combine everything into one interface to keep things simple for the users. Here's the ...
[ "The problem you are having is that Tesseract is an OCR engine, not page layout analysis software. The tesseract website says that version 3.0 will probably include page layout analysis.\nI know in previous versions it only responds well if there is a single column of text.\nI think you need to put in a step 1.5 th...
[ 1 ]
[]
[]
[ "ocr", "python", "tesseract" ]
stackoverflow_0004763956_ocr_python_tesseract.txt
Q: Faster App Engine Development Datastore Alternative Is there a way to use a real database(SQLite, Mysql, or even some non-relational one) as datastore for development, instead of memory/file datastore that is provided. I saw few projects, GAE-SQLite(did not seem to be working) and one tip about accessing producti...
Faster App Engine Development Datastore Alternative
Is there a way to use a real database(SQLite, Mysql, or even some non-relational one) as datastore for development, instead of memory/file datastore that is provided. I saw few projects, GAE-SQLite(did not seem to be working) and one tip about accessing production datastore using remote api (still pretty slow for larg...
[ "MongoDB works great for that. You will need:\n\nThe MongoDB stub: http://github.com/mongodb/mongo-appengine-connector\nMongoDB: http://www.mongodb.org/display/DOCS/Downloads\nSome code to set it up like:\n\ncode:\nimport datastore_mongo_stub\n\nos.environ['APPLICATION_ID'] = 'test'\n\ndatastore = datastore_mongo_s...
[ 4, 2, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002112950_google_app_engine_google_cloud_datastore_python.txt
Q: Running an external program (executable) with parameters in python I am trying to automate a command line program. The exe file takes one argument to run. For example: ztac.exe <mode> (where mode options are safe, normal or debug). To run in debug mode I simply type this in the command line: C:\source>ztac debug H...
Running an external program (executable) with parameters in python
I am trying to automate a command line program. The exe file takes one argument to run. For example: ztac.exe <mode> (where mode options are safe, normal or debug). To run in debug mode I simply type this in the command line: C:\source>ztac debug How do I write a Python program to run this ztac.exe file while taking th...
[ "program = 'ztac.exe'\narguments = ('safe', 'normal', 'debug')\nargument = raw_input('Enter your argument: ')\nif argument in arguments:\n subprocess.call([program, argument])\nelse:\n print('Illegal Argument')\n\n" ]
[ 2 ]
[]
[]
[ "command_line_arguments", "python" ]
stackoverflow_0004813889_command_line_arguments_python.txt
Q: Fetch only the last 128 bytes of an mp3 file over a http connection I have been looking for an example of how python could fetch only the last 128 bytes of an mp3 file over a http connection. Is it possible to do range specific file access over HTTP in python? A: Yes, it is possible to do it via HTTP using urll...
Fetch only the last 128 bytes of an mp3 file over a http connection
I have been looking for an example of how python could fetch only the last 128 bytes of an mp3 file over a http connection. Is it possible to do range specific file access over HTTP in python?
[ "Yes, it is possible to do it via HTTP using urllib2.\nclass HTTPRangeHandler(urllib2.BaseHandler):\n\n def http_error_206(self, req, fp, code, msg, hdrs):\n # Range header supported\n r = urllib.addinfourl(fp, hdrs, req.get_full_url())\n r.code = code\n r.msg = msg\n return r\...
[ 9, 5, 1 ]
[]
[]
[ "http", "mp3", "python", "tags" ]
stackoverflow_0004814137_http_mp3_python_tags.txt
Q: how to efficiently strip a string with delimiting characters on both ends? good day guys! suppose i have a string with a format like so ^a.b.c^ and i want to only get a.b.c . can you teach me a more efficient way to strip the delimiters than my code below? thanks ### line = '^123.456.102345^' start = line.find ('^...
how to efficiently strip a string with delimiting characters on both ends?
good day guys! suppose i have a string with a format like so ^a.b.c^ and i want to only get a.b.c . can you teach me a more efficient way to strip the delimiters than my code below? thanks ### line = '^123.456.102345^' start = line.find ('^') line = line[(start+1):] end = line.find ('^') line = line[:end] print line
[ ">>> s = '^a.b.c^'\n>>> s.strip('^')\n'a.b.c'\n\nCheck out the docs for str.strip\n" ]
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0004814639_python.txt
Q: AttributeError when using replace_urlpattern in Satchmo I'm trying to override the default category view in Satchmo. I'm successfully overriding other views with no problems, but this one is throwing an error. Here is the code I'm using in my root urls.py to override the default category view: replacement = ur...
AttributeError when using replace_urlpattern in Satchmo
I'm trying to override the default category view in Satchmo. I'm successfully overriding other views with no problems, but this one is throwing an error. Here is the code I'm using in my root urls.py to override the default category view: replacement = url(r'^(?P<parent_slugs>([-\w]+/)*)?(?P<slug>[-\w]+)/$', 'pasma...
[ "Notice the trailing comma in your first line. You are assigning replacement a one-tuple containing the result of url() call: same as replacement = (url(...),).\n" ]
[ 2 ]
[]
[]
[ "django", "python", "satchmo" ]
stackoverflow_0004814813_django_python_satchmo.txt
Q: Avoid Redundancy in Python I recently started using Python 2.6 for Ubuntu Server admin and have two minor issues concerning redundancy: First thing are imports: They all look something like import Class from Class from class import Class And the second thing are __init__ methods: __init__(self,arg1,...,argn): ...
Avoid Redundancy in Python
I recently started using Python 2.6 for Ubuntu Server admin and have two minor issues concerning redundancy: First thing are imports: They all look something like import Class from Class from class import Class And the second thing are __init__ methods: __init__(self,arg1,...,argn): self.arg1 = arg1 ... s...
[ "The second thing is not redundancy - it is setting instance attributes. You can do it also like this:\nclass Foo:\n\n def __init__(self, **kwargs):\n for name, value in kwargs.items():\n setattr(self, name, value)\n\nBut then you need to call Foo like this:\n Foo(arg1=1, arg2=2, arg3=3)\n\nAlso ...
[ 8, 2, 1 ]
[]
[]
[ "import", "init", "python", "redundancy" ]
stackoverflow_0004814655_import_init_python_redundancy.txt
Q: Querying datastore for all models that contain a certain element within a listproperty Hey, I have a model like this: class List(db.Model): user = db.ReferenceProperty(User) listname = db.StringProperty() published = db.DateTimeProperty(auto_now_add=True) score = db.IntegerProperty(required=False) ...
Querying datastore for all models that contain a certain element within a listproperty
Hey, I have a model like this: class List(db.Model): user = db.ReferenceProperty(User) listname = db.StringProperty() published = db.DateTimeProperty(auto_now_add=True) score = db.IntegerProperty(required=False) tld = db.StringProperty(required=False) categories = db.StringListProperty() Where ...
[ "Oops, I solved it sorry for the bother! For anyone who's interested you can just use a query like this:\nSELECT * FROM List where categories = 'Philosophy'\n\nWhich will match any list which has 'Philosophy' within the categories.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "gql", "listproperty", "python" ]
stackoverflow_0004773895_google_app_engine_gql_listproperty_python.txt
Q: How do I get a website's IP address using Python 3.x? I have a string representing a domain name. How can I get the corresponding IP address using Python 3.x? Something like this: >>> get_ip('http://www.stackoverflow.com') '64.34.119.12' A: Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Int...
How do I get a website's IP address using Python 3.x?
I have a string representing a domain name. How can I get the corresponding IP address using Python 3.x? Something like this: >>> get_ip('http://www.stackoverflow.com') '64.34.119.12'
[ "Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on win32\n>>> import socket\n>>> socket.gethostbyname('cool-rr.com')\n'174.120.139.162'\n\nNote that:\n\ngethostbyname() doesn't work with IPv6.\ngethostbyname() uses the C call gethostbanme(), which is deprecated.\n\nIf these are problem...
[ 11, 11, 7 ]
[]
[]
[ "dns", "ip", "python" ]
stackoverflow_0004815065_dns_ip_python.txt
Q: Depth First Traversal on BeautifulSoup Parse Tree Is there a way to do a DFT on a BeautifulSoup parse tree? I'm trying to do something like starting at the root, usually , get all the child elements and then for each child element get their children, etc until I hit a terminal node at which point I'll build my way...
Depth First Traversal on BeautifulSoup Parse Tree
Is there a way to do a DFT on a BeautifulSoup parse tree? I'm trying to do something like starting at the root, usually , get all the child elements and then for each child element get their children, etc until I hit a terminal node at which point I'll build my way back up the tree. Problem is I can't seem to find a me...
[ "mytag.find_all() already does that:\n\nIf you call mytag.find_all(), Beautiful Soup will examine all the descendants of mytag: its children, its children’s children, and so on\n\nfrom bs4 import BeautifulSoup # pip install beautifulsoup4\n\nsoup = BeautifulSoup(\"\"\"<!doctype html>\n<div id=a>A\n <div id=1>A1</...
[ 17, 6 ]
[]
[]
[ "beautifulsoup", "python", "tree_traversal" ]
stackoverflow_0004814317_beautifulsoup_python_tree_traversal.txt
Q: Provisioning mercurial server I'm in need of a software (not a service) that has a web API to both create as well as interact with mercurial repositories. In my mind's eye I imagine the API might look like: POST /repos name=foo Creates a repository at /repos/foo, which then works as per hgwebdir.cgi. Does suc...
Provisioning mercurial server
I'm in need of a software (not a service) that has a web API to both create as well as interact with mercurial repositories. In my mind's eye I imagine the API might look like: POST /repos name=foo Creates a repository at /repos/foo, which then works as per hgwebdir.cgi. Does such software exist? If not, any recom...
[ "I am not aware of such software, but it would be pretty trivial to create one yourself if you are familiar with web applications and python. \nimport os\nfrom mercurial import commands,ui\nos.mkdir(\"/repos/foo\")\ncommands.init(ui.ui(),\"/repos/foo\")\n\nshould do the trick. Of course you need to wrap it inside a...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "mercurial", "python" ]
stackoverflow_0001519785_mercurial_python.txt
Q: How use Gridfs of mongodb with PIL (Python Image Library) i use mongodb and save file to gridfs now i want edit images from gridfs ... i use this code def thumbnail(file_obj): import StringIO from PIL import Image im = StringIO.StringIO() im.write(file_obj.raw_file) im_ful = Image.open(im) ...
How use Gridfs of mongodb with PIL (Python Image Library)
i use mongodb and save file to gridfs now i want edit images from gridfs ... i use this code def thumbnail(file_obj): import StringIO from PIL import Image im = StringIO.StringIO() im.write(file_obj.raw_file) im_ful = Image.open(im) return im_ful.info but pil said "cannot identify image fil...
[ "You need an im.seek(0) before the Image.open(im) call. Otherwise PIL tries to read from the end of the file, gets no data, and fails.\n" ]
[ 6 ]
[]
[]
[ "gridfs", "mongodb", "python", "python_imaging_library" ]
stackoverflow_0004814525_gridfs_mongodb_python_python_imaging_library.txt
Q: How to access (and edit) variables from a callback function? I use Boto to access Amazon S3. And for file uploading I can assign a callback function. The problem is that I cannot access the needed variables from that callback function until I make them global. In another hand, if I make them global, they are globa...
How to access (and edit) variables from a callback function?
I use Boto to access Amazon S3. And for file uploading I can assign a callback function. The problem is that I cannot access the needed variables from that callback function until I make them global. In another hand, if I make them global, they are global for all other Celery tasks, too (until I restart Celery), as the...
[ "In Python 2.x closures are read-only. You can however use a closure over a mutable value... i.e.\ndef myfunc():\n stuff = [17] # <<---- this is a mutable object\n def lfun(arg):\n print \"got arg\", arg, \"and stuff[0] is\", stuff[0]\n stuff[0] += 1\n return lfun\n\nmy_function = myfunc()\nm...
[ 14, 3, 0 ]
[]
[]
[ "callback", "closures", "namespaces", "python", "variables" ]
stackoverflow_0004815329_callback_closures_namespaces_python_variables.txt
Q: Writing utf-8 string inside my python files This line in my .py file is giving me a: "UnicodeDecodeError: 'utf8' codec can't decode bytes in position 8-13: unsupported Unicode code range" if line.startswith(u"Fußnote"): The file is saved in utf-8 and has the encoding at the top: # -- coding: utf-8 -- I've got a l...
Writing utf-8 string inside my python files
This line in my .py file is giving me a: "UnicodeDecodeError: 'utf8' codec can't decode bytes in position 8-13: unsupported Unicode code range" if line.startswith(u"Fußnote"): The file is saved in utf-8 and has the encoding at the top: # -- coding: utf-8 -- I've got a lot of other py files with utf-8 encoded chinese t...
[ "Let's examine that error message very closely:\n\"UnicodeDecodeError: 'utf8' codec can't decode bytes in position 8-13: unsupported Unicode code range\"\nNote carefully that it says \"bytes in position 8-13\" -- that's a 6-byte UTF-8 sequence. That might have been valid in the dark ages, but since Unicode was froz...
[ 10, 6, 3, 2, 0 ]
[]
[]
[ "python", "unicode", "utf_8" ]
stackoverflow_0004812186_python_unicode_utf_8.txt
Q: Get part of XML document in Python I have XML files matching a DTD <!ELEMENT root (node, notinteresting> <!ELEMENT node (node*)> <!ELEMENT notinteresting (#PCDATA)> and I want to retrieve the topmost node (in XPath: /root/node) of such a file and everything below it, ignoring the notinteresting bit. How can I do ...
Get part of XML document in Python
I have XML files matching a DTD <!ELEMENT root (node, notinteresting> <!ELEMENT node (node*)> <!ELEMENT notinteresting (#PCDATA)> and I want to retrieve the topmost node (in XPath: /root/node) of such a file and everything below it, ignoring the notinteresting bit. How can I do this in a few lines of Python? Speed/mem...
[ "You can use elementtree API, depending on the version you will use the import might be slightly different. You need version >= python 2.7\nfrom xml.etree.ElementTree import ElementTree\ntree = ElementTree()\ntree.parse(\"yourdoc.xml\")\nroottree = tree.getroot() \n\nThen it gives you the possibility to do things l...
[ 3, 0 ]
[]
[]
[ "css_selectors", "python", "xml" ]
stackoverflow_0004815822_css_selectors_python_xml.txt
Q: tk: how to invoke it just to display something, and return to the main program? Sorry for the noob question but I really don't understand this. I'm using python / tkinter and I want to display something (say, a canvas with a few shapes on it), and keep it displayed until the program quits. I understand that no wid...
tk: how to invoke it just to display something, and return to the main program?
Sorry for the noob question but I really don't understand this. I'm using python / tkinter and I want to display something (say, a canvas with a few shapes on it), and keep it displayed until the program quits. I understand that no widgets would be displayed until I call tkinter.tk.mainloop(). However, if I call tkinte...
[ "Tk needs an event loop, there's no avoiding that. That's how the widgets know to redraw themselves when obscured, for instance. So, you must have the event loop running.\nYou have at least three choices. First, use the main thread for the GUI, and put your other logic in a separate thread. A second option is to us...
[ 3 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0004813952_python_tkinter_user_interface.txt
Q: Is Pyro signal safe? I have been using Pyro 3 for a little while now, with great success, but occasionally I have noticed, that when a signal such as SIGHUP or SIGINT arrives while Pyro is doing some remote communications, the process hangs, hence the question, is Pyro signal safe? Thanks in advance. A: Seems th...
Is Pyro signal safe?
I have been using Pyro 3 for a little while now, with great success, but occasionally I have noticed, that when a signal such as SIGHUP or SIGINT arrives while Pyro is doing some remote communications, the process hangs, hence the question, is Pyro signal safe? Thanks in advance.
[ "Seems the issue here is by default Python sets up a handlers for SIGINT and SIGTERM which raise exceptions. If you therfore receive a signal while doing some Pyro comms, the exception is raised, and off it goes to look for an appropriate except clause, not finishing what it was doing, if you then try and use Pyro ...
[ 2 ]
[]
[]
[ "pyro", "python", "signals" ]
stackoverflow_0004793234_pyro_python_signals.txt
Q: pyfacebook + Google App Engine: can't find new functions in facebook.py I'm trying to use the pyfacebook functions (https://github.com/sciyoshi/pyfacebook/) in a Google app engine project. I've followed the advice on the Facebook developer forum (http://forum.developers.facebook.net/viewtopic.php?pid=164613) and a...
pyfacebook + Google App Engine: can't find new functions in facebook.py
I'm trying to use the pyfacebook functions (https://github.com/sciyoshi/pyfacebook/) in a Google app engine project. I've followed the advice on the Facebook developer forum (http://forum.developers.facebook.net/viewtopic.php?pid=164613) and added the additional functions to the __init__.py file, copied that file to th...
[ "You believe the Facebook class has a certain method but Python is sure it hasn't. Why? Maybe you misspelled the method name, maybe you did not get the indentation right - hard to say without seeing the code.\nYou could try poking around to validate your assumptions:\nimport facebook\nimport logging\n\nlogging.warn...
[ 2 ]
[]
[]
[ "facebook", "google_app_engine", "pyfacebook", "python" ]
stackoverflow_0004806288_facebook_google_app_engine_pyfacebook_python.txt
Q: How to draw floating pie charts on an existing plot with matplotlib I would like to plot multiple pie charts over an existing plot using absolute coordinates. I went through the add_axes method and also the AxesGrid toolikt but couldn't find a solution. To be more specific, I want to draw pie charts over a geogra...
How to draw floating pie charts on an existing plot with matplotlib
I would like to plot multiple pie charts over an existing plot using absolute coordinates. I went through the add_axes method and also the AxesGrid toolikt but couldn't find a solution. To be more specific, I want to draw pie charts over a geographical map using the basemap module.
[ "This tutorial explains how to use matplotlib Basemap for drawing pie charts on a map. It is fairly simple and gives code examples.\n" ]
[ 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0004187119_matplotlib_python.txt
Q: test time-based scripts I'm writing a simple script which has a few lines like this: if (datetime.datetime.hour == 12): What is the easiest way to test these? Changing the system time to different times every time I want to test it is a bit annoying, is there an easier way to let Python think it's a different tim...
test time-based scripts
I'm writing a simple script which has a few lines like this: if (datetime.datetime.hour == 12): What is the easiest way to test these? Changing the system time to different times every time I want to test it is a bit annoying, is there an easier way to let Python think it's a different time?
[ "Create a datetime object now and use it:\nimport datetime, pytz\n\ntesting = False # set to True/False\n\nif testing:\n now = datetime.datetime(2011, 1, 1, 12, 23, 34, tzinfo=pytz.utc)\n # testing with any time\nelse:\n now = datetime.datetime.now(pytz.utc)\n # normal usage with current time\n\nif (now...
[ 2 ]
[]
[]
[ "datetime", "python", "unit_testing" ]
stackoverflow_0004816825_datetime_python_unit_testing.txt
Q: file.read() on appengine returns junk characters I'm using the following code: class Image(webapp.RequestHandler): def get(self, id): path = os.path.join(os.path.dirname(__file__), 'fcimages/%s.png' % id) self.response.headers['Content-Type'] = 'image/png' print file(path,'rb').read() ...
file.read() on appengine returns junk characters
I'm using the following code: class Image(webapp.RequestHandler): def get(self, id): path = os.path.join(os.path.dirname(__file__), 'fcimages/%s.png' % id) self.response.headers['Content-Type'] = 'image/png' print file(path,'rb').read() And it works fine locally (i.e. returns the image), bu...
[ "I managed to fix it eventually, I think the problem was the combination of self.response and print. Here's the code that works:\nclass Image(webapp.RequestHandler):\n def get(self, id):\n path = os.path.join(os.path.dirname(__file__), 'fcimages/%s.png' % id)\n self.response.headers['Content-Type']...
[ 5, 0 ]
[]
[]
[ "file_io", "google_app_engine", "python" ]
stackoverflow_0004816601_file_io_google_app_engine_python.txt
Q: Deploying django on a 1and1 dedicated server Hay, the company i work for uses a server just like this (https://order.1and1.co.uk/xml/order/ServerPremiumDualCoreXL;jsessionid=6007C323B398ACB7D9749B0386161CAE.TCpfix153b?__frame=top&_lf=Static&ordernow=true). To host our websites, the product claims it has python onb...
Deploying django on a 1and1 dedicated server
Hay, the company i work for uses a server just like this (https://order.1and1.co.uk/xml/order/ServerPremiumDualCoreXL;jsessionid=6007C323B398ACB7D9749B0386161CAE.TCpfix153b?__frame=top&_lf=Static&ordernow=true). To host our websites, the product claims it has python onboard, but how would i go about deploying a django ...
[ "you have to find out if one of the supported django mode is available: \n\nmod_wsgi, mod_fcgi, mod_python \n\nI have not used dedicated servers, but I think you might be able to configure it according to your needs. Ask the service provider. \n" ]
[ 1 ]
[]
[]
[ "deployment", "django", "linux", "python" ]
stackoverflow_0004816676_deployment_django_linux_python.txt
Q: static method as default parameter to a class method My question is about two answers to another question: Using class/static methods as default parameter values within methods of the same class. I am trying to understand if there's really a difference between what the two answers do, and if so, what's the pros a...
static method as default parameter to a class method
My question is about two answers to another question: Using class/static methods as default parameter values within methods of the same class. I am trying to understand if there's really a difference between what the two answers do, and if so, what's the pros and cons of each. Question: how to use a class method as a ...
[ "The answer really depends on what other intentions you have for X.default_func. If you intend for X.default_func to be called outside of an instance of X, then you want it to be a static method (Answer 2).\n# in other code...\nsome_object = \"Bring out your dead\"\nX.default_func(some_object)\n\nIf, on the other h...
[ 3 ]
[]
[]
[ "argument_passing", "python", "static_methods" ]
stackoverflow_0003971490_argument_passing_python_static_methods.txt
Q: How do I import a module whose name clashes with a module in my package? I have several python modules in a directory. In the same directory, I have a package tests. I would quite like to name the modules in tests the same as the modules that they contain tests for, although of course it isn't critical. So, in tes...
How do I import a module whose name clashes with a module in my package?
I have several python modules in a directory. In the same directory, I have a package tests. I would quite like to name the modules in tests the same as the modules that they contain tests for, although of course it isn't critical. So, in tests.foo I naively write import foo. This isn't working so well - it imports tes...
[ "test_foo.py seems like an appropriate solution in this case.\nIf you don't rename the test modules then make the tests directory into Python package (add tests/__init__.py file) and use absolute imports:\nfrom __future__ import absolute_import \nimport foo # import global foo.py, the first foo.py...
[ 8, 3 ]
[]
[]
[ "import", "python" ]
stackoverflow_0004816595_import_python.txt
Q: Django Custom image upload field with dynamic path I'm trying to create my own field type for uploading images, it won't be used in the django admin panel. I imagine the syntax would probably look something like: photo = CustomImageField(upload_to='images', width="200", height="200") I want to be able to set the ...
Django Custom image upload field with dynamic path
I'm trying to create my own field type for uploading images, it won't be used in the django admin panel. I imagine the syntax would probably look something like: photo = CustomImageField(upload_to='images', width="200", height="200") I want to be able to set the parameters in the field when I upload and save an image....
[ "You don't need a custom field for this. As the documentation shows, upload_to can be a callable, which is passed the instance and returns a path which determines where the field is saved.\nI'm not sure what you mean about the width and height parameters. These are calculated from the image in any case. If you spec...
[ 3, 2, 0 ]
[]
[]
[ "django", "django_forms", "file_upload", "filefield", "python" ]
stackoverflow_0004815150_django_django_forms_file_upload_filefield_python.txt
Q: Python and re.compile return inconsistent results I'm trying to replace all instances of href="../directory" with href="../directory/index.html". In Python, this reg = re.compile(r'<a href="../(.*?)">') for match in re.findall(reg, input_html): output_html = input_html.replace(match, match+'index.html') produ...
Python and re.compile return inconsistent results
I'm trying to replace all instances of href="../directory" with href="../directory/index.html". In Python, this reg = re.compile(r'<a href="../(.*?)">') for match in re.findall(reg, input_html): output_html = input_html.replace(match, match+'index.html') produces the following output: href="../personal-autonomy/in...
[ "Don't parse html with regexs:\nimport re \nfrom lxml import html\n\ndef replace_link(link):\n if re.match(r\"\\.\\./[^/]+/$\", link):\n link += \"index.html\"\n return link\n\nprint html.rewrite_links(your_html_text, replace_link)\n\nOutput\n<p> \n\n <a href=\"../personal-autonomy/index.html\">auto...
[ 5, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004816377_python_regex.txt
Q: UnicodeEncodeError when trying to convert Django models to XML I found a python program: Export Django database to xml file that converts django models to a xml representation. I get these errors when trying to run the program. My models contain some text written in French. Traceback (most recent call last): Fil...
UnicodeEncodeError when trying to convert Django models to XML
I found a python program: Export Django database to xml file that converts django models to a xml representation. I get these errors when trying to run the program. My models contain some text written in French. Traceback (most recent call last): File "xml_export.py", line 71, in <module> writer.content(value) File...
[ "It looks like your variable text contains a non-ASCII string. \nSee:\n>>> mystring = u\"élève\"\n>>> mystring\nu'\\xe9l\\xe8ve'\n>>> str(mystring)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nUnicodeEncodeError: 'ascii' codec can't encode character u'\\xe9' in position 0: ordinal n...
[ 7, 3, 0 ]
[]
[]
[ "django", "django_models", "encoding", "python", "xml" ]
stackoverflow_0004817018_django_django_models_encoding_python_xml.txt
Q: Import statement after function definition -- How can I make it more pythonic? I wrote the following piece of code and I think it's lame: def findfile1(wildcard): """Returns path of the first matched file. Using win32file. >>> findfile1("D:\\Python26\\*.exe") 'D:\\Python26\\python.exe' """ retu...
Import statement after function definition -- How can I make it more pythonic?
I wrote the following piece of code and I think it's lame: def findfile1(wildcard): """Returns path of the first matched file. Using win32file. >>> findfile1("D:\\Python26\\*.exe") 'D:\\Python26\\python.exe' """ return filepath def findfile2(wildcard): "Same as above, but using glob." retur...
[ "How about putting the functions in two different modules?\nmodule1:\nimport win32file\n\ndef findfile(wildcard):\n \"\"\"Returns path of the first matched file. Using win32file.\n >>> findfile1(\"D:\\\\Python26\\\\*.exe\")\n 'D:\\\\Python26\\\\python.exe'\n \"\"\"\n return filepath\n\nmodule2:\nimpo...
[ 4, 4, 1, 0 ]
[]
[]
[ "import", "python", "refactoring" ]
stackoverflow_0004802646_import_python_refactoring.txt
Q: How to create a setup.py that consumes a tar file Our systems people bundle source up in git and do not support pip. The git repository contains a compressed tar file. And the tar file has a setup.py within it. I figure the easiest way to expose this in my project is to add a -e git... line to my pip requirements....
How to create a setup.py that consumes a tar file
Our systems people bundle source up in git and do not support pip. The git repository contains a compressed tar file. And the tar file has a setup.py within it. I figure the easiest way to expose this in my project is to add a -e git... line to my pip requirements.txt and add a setup.py in the root of the git repositor...
[ "I went with writing a pseudo setup.py file in the root of the git package:\nimport os\nimport subprocess\n\nif __name__ == '__main__':\n package_name = 'package'\n short_package_name = 'package-1.0.6'\n\n print \"Changing to SOURCES\"\n os.chdir('SOURCES')\n\n tar_file = '.'.join([short_package_name...
[ 2 ]
[]
[]
[ "python", "setup.py" ]
stackoverflow_0004817200_python_setup.py.txt
Q: Delete an object by id in python? If I get the id of an object, how can I delete an object by it's id ? A: This is not a good idea. Try using the weakref module, which allows you to create weak references (analogous to symbolic links) to objects. A: AFAIK objects are deleted by garbage collector in python. Yo...
Delete an object by id in python?
If I get the id of an object, how can I delete an object by it's id ?
[ "This is not a good idea. Try using the weakref module, which allows you to create weak references (analogous to symbolic links) to objects.\n", "AFAIK objects are deleted by garbage collector in python. You can't force a delete yourself.\n", "The id refers to a memory address. You \"can't\" delete (or free) a...
[ 2, 1, 0 ]
[ "You can delete objects by calling del() on them.\nBut AFAIK id won't help in that.\n" ]
[ -2 ]
[ "object", "python" ]
stackoverflow_0004817726_object_python.txt
Q: Filling complements of areas with matplotlib I'm currently implementing something with Python and matplotlib. I know how to draw polygons and also how to fill them, but how do I fill everything except the interior of a polygon? To be clearer, I'd like to modify the result below, obtained using axhspan's and axvspa...
Filling complements of areas with matplotlib
I'm currently implementing something with Python and matplotlib. I know how to draw polygons and also how to fill them, but how do I fill everything except the interior of a polygon? To be clearer, I'd like to modify the result below, obtained using axhspan's and axvspan's, by clipping the horizontal and vertical red l...
[ "This post asks (and answers) essentially this question. Look at 'Edit 2' in the accepted answer. It describes how to create a vector polygon the size of your plot bounds and then how to create a hole in it to match the shape you want to complement. It does this by assigning line codes that define whether or not ...
[ 5, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0004814318_matplotlib_python.txt
Q: Problem with decorator def my_decorator(func) : print "I am a ordinary function" def wrapper() : print "I am function returned by the decorator" func() return wrapper def lazy_function() : print "zzzzzzzz" functionDecorator=my_decorator(lazy_function) I have in Debug IO I am a ord...
Problem with decorator
def my_decorator(func) : print "I am a ordinary function" def wrapper() : print "I am function returned by the decorator" func() return wrapper def lazy_function() : print "zzzzzzzz" functionDecorator=my_decorator(lazy_function) I have in Debug IO I am a ordinary function I don't get ...
[ "When you first call my_decorator, before it returns the the function wrapper, it will print your message.\nTry calling functionDecorator() again, you won't get the output a second time because the function has already been decorated by my_decorator. Each time you call my_decorator, however, it will print your mess...
[ 5, 4 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0004817973_decorator_python.txt
Q: Creating a very simple IRC bot with SSL? How do I implement SSL with this? I've been trying to use an SSL socket but I haven't been able to get it to work yet. Any ideas? Thanks, Dennis Edit: Got it! # Import some necessary libraries. import socket, ssl # Some basic variables used to configure the bot ser...
Creating a very simple IRC bot with SSL?
How do I implement SSL with this? I've been trying to use an SSL socket but I haven't been able to get it to work yet. Any ideas? Thanks, Dennis Edit: Got it! # Import some necessary libraries. import socket, ssl # Some basic variables used to configure the bot server = "irc.freenode.net" # Server port = 7000 ...
[ "With the danger of missing the question entirely, have you tried this?\n", "It hasn't been updated in a while, but irclib supports ssl sockets. You can take a look at how it does it.\n" ]
[ 1, 1 ]
[]
[]
[ "openssl", "python", "sockets", "ssl" ]
stackoverflow_0004817963_openssl_python_sockets_ssl.txt
Q: why does cx_oracle execute() not like my string now? I've downloaded cx_oracle some time ago and wrote a script to convert data to XML. I've had to reisntall my OS and grabbed the latest version of cx_Oracle (5.0.3) and all of the sudden my code is broken. The first thing was that cx_Oracle.connect wanted unicode ...
why does cx_oracle execute() not like my string now?
I've downloaded cx_oracle some time ago and wrote a script to convert data to XML. I've had to reisntall my OS and grabbed the latest version of cx_Oracle (5.0.3) and all of the sudden my code is broken. The first thing was that cx_Oracle.connect wanted unicode rather string for the username and password, that was very...
[ "I see they support python 3 now. It could be that they want a unicode object instead of str, and they're using python 3 terminology in that error message, even though they presumably didn't in the error messages relating to user/pass.\n", "Maybe changing your encoding settings will help.\nI HAVE this in my case ...
[ 4, 1 ]
[]
[]
[ "cx_oracle", "database", "python" ]
stackoverflow_0002903497_cx_oracle_database_python.txt
Q: SSL wrap socket: AttributeError: 'module' object has no attribute 'wrap_socket' I'm creating a very simple example on OSX with python 2.6 but I keep getting: Traceback (most recent call last): File "ssl.py", line 1, in <module> import socket, ssl File "/Users/Dennis/ssl.py", line 5, in <module> sslSock...
SSL wrap socket: AttributeError: 'module' object has no attribute 'wrap_socket'
I'm creating a very simple example on OSX with python 2.6 but I keep getting: Traceback (most recent call last): File "ssl.py", line 1, in <module> import socket, ssl File "/Users/Dennis/ssl.py", line 5, in <module> sslSocket = ssl.wrap_socket(s) AttributeError: 'module' object has no attribute 'wrap_socket...
[ "Don't name your script ssl.py, because when you name your script ssl.py and you do import ssl you're importing this same script .\n", "Your script is : ssl.py\nWhen you do an import ssl, it calls itself and that is why you get the AttributeError\nGive another name to your script and it should work.\n" ]
[ 18, 5 ]
[]
[]
[ "python", "ssl" ]
stackoverflow_0004818280_python_ssl.txt
Q: can not import the module deepcopy i've ran into this wierd error since few days where most of the applications/frameworks/modules will refuse to run , because of of the unavailability of the module deepcopy i can't understand why is that so ? Traceback (most recent call last): File "<stdin>", line 1, in <m...
can not import the module deepcopy
i've ran into this wierd error since few days where most of the applications/frameworks/modules will refuse to run , because of of the unavailability of the module deepcopy i can't understand why is that so ? Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/pymodules/python...
[ "seems like i had another copy.py file in my path that was confusing python .removed it and it worked like a charm .\n", "If think you want to use:\nfrom copy import deepcopy\n\nI can't import it either. I think it has been removed from Django.\n" ]
[ 15, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004818325_python.txt
Q: Is there a way to have (animated)GIF image as system tray icon with pyqt? I have created static(PNG) image as tray icon with pyqt. Did the same with GIF image results in static tray icon. Can it animated in system tray with pyqt? QtGui.QSystemTrayIcon.__init__(self, parent) self.setIcon(QtGui.QIcon("Image.gif")) ...
Is there a way to have (animated)GIF image as system tray icon with pyqt?
I have created static(PNG) image as tray icon with pyqt. Did the same with GIF image results in static tray icon. Can it animated in system tray with pyqt? QtGui.QSystemTrayIcon.__init__(self, parent) self.setIcon(QtGui.QIcon("Image.gif"))
[ "Use QMovie to play the animated gif, and update the tray icon on each new frame event:\nm_icon = new QSystemTrayIcon();\nm_icon->show();\nm_gif = new QMovie(\":/animated.gif\");\nconnect(m_gif, SIGNAL(frameChanged(int)), this, SLOT(updateIcon()));\nm_gif->start();\n\n...\nvoid MyWidget::updateIcon()\n{\n m_icon...
[ 3 ]
[]
[]
[ "pyqt", "python", "qt", "system_tray" ]
stackoverflow_0004816445_pyqt_python_qt_system_tray.txt
Q: Is Python-OpenID going through Janrain? I'm looking to implement OpenID in my python based project, and a good implementation is Python-OpenID, maintained by Janrain. But Janrain is free only when there is less than 2.500 unique sign-in/registration. I was wondering if this limitation is linked to Python-OpenID. W...
Is Python-OpenID going through Janrain?
I'm looking to implement OpenID in my python based project, and a good implementation is Python-OpenID, maintained by Janrain. But Janrain is free only when there is less than 2.500 unique sign-in/registration. I was wondering if this limitation is linked to Python-OpenID. What happens if you reach this 2.500 quota ? N...
[ "As far as I know, it's an OpenID library, so it doesn't have anything to do with Janrain Engage. And it doesn't stop working because you have too many users.\n" ]
[ 0 ]
[]
[]
[ "janrain", "openid", "python" ]
stackoverflow_0004816560_janrain_openid_python.txt
Q: Multiple Tries in Try/Except Block I have some python code where I can accept two different file names, so I would like to do something like try the first file name, if there is an exception then try the second filename, if the second try fails, then raise the exception and handle the error. So the basic logic is:...
Multiple Tries in Try/Except Block
I have some python code where I can accept two different file names, so I would like to do something like try the first file name, if there is an exception then try the second filename, if the second try fails, then raise the exception and handle the error. So the basic logic is: first try this: f = file(name1) if n...
[ "You could simply use a for loop:\nfor name in filenames:\n try:\n f = open(name)\n break\n except IOError:\n pass\nelse:\n # error\n\n", "You can do a loop of try ... except like:\nfor f_name in names:\n try:\n f = open(f_name, 'r')\n # do something\n break #...
[ 19, 4 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0004819402_exception_python.txt
Q: Django-Piston returning JSON/Dictionary as text/plain whenever I change the response type I'm debugging some code written by another programmer that uses django-piston to provide an API that returns Python dictionary objects to the caller via JSON. I'm following the documentation on piston here. I noticed some str...
Django-Piston returning JSON/Dictionary as text/plain whenever I change the response type
I'm debugging some code written by another programmer that uses django-piston to provide an API that returns Python dictionary objects to the caller via JSON. I'm following the documentation on piston here. I noticed some strange behavior where if I manually set response = rc.CREATED and response.content = my_dict, the...
[ "I ran into a very similar problem. After digging through Piston and Django source I decided to try this and it worked:\nresp = rc.CREATED\nresp.content = dict(\n attendee_id=attendee.id,\n order_id=order.id,\n)\nreturn resp\n\nThat yields this in HTTP (some headers removed for brevity).\n< HTTP/1.1 201 CREAT...
[ 2 ]
[]
[]
[ "dictionary", "django", "django_piston", "json", "python" ]
stackoverflow_0004572995_dictionary_django_django_piston_json_python.txt
Q: Will learning Django translates well into other applications? Does anyone have experience using Python in different variaty of applications? A little background - I am a 3D artist in an animation studio. I do programming in PHP and use Zend framework for my personal project. Python has always been a language I wa...
Will learning Django translates well into other applications?
Does anyone have experience using Python in different variaty of applications? A little background - I am a 3D artist in an animation studio. I do programming in PHP and use Zend framework for my personal project. Python has always been a language I wanted to learn because it can be used within many applications our s...
[ "\nSo if I learn Python with web application and Django in mind, will that limit my Python skill from applying it to other applications?\n\nNo\n\nauthenticate against Windows active directory\n\nYes. You may need to customize an Authentication Backend.\n\nquick database update via AJAX interaction (drag and drop t...
[ 0, 0, 0 ]
[]
[]
[ "django", "python", "zend_framework" ]
stackoverflow_0004816766_django_python_zend_framework.txt
Q: Finding the amount of time difference between dates in python Suppose I had 2 lists that looked something like this: L1=['Smith, John, 2008, 12, 10, Male', 'Bates, John, 2006, 1, Male', 'Johnson, John, 2009, 1, 28, Male', 'James, John, 2008, 3, Male'] L2=['Smith, Joy, 2008, 12, 10, Female', 'Smi...
Finding the amount of time difference between dates in python
Suppose I had 2 lists that looked something like this: L1=['Smith, John, 2008, 12, 10, Male', 'Bates, John, 2006, 1, Male', 'Johnson, John, 2009, 1, 28, Male', 'James, John, 2008, 3, Male'] L2=['Smith, Joy, 2008, 12, 10, Female', 'Smith, Kevin, 2008, 12, 10, Male', 'Smith, Matt, 2008, 12, 10...
[ "As Joe Kington suggested, the dateutil module is useful for this.\nIn particular, it can tell you the difference between two dates in terms of years, months and days. (Doing the calculation yourself would involve taking account of leap years, etc. Much better to use a well-tested module than to reinvent this wheel...
[ 6, 2, 0 ]
[]
[]
[ "list", "python", "time" ]
stackoverflow_0004818392_list_python_time.txt
Q: wxpython: close the frame but no the script I have a script, this call to a wx.app when I close the wx.app this close the script, why ? class Frame(wx.Frame): def _init_ctrls(self, prnt): ... class BoaApp(wx.App): def OnInit(self): self.main = Frame.create(None) self.main.Show() ...
wxpython: close the frame but no the script
I have a script, this call to a wx.app when I close the wx.app this close the script, why ? class Frame(wx.Frame): def _init_ctrls(self, prnt): ... class BoaApp(wx.App): def OnInit(self): self.main = Frame.create(None) self.main.Show() self.SetTopWindow(self.main) return Tru...
[ "When you call app.MainLoop() the script goes into a loop which runs the app. When you close the app the loop exits and any code after the call of app.MainLoop() then executes. If there isn't anything left to do, the script will end.\n" ]
[ 3 ]
[]
[]
[ "frame", "python", "wxpython" ]
stackoverflow_0004819715_frame_python_wxpython.txt
Q: Why does SLOT('insertColumn()') fail in PyQt binding? I'm diving into PyQt, and I've come across a little annoyance. SLOT('insertColumn()') does nothing when attached to a button in the GUI. SLOT('clear()') works perfectly, and insertColumn() works outside of the binding. insertColumn() is listed as a public sl...
Why does SLOT('insertColumn()') fail in PyQt binding?
I'm diving into PyQt, and I've come across a little annoyance. SLOT('insertColumn()') does nothing when attached to a button in the GUI. SLOT('clear()') works perfectly, and insertColumn() works outside of the binding. insertColumn() is listed as a public slot in the Qt documentation, so I'm stuck. Here's the code: ...
[ "The call to .connect() only sets up the relationship for the signal and the slot. You can't actually pass values to the slot in the .connect() call. You can create your own slot and put that in the call to .connect() and then in your own slot implementation call self.tableWidget.insertColumn(2).\nEdit:\n Just to ...
[ 2, 2 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0004819706_pyqt_pyqt4_python_qt_qt4.txt
Q: Convert Word doc to PDF - Python I need to fill in a document and then try and convert it into a PDF. Any idea how I can do this? A: You can use OpenOffice if it is available on the system. import subprocess import shutil input_filename = 'input.doc' output_filename = 'output.pdf' p = subprocess.Popen(['unocon...
Convert Word doc to PDF - Python
I need to fill in a document and then try and convert it into a PDF. Any idea how I can do this?
[ "You can use OpenOffice if it is available on the system.\nimport subprocess\nimport shutil\n\ninput_filename = 'input.doc'\noutput_filename = 'output.pdf'\n\np = subprocess.Popen(['unoconv', '--stdout', input_filename], stdout=subprocess.PIPE)\nwith open(output_filename, 'w') as output:\n shutil.copyfileobj(p.st...
[ 13, 2, 0 ]
[]
[]
[ "ms_word", "pdf", "python" ]
stackoverflow_0004818342_ms_word_pdf_python.txt
Q: GAE, How do I run a function of a model at the time the new model instance is created? How do I perform setup() automatically when a new model instance has been created? class MyModel(bd.Model): setup(self): ... model = MyModel() A: You can override the __init__() method to do this in addition t...
GAE, How do I run a function of a model at the time the new model instance is created?
How do I perform setup() automatically when a new model instance has been created? class MyModel(bd.Model): setup(self): ... model = MyModel()
[ "You can override the __init__() method to do this in addition to its usual work:\nclass MyModel(db.Model): \n def __init__(self, *args, **kwargs): \n super(MyModel, self).__init__(*args, **kwargs) # run the default code\n self.setup() # run custom setup code\n def setup(self):\n print ...
[ 3 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004820124_google_app_engine_google_cloud_datastore_python.txt
Q: basics of python encryption w/ hashlib sha1 I'm struggling to fully understand how encryption works and is coded, particularly with python. I'm just trying to get the basics down and create code in the simplest form. I'm going to be passing a userID between two different sites, but obviously I need this to be encr...
basics of python encryption w/ hashlib sha1
I'm struggling to fully understand how encryption works and is coded, particularly with python. I'm just trying to get the basics down and create code in the simplest form. I'm going to be passing a userID between two different sites, but obviously I need this to be encrypted with a private key so Website2 knows it cam...
[ "The hashlib module provides hashing functions. While there is some relation to encryption, once you hash some data you can not go back to get the original data from the hash result.\nInstead of encripting the data you can take a different approach: creating a unique signature using a hash of the data and some secr...
[ 21, 17, 3 ]
[]
[]
[ "cryptography", "hashlib", "hmac", "python", "sha1" ]
stackoverflow_0004820043_cryptography_hashlib_hmac_python_sha1.txt
Q: distinguishable socket input Im trying to send multiple data items over a tcp socket from an android client to a python server. The user on the client side can make multiple choices so im using a number sent as a character to differentiate between request types. I have to send the choice and specific data dependin...
distinguishable socket input
Im trying to send multiple data items over a tcp socket from an android client to a python server. The user on the client side can make multiple choices so im using a number sent as a character to differentiate between request types. I have to send the choice and specific data depending on the choice.For the current se...
[ "TCP will combine your writes into one packet if they are written before the packet is sent, meaning the information will be received concatenated.\nA common solution would be to incorporate an 'opcode' before your data.\nFor example, prefix CHOICE before sending your integer. When you read CHOICE in your python sc...
[ 2 ]
[]
[]
[ "android", "java", "python", "sockets" ]
stackoverflow_0004820021_android_java_python_sockets.txt
Q: A "safe" python HTML text formatting (ala textile) I've been looking around for an existing python library in the style of textile to format text for users to enter. If it was just me entering it, just textile would have been fine, but since the input is meant for a django app that will take user input and display...
A "safe" python HTML text formatting (ala textile)
I've been looking around for an existing python library in the style of textile to format text for users to enter. If it was just me entering it, just textile would have been fine, but since the input is meant for a django app that will take user input and display it, while still maintaining some formatting. I managed ...
[ "If you're using Django, you could try safe markdown:\n{% load markup %}\n\n{{ foo|markdown:\"safe\" }}\n\nYou'll need to have markdown installed, and django.contrib.markup in your settings.py apps.\nIf you want to sanitize HTML on save, I've had good luck using feedparser's sanitize (http://www.feedparser.org/). \...
[ 6, 2, 1 ]
[]
[]
[ "django", "formatting", "python", "textile" ]
stackoverflow_0001703678_django_formatting_python_textile.txt
Q: Good source code for compiler components I am currently taking a course on Compilers. I don't like the idea of blindly memorising facts without any sort of place to apply them to. I want to learn by hands-on doing. So, I would like to have the complete code of 3-4 compilers, possibly for languages with different ...
Good source code for compiler components
I am currently taking a course on Compilers. I don't like the idea of blindly memorising facts without any sort of place to apply them to. I want to learn by hands-on doing. So, I would like to have the complete code of 3-4 compilers, possibly for languages with different syntax rules (python,c, c++, java) while worki...
[ "You can grab code for the Lua compiler from lua.org, they distribute full source, and you could also get GCC's source code, which is both C and C++ compiling.\n", "There is a bunch of simple and comprehendable compilers:\n\nhttp://spivey.oriel.ox.ac.uk/corner/Oxford_Oberon-2_compiler\nhttp://caml.inria.fr/caml-l...
[ 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "c++", "compiler_construction", "java", "parsing", "python" ]
stackoverflow_0004818779_c++_compiler_construction_java_parsing_python.txt
Q: windows cookies index.dat parser Could someone explain how Internet Exploer cookies stored and how it retrived using the index.dat ,also could someone provide how this binray file is built and if there are a paserer/module/library for it written on perl /python ? A: Have a look at HTTP::Cookies::Microsoft, part ...
windows cookies index.dat parser
Could someone explain how Internet Exploer cookies stored and how it retrived using the index.dat ,also could someone provide how this binray file is built and if there are a paserer/module/library for it written on perl /python ?
[ "Have a look at HTTP::Cookies::Microsoft, part of libwww-perl.\n", "Here is a series of blog posts I wrote about index.dat:\n\nIndex.dat: Part I - What is index.dat?\nIndex.dat: Part II - What are they used for?\n\nBasically you'll need to be able to call the wininet UrlCacheEntry APIs from Perl. I think there i...
[ 3, 2 ]
[]
[]
[ "cookies", "internet_explorer", "internet_explorer_8", "perl", "python" ]
stackoverflow_0004819176_cookies_internet_explorer_internet_explorer_8_perl_python.txt
Q: Is there a Python module for handling Python object addresses? (When I say "object address", I mean the string that you type in Python to access an object. For example 'life.State.step'. Most of the time, all the objects before the last dot will be packages/modules, but in some cases they can be classes or other o...
Is there a Python module for handling Python object addresses?
(When I say "object address", I mean the string that you type in Python to access an object. For example 'life.State.step'. Most of the time, all the objects before the last dot will be packages/modules, but in some cases they can be classes or other objects.) In my Python project I often have the need to play around w...
[ "Short answer: No. What you want is impossible.\nThe long answer is that what you think of as the \"address\" of an object is anything but. life.State.step is merely one of the ways to get a reference to the object at that particular time. The same \"address\" at a later point can give you a different object, or it...
[ 5, 4, 1, 0 ]
[]
[]
[ "namespaces", "object", "object_address", "python" ]
stackoverflow_0003684151_namespaces_object_object_address_python.txt
Q: Mapping obj.method({argument:value}) to obj.argument(value) I don't know if this will make sense, but... I'm trying to dynamically assign methods to an object. #translate this object.key(value) #into this object.method({key:value}) To be more specific in my example, I have an object (which I didn't write), lets c...
Mapping obj.method({argument:value}) to obj.argument(value)
I don't know if this will make sense, but... I'm trying to dynamically assign methods to an object. #translate this object.key(value) #into this object.method({key:value}) To be more specific in my example, I have an object (which I didn't write), lets call it motor, which has some generic methods set, status and a fe...
[ "What about creating your own __getattr__ for the class that returns a function created on the fly? IIRC, there's some tricky cases to watch out for between __getattr__ and __getattribute__ that I don't recall off the top of my head, I'm sure someone will post a comment to remind me:\ndef __getattr__(self, name):\n...
[ 4, 1, 1, 1 ]
[]
[]
[ "lambda", "metaprogramming", "python" ]
stackoverflow_0004820341_lambda_metaprogramming_python.txt
Q: Is there a one-liner to list a directory two levels deep where the second level is an only-child, but not known? Suppose you have a directory structure like this: A/ B/ a.1 b.2 c.3 I'm wondering if there's a way, knowing that B has no siblings AND NOT KNOWING B's NAME, to do an os.listdir ope...
Is there a one-liner to list a directory two levels deep where the second level is an only-child, but not known?
Suppose you have a directory structure like this: A/ B/ a.1 b.2 c.3 I'm wondering if there's a way, knowing that B has no siblings AND NOT KNOWING B's NAME, to do an os.listdir operation in one swoop (that is, without calling os.listdir twice), instead of in three commands like so: root = "A" seco...
[ "import glob\nos.listdir(glob.glob('A/*')[0])\n\nor maybe even\nglob.glob('A/*/*')\n\n", "You are looking for os.walk. \n" ]
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004821331_python.txt
Q: Multithreading Python FS Crawler I've written a python function that scours a filesystem using a provided directory pattern, with optional 'actions' to take provided at each level. I then tried multi-threading it since some of the volumes are on network shares and I want to minimize IO blocking. I started by usi...
Multithreading Python FS Crawler
I've written a python function that scours a filesystem using a provided directory pattern, with optional 'actions' to take provided at each level. I then tried multi-threading it since some of the volumes are on network shares and I want to minimize IO blocking. I started by using the multiprocessing Pool class, sin...
[ "Not a complete solution, but I found a way to make the code work in either guise: from the interpreter or as code in a running script. I think the problem has to do with the following note in the multiprocessing docs:\nFunctionality within this package requires that the main method be importable by the children. ...
[ 1, 0 ]
[]
[]
[ "multiprocessing", "multithreading", "pool", "python" ]
stackoverflow_0004798912_multiprocessing_multithreading_pool_python.txt
Q: Is it possible to format a date with sqlite3? At start you have a string 'DDMMYYYY HHMMSS' and I want at the end to insert the string in a date field in sqlite3 database. The program is made in python. How can I do that ? A: Even though the ".schema" indicates that the field is a date or timestamp field... the ...
Is it possible to format a date with sqlite3?
At start you have a string 'DDMMYYYY HHMMSS' and I want at the end to insert the string in a date field in sqlite3 database. The program is made in python. How can I do that ?
[ "Even though the \".schema\" indicates that the field is a date or timestamp field... the field is actually a string. You can format the string anyway you want. If memory serves... their is no validation at all.\n", "I believe sqlite3 doesn't have a DATE type, therefore you have to do it manually in your python ...
[ 1, 1, 1 ]
[]
[]
[ "date", "python", "sqlite" ]
stackoverflow_0000889974_date_python_sqlite.txt
Q: Django - how to tell if a template fragment is already cached? I am using Django's Template Fragment Caching so in a template.html file {% extends 'base.html' %} {% load cache %} {% block content %} {% cache 500 "myCacheKey" %} My html here... {% endcache %} {% endblock %} This is working fine - I can se...
Django - how to tell if a template fragment is already cached?
I am using Django's Template Fragment Caching so in a template.html file {% extends 'base.html' %} {% load cache %} {% block content %} {% cache 500 "myCacheKey" %} My html here... {% endcache %} {% endblock %} This is working fine - I can see it's getting cached and hit but the view is doing something expens...
[ "If you do not use that data in your view, something as simple as this might work:\ndef index(request)\n get_data = api.getSomeExpensiveData\n return render_to_response('template.html', {'get_data':get_data} )\n\nIn template\n{% block content %}\n {% cache 500 \"myCacheKey\" %}\n {{ get_data.something }}\n...
[ 5, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0004821297_django_google_app_engine_python.txt
Q: Segfault running OpenCV under Apache / WSGI with python bindings I've got a django app that uses OpenCV for image processing and I'm running into problems deploying it in production. I can run the app just fine directly from python or using manage.py runserver. But when I try to run it inside apache / wsgi, as s...
Segfault running OpenCV under Apache / WSGI with python bindings
I've got a django app that uses OpenCV for image processing and I'm running into problems deploying it in production. I can run the app just fine directly from python or using manage.py runserver. But when I try to run it inside apache / wsgi, as soon as it gets to the line import cv it blows up with [Thu Jan 27 01:...
[ "You could start with:\nhttp://code.google.com/p/modwsgi/wiki/FrequentlyAskedQuestions#Apache_Process_Crashes\nThen go through:\nhttp://code.google.com/p/modwsgi/wiki/ApplicationIssues\nwhere it further elaborates on what can cause the crashes.\nFinally, you could investigate the point of the actual crash using:\nh...
[ 2 ]
[]
[]
[ "opencv", "python", "wsgi" ]
stackoverflow_0004819966_opencv_python_wsgi.txt
Q: How do I access the 1st element of each list in a lists of lists Example: numbers = ['1','2','3'] letters = ['a','b','c'] I want to get [1,a] as a results. Yeah I can loop through it, but I'm wondering if there is a fast one line way of doing this. EDIT EDIT !!!! I made a horrible mistake in describing the proble...
How do I access the 1st element of each list in a lists of lists
Example: numbers = ['1','2','3'] letters = ['a','b','c'] I want to get [1,a] as a results. Yeah I can loop through it, but I'm wondering if there is a fast one line way of doing this. EDIT EDIT !!!! I made a horrible mistake in describing the problem. I have access to the combined list (the list of lists of the questi...
[ "Try a list comprehension:\n# (numbers, letters) can be replaced with `list_of_lists` \n>>> [ x[0] for x in (numbers, letters) ] \n['1', 'a']\n\n", "import operator\nmap(operator.itemgetter(0), [numbers, letters])\n\n", "list_of_lists = [['1', '2', '3'], ['a', 'b', 'c']]\nlist_of_firsts = [l[0] for l in list_of...
[ 7, 2, 0 ]
[ "You may be looking for zip\n", "I would try:\nzip(*list_of_lists)[0]\n\n" ]
[ -1, -1 ]
[ "python" ]
stackoverflow_0004821363_python.txt
Q: How to make simplejson serializable class I have a class defined like this class A: def __init__(self): self.item1 = None def __repr__(self): return str(self.__dict__) when I do: >>> import simplejson >>> myA = A() >>> simplejson.dumps(myA) TypeError: {'item1': None} is not JSON serializab...
How to make simplejson serializable class
I have a class defined like this class A: def __init__(self): self.item1 = None def __repr__(self): return str(self.__dict__) when I do: >>> import simplejson >>> myA = A() >>> simplejson.dumps(myA) TypeError: {'item1': None} is not JSON serializable I can't find the reason why. Do I need to ...
[ "You can't serialize arbitrary objects with simplejson. You need to pass a default and object_hook to dump and load. Here's an example:\nclass SerializerRegistry(object):\n def __init__(self):\n self._classes = {}\n def add(self, cls):\n self._classes[cls.__module__, cls.__name__] = cls\n ...
[ 10, 3 ]
[]
[]
[ "python", "serialization", "simplejson" ]
stackoverflow_0004821940_python_serialization_simplejson.txt
Q: Reading least significant bits in Python I am having to parse the Facility and Severity of syslog messages in Python. These values come with each message as a single integer. The severity of the event is 0-7, specified in the 3 least significant bits in the integer. What is the easiest/fastest way to evaluate t...
Reading least significant bits in Python
I am having to parse the Facility and Severity of syslog messages in Python. These values come with each message as a single integer. The severity of the event is 0-7, specified in the 3 least significant bits in the integer. What is the easiest/fastest way to evaluate these 3 bits from the number? The code I have r...
[ "SEV = PRI & 7\nFAC = PRI >> 3\n\nLike that.\n", "Just apply a bit mask:\nsev = int(pri) & 0x07\n\n(0x07 is 00000111)\n", "Try the following\nresult = FAC & 0x7\n\n", "The normal way to extract the least significant bits would be to do a bitwise AND with the appropriate mask (7 in this case)\n" ]
[ 9, 4, 1, 0 ]
[]
[]
[ "bit_manipulation", "python", "syslog" ]
stackoverflow_0004822130_bit_manipulation_python_syslog.txt
Q: Python 2.7 using if elif to go through a text file Goal is to write a script which will copy a text file and exclude any line beginning with #. My question is I seem to get an index error which is dependent upon the order of my if elif conditions. The only difference between the nonworking code and the working co...
Python 2.7 using if elif to go through a text file
Goal is to write a script which will copy a text file and exclude any line beginning with #. My question is I seem to get an index error which is dependent upon the order of my if elif conditions. The only difference between the nonworking code and the working code (besides the suffix "_bad" to the nonworking function...
[ "If you do if textObj[0] == \"#\": and textObj=\"\" then there is no character at the zero index, because the string is empty, hence the index error. \nThe alternative is to do \n if textObj.startswith(\"#\"): which will work in both cases.\n", "some tips (and please please read PEP8):\n\nuse a 'for' instead of a...
[ 5, 5, 0, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0004821795_if_statement_python.txt
Q: Python NaN squared error This is purely out of curiosity, but why does this occur? >>> a = float('Nan') >>> a**2.0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: (33, 'Domain error') I would have expected it to simply return NaN instead of generating an error. A: It looks l...
Python NaN squared error
This is purely out of curiosity, but why does this occur? >>> a = float('Nan') >>> a**2.0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: (33, 'Domain error') I would have expected it to simply return NaN instead of generating an error.
[ "It looks like a bug in whatever implementation of Python you are using. It works as expected for me in all Python versions I tested, ranging from 2.5 to 3.1.\n>>> nan = float('NaN')\n>>> nan ** 2.0\nnan\n\n\nPython 2.6.4 on ideone\nPython 3.1.2 on ideone\n\n", "From http://www.mail-archive.com/relax-devel@gna.or...
[ 4, 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004821941_python.txt
Q: Python Algorithm- For the game "Ghost"- need a way to intelligently look up all 'winning' permutation of letters I'm writing a computer program to play the word game "Ghost." Here's how the current programs works: --User selects a letter (right now it only works if the user moves first) --Computer has a list of a...
Python Algorithm- For the game "Ghost"- need a way to intelligently look up all 'winning' permutation of letters
I'm writing a computer program to play the word game "Ghost." Here's how the current programs works: --User selects a letter (right now it only works if the user moves first) --Computer has a list of all possible odd-numbered words in its dictionary (this is so that the user will have to complete each word and therefo...
[ "You want the computer to look ahead, and yet choose randomly? :-)\nThis game is predictable enough and simple enough for you to make the computer always win, if you want. In fact, you can have it pre-generate strategy trees to guarantee a win. They aren't even that big, you could learn them by heart if you want.\n...
[ 1, 0 ]
[]
[]
[ "algorithm", "python", "string", "tree" ]
stackoverflow_0004822840_algorithm_python_string_tree.txt
Q: How to use multiple proxy in urllib2? Hello I'm have a task - create script, what will walk in internet and change proxy from list. I'm see in module urllib2: ProxyHandler and HTTPPasswordMgr, but manual is poor. 1. In documentation ProxyHandler get dict with many proxy-server, how to I'm can select from list and ...
How to use multiple proxy in urllib2?
Hello I'm have a task - create script, what will walk in internet and change proxy from list. I'm see in module urllib2: ProxyHandler and HTTPPasswordMgr, but manual is poor. 1. In documentation ProxyHandler get dict with many proxy-server, how to I'm can select from list and use for url_open? 2. HTTPPasswordMgr have m...
[ "ProxyHandler can use a different proxy for different protocols (HTTP, etc.) but I don't think it will help you. You should be able to write your own class for your needs without much difficulty.\n" ]
[ -1 ]
[]
[]
[ "proxy", "python", "urllib2" ]
stackoverflow_0004822860_proxy_python_urllib2.txt
Q: How to autopaginate this in Django Hey, dudes i wanna paginate some categories, but when i use autopaginate it always give me a TemplateError. Here is the code that i wanna paginate <!-- red 1 --> {% for tpl in cats %} <div class="clear Vraz10"></div> <div class="clear"> ...
How to autopaginate this in Django
Hey, dudes i wanna paginate some categories, but when i use autopaginate it always give me a TemplateError. Here is the code that i wanna paginate <!-- red 1 --> {% for tpl in cats %} <div class="clear Vraz10"></div> <div class="clear"> {% for cat in tpl %} ...
[ "It might be possible that you use {% autopaginate %} tag inside of block. Move it out of the {% block %} tag if this is the case.\nEverything else can be left as is, just the autopaginate tag doesn't work inside of blocks. It doesn't generate any content so it doesn't matter where you put it.\n{% extends ... %}\n{...
[ 0 ]
[]
[]
[ "django", "django_models", "html", "python", "templates" ]
stackoverflow_0004822248_django_django_models_html_python_templates.txt
Q: How to change the generated .py file by SWIG in cmake? We can use EXECUTABLE_OUTPUT_PATH to something like ${PROJECT_BINARY_DIR}/bin. How to set the output path for a generated python module by SWIG. ex, got the following CMakeLists.txt FIND_PACKAGE(SWIG) IF(SWIG_FOUND) FIND_PACKAGE(PythonLibs) IF(PYTHONLIBS_FOUN...
How to change the generated .py file by SWIG in cmake?
We can use EXECUTABLE_OUTPUT_PATH to something like ${PROJECT_BINARY_DIR}/bin. How to set the output path for a generated python module by SWIG. ex, got the following CMakeLists.txt FIND_PACKAGE(SWIG) IF(SWIG_FOUND) FIND_PACKAGE(PythonLibs) IF(PYTHONLIBS_FOUND) INCLUDE(${SWIG_USE_FILE}) EXECUTE_PROCESS( COMMAND pyth...
[ "From the CMake 2.8 docs:\n\nAnother special variable is\n CMAKE_SWIG_OUTDIR, it allows one to\n specify where to write all the swig\n generated module (swig -outdir option)\n\nSo, for example:\nset(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}/bin)\n\n", "Im not versed with CMAKE, however I know you can set t...
[ 5, 1 ]
[]
[]
[ "cmake", "python", "swig" ]
stackoverflow_0004807111_cmake_python_swig.txt
Q: check_password() from a user again I have the following form. How can I check the password from the user again, before the user can change his email address finally? Even if the user is logged in, I just want to be sure that it is really the user. Just a security thing. How do I do it with .check_password()? 'Emai...
check_password() from a user again
I have the following form. How can I check the password from the user again, before the user can change his email address finally? Even if the user is logged in, I just want to be sure that it is really the user. Just a security thing. How do I do it with .check_password()? 'EmailChangeForm' object has no attribute 'us...
[ "I would refactor your code to look something like this:\nView:\n@login_required\ndef view(request, extra_context=None, ...):\n\n form = EmailChangeForm(user=request.user, data=request.POST or None)\n\n if request.POST and form.is_valid():\n send_email_change_request(request.user,\n ...
[ 29, 11, 1 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0004822724_authentication_django_python.txt
Q: RSSI with pyBluez on WindowsXP I'm using the pyBluez module on Python 2.6 on WindowsXP. I'd like to get the RSSI of other bluetooth devices around. I foudn some code but it makes use of _bluetooth, which I cannto find anywhere for Windows. Is it available / is there another way to circumvent the problem, getting t...
RSSI with pyBluez on WindowsXP
I'm using the pyBluez module on Python 2.6 on WindowsXP. I'd like to get the RSSI of other bluetooth devices around. I foudn some code but it makes use of _bluetooth, which I cannto find anywhere for Windows. Is it available / is there another way to circumvent the problem, getting the RSSI without using _bluetooth? Th...
[ "MS bluetooth stack does not support RSSI measurement in the API.\nThis is confirmed for Windows XP till SP2 and situation seems not be changed in Vista nor Seven.\nWindows Mobile 6 has a different API for the BT management and offers the function BthReadRSSI.\nThe only way to get the RSSI from a bluetooth dongle i...
[ 1, 0, 0 ]
[]
[]
[ "bluetooth", "python", "rssi", "windows" ]
stackoverflow_0004815088_bluetooth_python_rssi_windows.txt
Q: Get all related many-to-many objects from a Django QuerySet I have a twisty maze of interrelated Django models, with many-to-many fields describing the relationships. What's the cleanest way to get a list of unique members of a related model from a QuerySet? If I have a Item model with a groups ManyToMany pointing...
Get all related many-to-many objects from a Django QuerySet
I have a twisty maze of interrelated Django models, with many-to-many fields describing the relationships. What's the cleanest way to get a list of unique members of a related model from a QuerySet? If I have a Item model with a groups ManyToMany pointing to the Groups model. If I have a queryset of Items, of 'items', ...
[ "One solution is to use 2 queries.\nYou can use the reverse relationships to query all Groups that an Item in your items points to.\ngroups = groups.objects.filter(item__in=items).distinct().values_list('name', flat=True)\n\n" ]
[ 18 ]
[]
[]
[ "django", "django_queryset", "many_to_many", "python" ]
stackoverflow_0004823601_django_django_queryset_many_to_many_python.txt
Q: Is there any reason to use malloc over PyMem_Malloc? I'm reading the documentation for Memory Management in Python C extensions, and as far as I can tell, there doesn't really seem to be much reason to use malloc rather than PyMem_Malloc. Say I want to allocate an array that isn't to be exposed to Python source c...
Is there any reason to use malloc over PyMem_Malloc?
I'm reading the documentation for Memory Management in Python C extensions, and as far as I can tell, there doesn't really seem to be much reason to use malloc rather than PyMem_Malloc. Say I want to allocate an array that isn't to be exposed to Python source code and will be stored in an object that will be garbage c...
[ "EDIT: Mixed PyMem_Malloc and PyObject_Malloc corrections; they are two different calls.\nWithout the PYMALLOC_DEBUG macro activated, PyMem_Malloc is an alias of libc's malloc(), having one special case: calling PyMem_Malloc to allocate zero bytes will return a non-NULL pointer, while malloc(zero_bytes) might retur...
[ 8, 7, 2 ]
[]
[]
[ "c", "malloc", "python", "python_c_extension" ]
stackoverflow_0004823054_c_malloc_python_python_c_extension.txt
Q: Does rect.center change rect properties? Greetings, It seems I am having a bit of trouble with a project I'm working on in pygame. For one of my objects i used: image.get_rect() and assigned it to: self.rect I understand the default coordinates for the get_rect function gives a value of (0,0). As a result, I use...
Does rect.center change rect properties?
Greetings, It seems I am having a bit of trouble with a project I'm working on in pygame. For one of my objects i used: image.get_rect() and assigned it to: self.rect I understand the default coordinates for the get_rect function gives a value of (0,0). As a result, I used: self.rect.center = (320,240) To roughly pl...
[ "The tuple type is immutable. That is, once set, you cannot change it.\nI assume that colliderect is trying to modify a tuple.\nUse a list in place of that tuple.\n" ]
[ 0 ]
[]
[]
[ "hittest", "pygame", "python" ]
stackoverflow_0004824244_hittest_pygame_python.txt
Q: Generated encrypted string does not have same size in PyCrypto and Crypto++ I recently used a Python script to encrypt a string. But could not decrypt it in C++ using Crypto++. I just compared generated encrypted strings and found they are not the same. Anybody can help? Here is my Python code: key = "0123456789a...
Generated encrypted string does not have same size in PyCrypto and Crypto++
I recently used a Python script to encrypt a string. But could not decrypt it in C++ using Crypto++. I just compared generated encrypted strings and found they are not the same. Anybody can help? Here is my Python code: key = "0123456789abcdef" data = "ccccccccccccccccdddddddddddddddd" iv = "aaaaaaaaaaaaaaaa" encrypto...
[ "By default, Crypto++ employs PKCS5 padding to the plaintext strings. This adds padding to the end of the string to make sure the string is a multiple of the block size which, for AES, is 16 bytes. If the plaintext is already a multiple of 16, Crypto++ adds another 16 bytes of padding to the plaintext and then encr...
[ 4 ]
[]
[]
[ "aes", "c++", "crypto++", "pycrypto", "python" ]
stackoverflow_0004632992_aes_c++_crypto++_pycrypto_python.txt
Q: Print text pyramid with spacing http://tekknolagi.co.cc/cgi-bin/helloworld.py that's the output what i would like it to do is make a pyramid shape here's the code... #!/usr/bin/env python # -*- coding: UTF-8 -*- # enable debugging import cgitb cgitb.enable() print "Content-Type: text/plain;charset=utf-8" print ...
Print text pyramid with spacing
http://tekknolagi.co.cc/cgi-bin/helloworld.py that's the output what i would like it to do is make a pyramid shape here's the code... #!/usr/bin/env python # -*- coding: UTF-8 -*- # enable debugging import cgitb cgitb.enable() print "Content-Type: text/plain;charset=utf-8" print for i in range(1,10): x = "hi...
[ "You can make use of the center command so that you can print both sides at once:\nfor i in range(1, 10):\n x = \" hi\" * i * 2\n print x.center(80)\n\n", "print x.rjust(40) + x.ljust(40)\n\n", "I had no clue about these justification functions. \nA little ipython auto completion showed me a center method...
[ 4, 4, 3, 2 ]
[]
[]
[ "cgi", "python", "python_2.x", "spacing" ]
stackoverflow_0004824301_cgi_python_python_2.x_spacing.txt
Q: Reading first line of an uploaded text file in python/django I am trying to process text files in a django app. Before I try to import the data, I need to evaluate the first line to determine the file type. i tried file[0], but of course that doesn't work. that did give me an error saying its a "'InMemoryUploadedF...
Reading first line of an uploaded text file in python/django
I am trying to process text files in a django app. Before I try to import the data, I need to evaluate the first line to determine the file type. i tried file[0], but of course that doesn't work. that did give me an error saying its a "'InMemoryUploadedFile' object" but I can't find much documentation about that. So, d...
[ "Django's UploadedFile has a content_type attribute which returns MIME type of the uploaded file supplied by user. \nIf you want to read the first line anyway, then you could use readline() method on the uploaded file object to get the first line. As Django's UploadedFile objects are file like objects, they support...
[ 2 ]
[]
[]
[ "django", "file_upload", "python" ]
stackoverflow_0004824410_django_file_upload_python.txt
Q: How do I calculate a 3D centroid? Is there even such a thing as a 3D centroid? Let me be perfectly clear—I've been reading and reading about centroids for the last 2 days both on this site and across the web, so I'm perfectly aware at the existing posts on the topic, including Wikipedia. That said, let me explain ...
How do I calculate a 3D centroid?
Is there even such a thing as a 3D centroid? Let me be perfectly clear—I've been reading and reading about centroids for the last 2 days both on this site and across the web, so I'm perfectly aware at the existing posts on the topic, including Wikipedia. That said, let me explain what I'm trying to do. Basically, I wan...
[ "In theory centroid = SUM(pos*volume)/SUM(volume) when you split the part into finite volumes each with a location pos and volume value volume.\nThis is precisely the calculation done for finding the center of gravity of a composite part.\n", "There is not just a 3D centroid, there is an n-dimensional centroid, a...
[ 8, 3, 2, 1 ]
[]
[]
[ "average", "maya", "python" ]
stackoverflow_0004824141_average_maya_python.txt
Q: Why do I get different instances of the same singleton in different modules? I have 2 files that print a singleton instance, but I get two different instances. I'm using Singleton code from Gary Robinson. Here are the files: test.py from singleton import Singleton import untitled class A(Singleton): def __ini...
Why do I get different instances of the same singleton in different modules?
I have 2 files that print a singleton instance, but I get two different instances. I'm using Singleton code from Gary Robinson. Here are the files: test.py from singleton import Singleton import untitled class A(Singleton): def __init__(self): super(A, self).__init__() if __name__ == "__main__": ...
[ "The reason you get two singletons is due to the way the modules are being imported. When you execute test.py from the command line, it is not known as test, it is __main__. An entry is added to sys.modules under the name __main__, and execution proceeds. When untitled imports test, sys.modules is examined, no m...
[ 3, 0 ]
[]
[]
[ "instances", "module", "python", "singleton" ]
stackoverflow_0004824096_instances_module_python_singleton.txt
Q: invert filename order script I have a set of files which the names follow this pattern: xxx - 001, xxx - 002 ..... xxx - 700 What I would like to do it`s a python script which I can invert the order of the name of the files, doing the xxx - 700 to be the xxx - 0001! A: Do you mean a Python script to rename all t...
invert filename order script
I have a set of files which the names follow this pattern: xxx - 001, xxx - 002 ..... xxx - 700 What I would like to do it`s a python script which I can invert the order of the name of the files, doing the xxx - 700 to be the xxx - 0001!
[ "Do you mean a Python script to rename all the files?\nFirst, you'll need to do the renaming into a different directory, or as soon as you rename \"xxx - 700\" to \"xxx - 001\", it will overwrite the existing file \"xxx - 001\". So have it rename \"xxx - 700\" to \"temp/xxx - 001\", and \"xxx - 699\" to \"temp/xxx ...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004824575_python.txt
Q: Detect fullscreen in pygtk I want to be able to detect if my app has been set to fullscreen by the user. I know I can use the gtk.window.fullscreen() method to make the window go fullscreen from the code, and the the action also emits a window-state-event signal, but when I wrote the callback I had no way of disti...
Detect fullscreen in pygtk
I want to be able to detect if my app has been set to fullscreen by the user. I know I can use the gtk.window.fullscreen() method to make the window go fullscreen from the code, and the the action also emits a window-state-event signal, but when I wrote the callback I had no way of distinguishing between when the event...
[ "You just need to check the event details.\n\nTo see what user action triggers the event, check changed_mask.\nTo see the new state (regardless of what causes the event), check new_window_state.\n\nUsually this translates into the following code:\n# Did the user actually toggle fullscreen, or was it\n# a different ...
[ 2 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0004824346_gtk_pygtk_python.txt
Q: Simple Django queryset __icontains search that will find most specific elements first I'm doing a queryset filter for "foo" in a CharField using __ictonains and I want to find the most specific search matches first. Dataset in database for a certain field named "description": fooal;skdjfkasdgh;alskdjrf foobar foo...
Simple Django queryset __icontains search that will find most specific elements first
I'm doing a queryset filter for "foo" in a CharField using __ictonains and I want to find the most specific search matches first. Dataset in database for a certain field named "description": fooal;skdjfkasdgh;alskdjrf foobar foo-nstastical foobariffic foo-ntastic foo When I search for: MyModel.objects.filter(descrip...
[ "If it's a small field, you could potentially sort by field length and get good results.\nGiven a match, the shortest result is the hardest and most significant match. Wouldn't work for full text of course...\nI would be comfortable doing this for an autocomplete username or tag field.\nfoo\nbofoo\nfoobar\nbarfood\...
[ 2 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0004824422_django_django_queryset_python.txt
Q: Python Packages Backward Compatibility Is there an easy way to tell if a Python package will work if not matched to my Python release? For example, I cannot get PyGreSQL for Python 2.7 on Win (only 2.6) and I can't get ZODB for Win any more recent than Python 2.4. Does the version mismatch guarantee incompatibil...
Python Packages Backward Compatibility
Is there an easy way to tell if a Python package will work if not matched to my Python release? For example, I cannot get PyGreSQL for Python 2.7 on Win (only 2.6) and I can't get ZODB for Win any more recent than Python 2.4. Does the version mismatch guarantee incompatibility, or do I just need to rename the package...
[ "There's no way to tell for sure if the package will work on another Python version, but using older packages on newer Python 2.x's is much much more likely to work than the other way around. \nOne thing to watch out for: if you're installing a Windows kit, it may only install in the version it was meant for, due t...
[ 3 ]
[]
[]
[ "package", "python", "zodb" ]
stackoverflow_0004824683_package_python_zodb.txt
Q: What is the difference between `vanilla Satchmo 0.8.1` and `just Satchmo v0.9.2`? What is the difference between vanilla Satchmo 0.8.1 and just Satchmo v0.9.2? A: There have been many changes in Satchmo between those releases so they are definitely different. Vanilla Satchmo 0.8.1 would refer to an unmodified sa...
What is the difference between `vanilla Satchmo 0.8.1` and `just Satchmo v0.9.2`?
What is the difference between vanilla Satchmo 0.8.1 and just Satchmo v0.9.2?
[ "There have been many changes in Satchmo between those releases so they are definitely different.\nVanilla Satchmo 0.8.1 would refer to an unmodified satchmo version 0.8.1. Satchmo v0.9.2 refers to Satchmo version 0.9.2, most likely also unmodified. If you are going to use Satchmo get 0.9.2 unless you have a real...
[ 1, 0 ]
[]
[]
[ "django", "python", "satchmo" ]
stackoverflow_0004766804_django_python_satchmo.txt
Q: Certificate Error on installing PythonForS60 I am trying to create a small application for Symbian mobile phones using Python. Being a beginner i am having some trouble in setting up the environment for development. I installed Symbian3 SDK,PyS60 Application Manager ( for creating the .sis files to be installed on...
Certificate Error on installing PythonForS60
I am trying to create a small application for Symbian mobile phones using Python. Being a beginner i am having some trouble in setting up the environment for development. I installed Symbian3 SDK,PyS60 Application Manager ( for creating the .sis files to be installed on phones) and python 2.5.2 . I created a small hell...
[ "Open Application Manager on your Symbian phone, go to settings and select Software installation. Change it from Signed to All. This will allow you to install applications which don't have a certificate, such as the SIS file you just packaged. \nAlso note that PythonForS60 2.0 works only with Python 2.5.\n" ]
[ 1 ]
[]
[]
[ "pys60", "python", "symbian" ]
stackoverflow_0004825055_pys60_python_symbian.txt
Q: Run function on WxPython GUI thread part-time C# programmer here trying to learn Python. I am looking to be able to, from another thread, set up a function that will be run on the GUI thread in WxPython. Currently the only way I can think of doing this is to push the function onto some cross-thread-synchronized li...
Run function on WxPython GUI thread
part-time C# programmer here trying to learn Python. I am looking to be able to, from another thread, set up a function that will be run on the GUI thread in WxPython. Currently the only way I can think of doing this is to push the function onto some cross-thread-synchronized list, then have a timer firing every few mi...
[ "wx.CallLater and wx.CallAfter().\n" ]
[ 5 ]
[]
[]
[ "multithreading", "python", "wxpython" ]
stackoverflow_0004825220_multithreading_python_wxpython.txt
Q: How to Display Data from MultipleChoiceField that renders in Unicode I have model data that came from a MultipleChoiceField. I have figured out it is rendering in unicode, but can't figure out how to display the data. {{chef.meal}} displays [u'Brunch'] How do you remove the unicode to only display the data? Thank...
How to Display Data from MultipleChoiceField that renders in Unicode
I have model data that came from a MultipleChoiceField. I have figured out it is rendering in unicode, but can't figure out how to display the data. {{chef.meal}} displays [u'Brunch'] How do you remove the unicode to only display the data? Thanks!
[ "That's a list. Join it or iterate over it to get the contents.\n{{ chef.meal|join:\", \" }}\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_templates", "python", "unicode" ]
stackoverflow_0004825390_django_django_templates_python_unicode.txt
Q: offsetting iterator I've got this : d = {"date": tuple(date),"open":tuple(open),"close":tuple(close)} comp1 = zip(d['open'],d['close']) for i in comp1: if i[0]<i[1]: print "bar up" if i[0]>i[1]: print "bar down" It's all well and good, it tells me if a bar is up or down, now I would ...
offsetting iterator
I've got this : d = {"date": tuple(date),"open":tuple(open),"close":tuple(close)} comp1 = zip(d['open'],d['close']) for i in comp1: if i[0]<i[1]: print "bar up" if i[0]>i[1]: print "bar down" It's all well and good, it tells me if a bar is up or down, now I would like to "shift" my iterat...
[ "If you're using a zip iterator why not just take it to the next level?\ncomp1 = zip(d['open'],d['close'],d['open'][1:],d['close'][1:])\n\nand there you have it as long as the tuples have length greater than 1. Now you can iterate over not only the tuples but also the next element of each tuple too.\n", "up = la...
[ 2, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004824789_python.txt
Q: python2.4.3: format bug? Here is an example: >>> "%.2f" % 0.355 '0.35' >>> "%.2f" % (float('0.00355') *100) '0.36' Why they give different result? A: This isn't a format bug. This is just floating point arithmetic. Look at the values underlaying your format commands: In [18]: float('0.00355') Out[18]: 0.00355...
python2.4.3: format bug?
Here is an example: >>> "%.2f" % 0.355 '0.35' >>> "%.2f" % (float('0.00355') *100) '0.36' Why they give different result?
[ "This isn't a format bug. This is just floating point arithmetic. Look at the values underlaying your format commands:\nIn [18]: float('0.00355')\nOut[18]: 0.0035500000000000002\n\nIn [19]: float('0.00355')*100\nOut[19]: 0.35500000000000004\n\nIn [20]: 0.355\nOut[20]: 0.35499999999999998\n\nThe two expressions crea...
[ 6, 4, 1 ]
[]
[]
[ "floating_point", "python", "python_2.4" ]
stackoverflow_0004825548_floating_point_python_python_2.4.txt
Q: How can I write a function in Python that rounds a number? How can I write a function in Python that rounds a number, in the usual fashion. Numbers less than .5 round down, and .5 and above rounds up. 3.4 -> 3 11.9 -> 12 5.5 -> 6 A: Use the Python function round(). If you want to do it yourself, add 0.5 and ...
How can I write a function in Python that rounds a number?
How can I write a function in Python that rounds a number, in the usual fashion. Numbers less than .5 round down, and .5 and above rounds up. 3.4 -> 3 11.9 -> 12 5.5 -> 6
[ "Use the Python function round(). If you want to do it yourself, add 0.5 and then truncate.\n", "def roundNumberAccordingly(number):\n digits = str(number)\n\n integer = 0\n remainder = 0\n seen_decimal = False\n for i in range(len(digits)):\n if digits[i] == '.':\n seen_decimal ...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004825131_python.txt
Q: dependencies for pywinauto Do I need sendkeys and ctypes to be installed prior to installing pywinauto for python 2.7.1? ctypes is already installed with python. Are there any other dependencies for pywinauto? A: The Docs are at http://pywinauto.googlecode.com/hg/pywinauto/docs/index.html - but as I write this a...
dependencies for pywinauto
Do I need sendkeys and ctypes to be installed prior to installing pywinauto for python 2.7.1? ctypes is already installed with python. Are there any other dependencies for pywinauto?
[ "The Docs are at http://pywinauto.googlecode.com/hg/pywinauto/docs/index.html - but as I write this answer - I notice that they are slightly out of date (fixed the dependencies now :) - but not uploaded yet)\nctypes does not have to be installed (it comes with Python 2.5 and later).\nsendkeys mis not necessary anym...
[ 1 ]
[]
[]
[ "python", "pywinauto" ]
stackoverflow_0004824993_python_pywinauto.txt
Q: Twitter API XML Access I'm playing around with Twitter's API, but I've come across something I'm confused about. I'm trying to get a list of friends/followers from a public profile, and I could get the user IDs in XML with this URL: http://twitter.com/followers/ids.xml?screen_name=[namehere] But then I read the d...
Twitter API XML Access
I'm playing around with Twitter's API, but I've come across something I'm confused about. I'm trying to get a list of friends/followers from a public profile, and I could get the user IDs in XML with this URL: http://twitter.com/followers/ids.xml?screen_name=[namehere] But then I read the documentations on the Twitter...
[ "Getting just the IDs of the followers via followers/ids does not require authentication, and neither do the calls to users/show, statuses/friends and statuses/followers. The linked documentation reflects this. My guess is that your python-twitter library, and not Twitter, is requiring you to authenticate, or thos...
[ 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0004763984_python_twitter.txt
Q: Extracting data from JavaScript (Python Scraper) I'm currently using a fusion of urllib2, pyquery, and json to scrape a site, and now I find that I need to extract some data from JavaScript. One thought would be to use a JavaScript engine (like V8), but that seems like overkill for what I need. I would use regul...
Extracting data from JavaScript (Python Scraper)
I'm currently using a fusion of urllib2, pyquery, and json to scrape a site, and now I find that I need to extract some data from JavaScript. One thought would be to use a JavaScript engine (like V8), but that seems like overkill for what I need. I would use regular expressions, but the expression for this seems way ...
[ "Why regex? Can't you just use two substrings as you know how many characters you want to trim off the beginning and end?\nstring[42:-7]\n\nAs well as being quicker than a regex, it then doesn't matter if quotes inside <html> are escaped or not.\n", "If every occurance of \" inside the html code would be escaped ...
[ 2, 1 ]
[]
[]
[ "javascript", "python", "regex", "scraper", "web_scraping" ]
stackoverflow_0004825509_javascript_python_regex_scraper_web_scraping.txt
Q: Method with variable number of objects and a list of other arguments I want to create a method that accepts a variable number of objects and perform some actions(like calling object methods) based on number of other arguments supplied to the method. e.g. I have an object X with a method updateTable() which accepts...
Method with variable number of objects and a list of other arguments
I want to create a method that accepts a variable number of objects and perform some actions(like calling object methods) based on number of other arguments supplied to the method. e.g. I have an object X with a method updateTable() which accepts a,b as arguments. What I want to do is that the common code to update tab...
[ "To get a Python function to accept an arbitrary number of arguments, just do this:\ndef my_function(*args, **kwargs):\n\nand now args will be a list of all the positional arguments passed to that function, and kwargs is a dictionary of all the keyword arguments.\nSince this is a method, you should probably explici...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004826617_python.txt
Q: Inside python code, how do I run a .sh script? Will it continue the code after it's run? Or will it stop at that line until the script is done? A: Using subprocess.call is the easiest way. It will not return until the executed program has terminated. Have a look at the other methods of the subprocess module if y...
Inside python code, how do I run a .sh script?
Will it continue the code after it's run? Or will it stop at that line until the script is done?
[ "Using subprocess.call is the easiest way. It will not return until the executed program has terminated. Have a look at the other methods of the subprocess module if you need different behaviour.\n", "import os\nos.system('./script.sh')\n\npython script won't stop until sh is finished\n", "You can use os.system...
[ 10, 8, 1 ]
[]
[]
[ "bash", "python", "shell" ]
stackoverflow_0004826686_bash_python_shell.txt
Q: Import from different directories in python This is my folder structure: src/ __init__py Lowlevel/ __init__.py ModuleToCheck.Py Test/ __init__.py ModuleToCheck_test.py (__init__.py are empty files) Now I want to import ModuleToCheck.py in ModuleToCheck_test.py How am I able to do this withou...
Import from different directories in python
This is my folder structure: src/ __init__py Lowlevel/ __init__.py ModuleToCheck.Py Test/ __init__.py ModuleToCheck_test.py (__init__.py are empty files) Now I want to import ModuleToCheck.py in ModuleToCheck_test.py How am I able to do this without appending anything to sys.path? Update: from ....
[ "The following is from http://docs.python.org/tutorial/modules.html#intra-package-references\n\nNote that both explicit and implicit\n relative imports are based on the name\n of the current module. Since the name\n of the main module is always\n \"__main__\", modules intended for use\n as the main module of a...
[ 3 ]
[]
[]
[ "import", "package", "python" ]
stackoverflow_0004826955_import_package_python.txt
Q: problem subclassing builtin type # Python 3 class Point(tuple): def __init__(self, x, y): super().__init__((x, y)) Point(2, 3) would result in TypeError: tuple() takes at most 1 argument (2 given) Why? What should I do instead? A: tuple is an immutable type. It's already created and immutable b...
problem subclassing builtin type
# Python 3 class Point(tuple): def __init__(self, x, y): super().__init__((x, y)) Point(2, 3) would result in TypeError: tuple() takes at most 1 argument (2 given) Why? What should I do instead?
[ "tuple is an immutable type. It's already created and immutable before __init__ is even called. That is why this doesn't work. \nIf you really want to subclass a tuple, use __new__. \n>>> class MyTuple(tuple):\n... def __new__(typ, itr):\n... seq = [int(x) for x in itr]\n... return tuple...
[ 10 ]
[]
[]
[ "built_in_types", "python", "python_3.x", "subclassing" ]
stackoverflow_0004827303_built_in_types_python_python_3.x_subclassing.txt
Q: Django: want to delete an item with checkbox I have a template that displays the list of items. It has one checkbox to each item. I want to be able to remove an item from a checkbox when a checkbox is ticked. So I would need a button that deletes an item once a checkbox is selected. Here is my template. Apologies ...
Django: want to delete an item with checkbox
I have a template that displays the list of items. It has one checkbox to each item. I want to be able to remove an item from a checkbox when a checkbox is ticked. So I would need a button that deletes an item once a checkbox is selected. Here is my template. Apologies for the huge template. {% extends "base_popup.ht...
[ "I'm interpreting your question as, essentially, when a checkbox is clicked, you want to remove that row from your table. \nYou'll need to write a page that takes the ID of the item to be deleted, and returns true or false based on whether it's successful or not. I'd also advise you to not do this when the checkbox...
[ 1 ]
[]
[]
[ "checkbox", "django", "jquery", "python", "templates" ]
stackoverflow_0004827171_checkbox_django_jquery_python_templates.txt
Q: defining parsing range for a CSV I`m importing a CSV containing data from year 2002 to 2011 , using this : pair = csv.reader(open(sys.argv[1]), delimiter=' ') names = [] ; date = [] ; open = [] ; close = [] ; min = [] ; max = [] #Parse the CSV file into a list for data in pair: names.append(data[0]) names.po...
defining parsing range for a CSV
I`m importing a CSV containing data from year 2002 to 2011 , using this : pair = csv.reader(open(sys.argv[1]), delimiter=' ') names = [] ; date = [] ; open = [] ; close = [] ; min = [] ; max = [] #Parse the CSV file into a list for data in pair: names.append(data[0]) names.pop(0) How would I just keep the 2010 v...
[ "You test on the date, and keep it only if it's the right year. How this is done depends on what format the date is in, etc. For example:\nfrom datetime import datetime\n\nfor data in pair:\n date = datetime.strptime(data[1], <yourdateformat>)\n if date.year == 2010:\n names.append(data[0])\n\n", "As...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004825825_python.txt
Q: Python - convert to ? I'm using libxml2 and libxslt to process XML files. The return value is of type instance but I need to have a UTF-8 static string. styledoc = libxml2.parseFile(style_file) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseDoc(xml_data.encode("UTF-8")) html = style.applyStylesh...
Python - convert to ?
I'm using libxml2 and libxslt to process XML files. The return value is of type instance but I need to have a UTF-8 static string. styledoc = libxml2.parseFile(style_file) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseDoc(xml_data.encode("UTF-8")) html = style.applyStylesheet(doc) return html # <- t...
[ "Use \nreturn style.saveResultToString(html)\n\nInstead of return html\nHere is xml and xslt test files I used, and my test codes\ntest.xsl\n<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n <xsl:output method=\"html\" encoding=\"UT...
[ 2, 1 ]
[]
[]
[ "libxml2", "libxslt", "python", "static", "string" ]
stackoverflow_0004827521_libxml2_libxslt_python_static_string.txt
Q: python cx_freeze problem ascil I want to make EXE file by use py2exe or cx_freeze. so I was try to make exe file with py2exe but no luck. so now I was test with cx_freeze but it also failed. if anyone can help me much apprecaite following is setup.py file in cx_freeze from cx_Freeze import setup, Executable co...
python cx_freeze problem ascil
I want to make EXE file by use py2exe or cx_freeze. so I was try to make exe file with py2exe but no luck. so now I was test with cx_freeze but it also failed. if anyone can help me much apprecaite following is setup.py file in cx_freeze from cx_Freeze import setup, Executable copyDependentFiles=True silent = True ...
[ "The Python code you have posted is actually incorrect - if this is the actual code that you are trying to freeze - then you probably get an error along the lines of\n File \"cx_freeze_test.py\", line 35\n for line in os.popen(\"ipconfig /all\"):\n ^\nIndentationError: un...
[ 6 ]
[]
[]
[ "cx_freeze", "python" ]
stackoverflow_0004058927_cx_freeze_python.txt
Q: Are there any uses of the empty tuple in Python? Is there any other purpose (besides being there because it needs to be) the empty tuple may have? Or: what would you use the empty tuple for? If anything. I just can't find an answer (well, a positive answer as in: "yes, there is"), please help me out with getting t...
Are there any uses of the empty tuple in Python?
Is there any other purpose (besides being there because it needs to be) the empty tuple may have? Or: what would you use the empty tuple for? If anything. I just can't find an answer (well, a positive answer as in: "yes, there is"), please help me out with getting this question out of my head. "for testing if another t...
[ "Here's when.\ndef tuple_of_primes_less_than( n ):\n if n <= 2: return ()\n else:\n x, p = set( range(2,n) ), 2\n while p <= max(x):\n for k in range(2,int(2+math.sqrt(p))):\n x.discard(k*p)\n p += 1\n return tuple( sorted( x ) )\n\n", "You might wan...
[ 21, 8, 4 ]
[]
[]
[ "python" ]
stackoverflow_0004828041_python.txt