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: Creating xml file in django How can i create a xml file in django where the file is to contain objects from a queryset? def my_serialize(request): from django.core import serializers data = serializers.serialize('xml', Student.objects.filter(Q(name__startswith='A')), fields=('name','dob')) ...
Creating xml file in django
How can i create a xml file in django where the file is to contain objects from a queryset? def my_serialize(request): from django.core import serializers data = serializers.serialize('xml', Student.objects.filter(Q(name__startswith='A')), fields=('name','dob')) from django.core.files import Fi...
[ "from django.core import serializers\ndata = serializers.serialize(\"xml\", SomeModel.objects.all())\n\nTake a look at the Serialization documentation.\n", "I don't use version 1.3, so I'm not sure how it works, but could it be that the file is not actually being opened? Could adding myfile.open('w') work? Of cou...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005867570_django_python.txt
Q: Python: parse Text File and Show as a Graph I have text files that are in this format: BFrame.make() Frame.make_bbox() BBox.__init__(arg1=x, arg2=y, arg3=z) : None BBox.make() BBox.chk_pre() : None : (1,1,2,2) : None ExConfig.__init__(...
Python: parse Text File and Show as a Graph
I have text files that are in this format: BFrame.make() Frame.make_bbox() BBox.__init__(arg1=x, arg2=y, arg3=z) : None BBox.make() BBox.chk_pre() : None : (1,1,2,2) : None ExConfig.__init__(filename=None) ExConfig.setParam() ...
[ "Looks like you need a real parser here, since this is not a trivial format.\nMany methods for writing parsers in Python exist. See, for example, PLY. Another is PyParsing. \nAlternatively, maybe Python Call Graph is what you really need?\n", "Here's my shot at this:\na = \"\"\"BFrame.make()\n Frame.make_bbo...
[ 1, 1 ]
[]
[]
[ "graph", "parsing", "python" ]
stackoverflow_0005867140_graph_parsing_python.txt
Q: Passing Numpy arrays to a C function for input and output Oh my word I'm a fool. I was simply omitting the second and third arguments when calling the function. Like a fool. Because that's what I am. Original silly question follows: This seems like it must be a very common thing to do, but I can't find a relevant ...
Passing Numpy arrays to a C function for input and output
Oh my word I'm a fool. I was simply omitting the second and third arguments when calling the function. Like a fool. Because that's what I am. Original silly question follows: This seems like it must be a very common thing to do, but I can't find a relevant tutorial, and I'm too ignorant about Numpy and ctypes to figure...
[ "While not a direct answer to your original question, here's a much more convenient way to call your function. First, make the prototype of your C function exactly as you would do it in plain C. Since you don't need rowcount and colcount separately, I'll collapse them into a single size parameter:\nvoid cfun(cons...
[ 87, 21 ]
[]
[]
[ "ctypes", "ffi", "numpy", "python" ]
stackoverflow_0005862915_ctypes_ffi_numpy_python.txt
Q: Will installing new version of Python conflict with old versions I'm a newbie programmer just installing Python 3.2, but I know I also have an older version of Python on my machine. in fact, I think Macbook comes with it installed. Do I have to worry about having different versions on my computer when I try to sta...
Will installing new version of Python conflict with old versions
I'm a newbie programmer just installing Python 3.2, but I know I also have an older version of Python on my machine. in fact, I think Macbook comes with it installed. Do I have to worry about having different versions on my computer when I try to start learning Python?
[ "For the most part, you don't have to worry about conflicts with system Python. In fact it is recommended to install a different Python version instead of working with system Python. Also consider using virtualenv and virtualenvwrapper to maintain any dependencies for each project easily without conflicts.\n", "I...
[ 5, 4, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005552234_python.txt
Q: Data Binding / Data Conversion in Python Is there a Python lib to convert a bunch of strings to appropriate objects? Web frameworks represent request data typically as map of the form { str : [str, ..]} and I want to apply these string data structure to domain objects like Grails does: def book = new Book(params) ...
Data Binding / Data Conversion in Python
Is there a Python lib to convert a bunch of strings to appropriate objects? Web frameworks represent request data typically as map of the form { str : [str, ..]} and I want to apply these string data structure to domain objects like Grails does: def book = new Book(params) // params is from the request or book.propert...
[ "The example you show looks similar to JSON (see e.g. the json python module).\nQuoting an example from its documentation:\nimport json\njson.loads('[\"foo\", {\"bar\":[\"baz\", null, 1.0, 2]}]')\n\ngives you a nested structure of lists/dicts:\n[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]\n\n" ]
[ 1 ]
[]
[]
[ "converter", "data_binding", "grails", "python" ]
stackoverflow_0005868132_converter_data_binding_grails_python.txt
Q: How to Get a line of text from html to Python Im creating a program that prints out the Ip adress of the User. So what im trying to do is to get the Html of ipchicken.com and print out only the "Name Address" Part. here is my code so far: import urllib sock = urllib.urlopen("http://ipchicken.com") ht...
How to Get a line of text from html to Python
Im creating a program that prints out the Ip adress of the User. So what im trying to do is to get the Html of ipchicken.com and print out only the "Name Address" Part. here is my code so far: import urllib sock = urllib.urlopen("http://ipchicken.com") htmlSource = sock.read() sock.close() prin...
[ "Use a HTML scraping library, like BeautifulSoup.\n", "I would suggest that you use something that's more programmatic like ifconfig.me rather than ipchicken which is ad laden. ifconfig.me behaves different when being queried by something like cURL.\nIf you want to parse the HTML and get out the IP address with i...
[ 2, 2, 2, 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0005868341_html_python.txt
Q: Convert a string to datetime object in python I have a date string defined as followed: datestr = '2011-05-01' I want to convert this into a datetime object so i used the following code dateobj = datetime.datetime.strptime(datestr,'%Y-%m-%d') print dateobj But what gets printed is: 2011-05-01 00:00:00. I just ne...
Convert a string to datetime object in python
I have a date string defined as followed: datestr = '2011-05-01' I want to convert this into a datetime object so i used the following code dateobj = datetime.datetime.strptime(datestr,'%Y-%m-%d') print dateobj But what gets printed is: 2011-05-01 00:00:00. I just need 2011-05-01. What needs to be changed in my code ...
[ "dateobj.date() will give you the datetime.date object, such as datetime.date(2011, 5, 1)\nUse:\ndateobj = datetime.datetime.strptime(datestr,'%Y-%m-%d').date()\n\nSee also: Python documentation on datetime.\n", "As the name suggests, datetime objects always contain a date and a time. If you don't need the time,...
[ 12, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005868374_python.txt
Q: Does Django's form framework use the Django messages framework? I'm using django-registration and getting an introduction to Django's form framework. I've been using the .to_p() method to display forms, but I need a better way of presenting the form data, so I'm reading up on the forms framework. Do errors passed ...
Does Django's form framework use the Django messages framework?
I'm using django-registration and getting an introduction to Django's form framework. I've been using the .to_p() method to display forms, but I need a better way of presenting the form data, so I'm reading up on the forms framework. Do errors passed by the form framework get passed to Django's messages framework?
[ "No, they're completely separate - as they should be, as messages is in django.contrib and therefore can't be guaranteed to be enabled.\nThe best way to show errors is within the form itself, as the as_p method does. I use a template tag to display each field with its associated errors in one go - it's a modified v...
[ 4, 2, 0 ]
[]
[]
[ "django", "forms", "messages", "python" ]
stackoverflow_0005867313_django_forms_messages_python.txt
Q: Forcing steps with django form wizard How would I force steps for the django form wizard? I have step 0 showing a Subscription page with different account types. I wanted to have the ability to send someone a link such as /join/basic or /join/pro And have that link forward them to the correct step/form. Ive found...
Forcing steps with django form wizard
How would I force steps for the django form wizard? I have step 0 showing a Subscription page with different account types. I wanted to have the ability to send someone a link such as /join/basic or /join/pro And have that link forward them to the correct step/form. Ive found: FormWizard.parse_params() A hook for sav...
[ "I think you should handle the \"switch form\" behaviour here:\nFormWizard.process_step()\n\nThere you the data from previous submitted (and valid) form and is supposed to be the place where you \"change the internal state\" of the wizard (eg. to change the form list)\nNote that the method is called every time a st...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005864440_django_python.txt
Q: App Engine - Specify entity name at runtime In the low-level Java api, I used to be able to make up entity names at runtime. In python, it seems that I have to pre-define a class name that is also my entity name: class SomeKindaData(db.Expando): pass sKD = SomeKindaData(key_name='1') ... Is there a way to ma...
App Engine - Specify entity name at runtime
In the low-level Java api, I used to be able to make up entity names at runtime. In python, it seems that I have to pre-define a class name that is also my entity name: class SomeKindaData(db.Expando): pass sKD = SomeKindaData(key_name='1') ... Is there a way to make entity names up at run time in App Engine for ...
[ "I don't know much about App Engine, but you can define classes at run time like this:\ndef get_my_class(name):\n return type(name, (db.Expando,), {})\n\nSo type takes three arguments:\n\nname of class\ntuple of classes to inherit from\ndictionary of class attributes\n\n", "Entities themselves don't have names...
[ 3, 2 ]
[]
[]
[ "entity", "google_app_engine", "python" ]
stackoverflow_0005865254_entity_google_app_engine_python.txt
Q: programmatically update facebook status Is there a Python program where you can post a status update without going to the website itself? Where or how do i get started? A: You would wanna get started here, https://github.com/facebook/python-sdk unless there's a library I don't know about. A: You can checkout...
programmatically update facebook status
Is there a Python program where you can post a status update without going to the website itself? Where or how do i get started?
[ "You would wanna get started here, https://github.com/facebook/python-sdk\nunless there's a library I don't know about. \n", "You can checkout my fork of the python sdk. It's customized to work better with django.\nYou can check here on how to use it to authenticate a user.\nAfter that you can use the python sdk ...
[ 2, 1 ]
[]
[]
[ "facebook", "post", "python", "status" ]
stackoverflow_0005868756_facebook_post_python_status.txt
Q: How to receive an uploaded file to store it using Blobstore API I have a server side code to process uploaded binary files: class UploadHandler(webapp.RequestHandler): def post(self): file_name = files.blobstore.create(mime_type='application/octet-stream') with files.open(file_name, 'a') as f: ...
How to receive an uploaded file to store it using Blobstore API
I have a server side code to process uploaded binary files: class UploadHandler(webapp.RequestHandler): def post(self): file_name = files.blobstore.create(mime_type='application/octet-stream') with files.open(file_name, 'a') as f: f.write('data') files.finalize(file_name) ...
[ "Should be something like this:\nclass UploadHandler(webapp.RequestHandler):\n def post(self):\n mime_type = self.request.headers['X-File-Type']\n name = self.request.headers['X-File-Name']\n file_name = files.blobstore.create(mime_type=mime_type,\n ...
[ 1 ]
[]
[]
[ "blobstore", "google_app_engine", "python" ]
stackoverflow_0005869578_blobstore_google_app_engine_python.txt
Q: sqlalchemy identity map question The identity map and unit of work patterns are part of the reasons sqlalchemy is much more attractive than django.db. However, I am not sure how the identity map would work, or if it works when an application is configured as wsgi and the orm is accessed directly through api calls,...
sqlalchemy identity map question
The identity map and unit of work patterns are part of the reasons sqlalchemy is much more attractive than django.db. However, I am not sure how the identity map would work, or if it works when an application is configured as wsgi and the orm is accessed directly through api calls, instead of a shared service. I would ...
[ "I think you misunderstood the identity map pattern.\nFrom : http://martinfowler.com/eaaCatalog/identityMap.html\n\nAn Identity Map keeps a record of all\n objects that have been read from the\n database in a single business\n transaction.\n\nRecords are kept in the identity map for a single business transaction...
[ 8, 0 ]
[]
[]
[ "identity_map", "python", "sqlalchemy" ]
stackoverflow_0005869514_identity_map_python_sqlalchemy.txt
Q: how to make child of a list become a variable in python i'm trying to make a web only using couchdb and couchapp... but for some reason i need external process using python.. and now i'm stuck how to handle post variable in python... i'v read this(and it works) and this... but i want it like this : >>> a = {"succ...
how to make child of a list become a variable in python
i'm trying to make a web only using couchdb and couchapp... but for some reason i need external process using python.. and now i'm stuck how to handle post variable in python... i'v read this(and it works) and this... but i want it like this : >>> a = {"success":1,"data":{"var1":1,"var2":2,"var3":3}} >>> a["data"]["va...
[ "you should try to update your local (not recommended) or global dictionnary with your data dictionnary\n>>> a = {\"success\":1,\"data\":{\"var1\":1,\"var2\":2,\"var3\":3}}\n>>> a[\"data\"][\"var2\"]\n2\n>>> locals().update(a[\"data\"])\n>>> var2\n2\n\nor \n>>> globals().update(a[\"data\"])\n>>> var2\n2\n\nTo do th...
[ 4, 2, 1 ]
[]
[]
[ "couchapp", "external_process", "metaprogramming", "python" ]
stackoverflow_0005867895_couchapp_external_process_metaprogramming_python.txt
Q: Ensure all code on all machines are the same - python mpi I can have up to 20 machines in my MPI rings. How can I automate some sort of checking that all machines are using the same version of their python code? Is there a way to generate a hash of all the modules/source files in your program? A: I don't know ...
Ensure all code on all machines are the same - python mpi
I can have up to 20 machines in my MPI rings. How can I automate some sort of checking that all machines are using the same version of their python code? Is there a way to generate a hash of all the modules/source files in your program?
[ "I don't know of a way to hash the package contents beyond hashing a zip archive of the code. But why not create a local package repository. Have the MPI nodes download the latest version of the package and install it (locally or in a virtualenv if you prefer) at the start of the run? You can always check the packa...
[ 2 ]
[]
[]
[ "mpi", "python" ]
stackoverflow_0005863897_mpi_python.txt
Q: opening a txt file in an editor with python I'm newbie with python, I'm writing a program with python to let the user select an XML script and the python program will automatically parse the XML and create a txt file using header info from the XML and open that txt file in a text editor window. I've figured out e...
opening a txt file in an editor with python
I'm newbie with python, I'm writing a program with python to let the user select an XML script and the python program will automatically parse the XML and create a txt file using header info from the XML and open that txt file in a text editor window. I've figured out everything but how to get the txt file opened in t...
[ "Im not sure if understand the question entirely, but to open a pre-existing txt file with python using the default app. You could use\nimport webbrowser\nfile = \"TEXT.txt\"\nwebbrowser.open(file)\n\n", "I'm assuming you want the contents of the extracted text to show up in your wx.TextCtrl, correct? If so, try ...
[ 1, 0, 0 ]
[]
[]
[ "python", "text_files", "window", "wxpython", "xml" ]
stackoverflow_0005863027_python_text_files_window_wxpython_xml.txt
Q: Which Django/Pinax app should I use? There are so many, and I just want the simplest one I want a "settings" page where the user can submit his hometown/biography/email settings and upload his avatar We will be building a mobile app that uses HTTP Rest API to update the user's profile, so we must be able to do man...
Which Django/Pinax app should I use? There are so many, and I just want the simplest one
I want a "settings" page where the user can submit his hometown/biography/email settings and upload his avatar We will be building a mobile app that uses HTTP Rest API to update the user's profile, so we must be able to do manual override of these apps. That's it! I don't want anything else. I don't care about the fr...
[ "django-profile may be of use in this case.\n", "I actually am approaching the same problem.\nI find overriding the pinax profile app is enough. The profile section is what allows the upload of avatars and your info and allows you to also edit it.\nI still haven't found a good way to override the native apps yet....
[ 1, 1, 0 ]
[]
[]
[ "django", "pinax", "profiles", "python" ]
stackoverflow_0004299769_django_pinax_profiles_python.txt
Q: Class-based (generic) views in Flask What's the best way to write generic views using the Flask web framework? Does the @app.route decorator support callable classes? Or am I thinking about this in entirely the wrong fashion? Any help or advice would be greatly appreciated! A: Starting with Python 2.6 you can ap...
Class-based (generic) views in Flask
What's the best way to write generic views using the Flask web framework? Does the @app.route decorator support callable classes? Or am I thinking about this in entirely the wrong fashion? Any help or advice would be greatly appreciated!
[ "Starting with Python 2.6 you can apply the decorators to classes as well. There is no builtin pattern for callable classes because there are too many ways to implement them, but essentially the trick would be to override __call__ on the class and to have a wrapper decorator that instanciates the class.\nI was pla...
[ 11 ]
[]
[]
[ "django_class_based_views", "flask", "python", "web_frameworks" ]
stackoverflow_0005869899_django_class_based_views_flask_python_web_frameworks.txt
Q: GtkTreeviewColumn with different combo model for each row I have a global set of values, e.g. ["Foo", "Bar", "Baz", "Quux"]. Each row in my TreeView represents an entity that can only deal with a subset of these values. For example, the first row might deal with "Foo" and "Bar", and the second, "Bar" and "Quux". I...
GtkTreeviewColumn with different combo model for each row
I have a global set of values, e.g. ["Foo", "Bar", "Baz", "Quux"]. Each row in my TreeView represents an entity that can only deal with a subset of these values. For example, the first row might deal with "Foo" and "Bar", and the second, "Bar" and "Quux". I want a ComboBox column to allow each row to select one of the ...
[ "What you are looking for is gtk.TreeModelFilter. It is a tree model containing filtered values of another underlying tree model. You can decide which rows should be visible by calling set_visible_func() on the filtered model.\n", "There's also another way to do this. \nSee also:\nhttp://mail.gnome.org/archives/g...
[ 3, 2 ]
[]
[]
[ "combobox", "gtk", "gtktreeview", "python" ]
stackoverflow_0003575606_combobox_gtk_gtktreeview_python.txt
Q: Fast DES for Python i am searching for compiled des implementation for python. M2Crypto don't work for me with error message "ImportError: DLL load failed:". OpenSSLLight installed. Edit: ok, fixed with M2Crypto. For some reasons, if you select during the installation of SSLLight that the libraries should be place...
Fast DES for Python
i am searching for compiled des implementation for python. M2Crypto don't work for me with error message "ImportError: DLL load failed:". OpenSSLLight installed. Edit: ok, fixed with M2Crypto. For some reasons, if you select during the installation of SSLLight that the libraries should be placed in the program director...
[ "Pycrypto supports DES/DES3 and has prebuilt Windows installers from Voidspace. Quick example:\nfrom Crypto.Cipher import DES\ndes = DES.new('13371337', DES.MODE_ECB)\ndes.encrypt('plaintxt')\n\n'\\xeb\\x9d\\xe7~&\\xb4fp'\n\n" ]
[ 0 ]
[]
[]
[ "des", "python" ]
stackoverflow_0005866510_des_python.txt
Q: Cocoa/OSX console messages: Could not setup Mach task special port 9: (os/kern) no access I have a data gathering app (terrestrial magnetic field strength) that has four phases; they run, via cron, at 2,3,4, and 5 minute intervals, ordered so that everything needed for one step is collected before it happens. Beca...
Cocoa/OSX console messages: Could not setup Mach task special port 9: (os/kern) no access
I have a data gathering app (terrestrial magnetic field strength) that has four phases; they run, via cron, at 2,3,4, and 5 minute intervals, ordered so that everything needed for one step is collected before it happens. Because of the intervals, I can't, as I understand it, use launchd to fire the phases; consequently...
[ "Ok. I've done a LOT of googling, and there are several things of note about this issue. First, the problem has existed for years. There are huge numbers of complaints about it on the net. I found a post in the Apple dev forums where it was said that Apple knew about it, it's a bug, and would be fixed at some futur...
[ 1, 0 ]
[]
[]
[ "console", "cron", "crontab", "macos", "python" ]
stackoverflow_0005807338_console_cron_crontab_macos_python.txt
Q: How to insert an image in a web based Python application? Actually i want to insert an image in a web application which uses Python as server side scripting language. I am using Python 2.7 version in windows platform. I have written a simple script to insert an image in python language. print "<img src='image.png'...
How to insert an image in a web based Python application?
Actually i want to insert an image in a web application which uses Python as server side scripting language. I am using Python 2.7 version in windows platform. I have written a simple script to insert an image in python language. print "<img src='image.png'>" Even in this script i am not getting any errors or warnings...
[ "No, you need not import any extra packages. Just use raw string in Python because if your path contains \\n like characters, it should be interpreted for newline. Like this\nprint r'<img src=\"c:\\path\\new\\image.png'\n\nBut when are printing html in server-side, you are actually doing CGI programming and I would...
[ 1, 1 ]
[]
[]
[ "image", "python" ]
stackoverflow_0005870446_image_python.txt
Q: Peeking in a heap in python What is the official way of peeking in a python heap as created by the heapq libs? Right now I have def heappeak(heap): smallest = heappop(heap) heappush(heap, smallest) return smallest which is arguably, not very nice. Can I always assume that heap[0] is the top of the heap and ...
Peeking in a heap in python
What is the official way of peeking in a python heap as created by the heapq libs? Right now I have def heappeak(heap): smallest = heappop(heap) heappush(heap, smallest) return smallest which is arguably, not very nice. Can I always assume that heap[0] is the top of the heap and use that? Or would that assume to...
[ "Yes, you can make this assumption, because it is stated in the documentation:\n\nHeaps are arrays for which heap[k] <= heap[2*k+1] and heap[k] <=\n heap[2*k+2] for all k, counting\n elements from zero. For the sake of\n comparison, non-existing elements are\n considered to be infinite. The\n interesting prope...
[ 83, 9 ]
[]
[]
[ "heap", "peek", "python" ]
stackoverflow_0001750991_heap_peek_python.txt
Q: Strange Python datetime import problem Hi I'm finding this problem to manifest differently on various setups. I've had any one of the following work while the others fail, and this changes sometimes (that is one snippet would fail on one setup while the other fail on another) from datetime import datetime datetim...
Strange Python datetime import problem
Hi I'm finding this problem to manifest differently on various setups. I've had any one of the following work while the others fail, and this changes sometimes (that is one snippet would fail on one setup while the other fail on another) from datetime import datetime datetime.datetime.utcnow() import datetime dateti...
[ "IF you're doing from datetime import datetime, you need to use datetime.utcnow() instead of datetime.datetime.utcnow(). I can't possibly see how your first snippet could ever work.\n>>> from datetime import datetime\n>>> datetime.datetime.utcnow()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in...
[ 4, 4, 0 ]
[]
[]
[ "datetime", "import", "python" ]
stackoverflow_0005870702_datetime_import_python.txt
Q: I'm trying to understand how to call a function from another function in the same class I'm attempting to login to an Ubuntu server and search logs at several different paths with a function that already works locally (Python 2.7 - win7 machine). Below is the function of how I login and select the logs (also, the ...
I'm trying to understand how to call a function from another function in the same class
I'm attempting to login to an Ubuntu server and search logs at several different paths with a function that already works locally (Python 2.7 - win7 machine). Below is the function of how I login and select the logs (also, the basis of my program is Python's cmd module): def do_siteserver(self, line): import par...
[ "Methods are invoked via the object that has them.\nself.do_search(...)\n\n", "self.do_search(linenumber)\n\nThat is all.\n" ]
[ 2, 2 ]
[]
[]
[ "cmd", "function_calls", "python" ]
stackoverflow_0005870788_cmd_function_calls_python.txt
Q: Why call clearup code in generator function? guys. I'm reading web.py source code to understand how WSGI frameworks work. When reading application.py module, I wonder why call self._cleanup in cleanup which is a generator function. I searched reasons to use generator, like this, but I'm not sure why use generator ...
Why call clearup code in generator function?
guys. I'm reading web.py source code to understand how WSGI frameworks work. When reading application.py module, I wonder why call self._cleanup in cleanup which is a generator function. I searched reasons to use generator, like this, but I'm not sure why use generator here. Here is the code block: def wsgi(env, start_...
[ "What itertools.chain(result, cleanup()) does is effectively\ndef wsgi(env, start_resp):\n [...]\n\n status, headers = web.ctx.status, web.ctx.headers\n start_resp(status, headers)\n\n for part in result:\n yield part\n self._cleanup()\n # yield '' # you'd skip this line because it's point...
[ 1 ]
[]
[]
[ "frameworks", "python", "web.py", "wsgi" ]
stackoverflow_0005870676_frameworks_python_web.py_wsgi.txt
Q: Python run command line (time) I want to run the 'time' unix command from a Python script, to time the execution of a non Python app. I would use the os.system method. Is there any way to save the output of this in Python? My goal is to run the app several times, save their execution times and then do some statist...
Python run command line (time)
I want to run the 'time' unix command from a Python script, to time the execution of a non Python app. I would use the os.system method. Is there any way to save the output of this in Python? My goal is to run the app several times, save their execution times and then do some statistics on them. Thank You
[ "You really should be using the subprocess module to run external commands. The Popen() method lets you specify a file object where stdout should go (note, you can use any Python object that behaves like a file, you don't necessarily need to write it to a file).\nFor instance:\nimport subprocess\nlog_file = open('/...
[ 3, 0 ]
[]
[]
[ "command_line", "python", "time" ]
stackoverflow_0002662852_command_line_python_time.txt
Q: Django: How to import variables in html templates I have a django application and what I want to do is change wherever it says "Company id" in my templates. The thing it can be very tedious because I have to make this change in every template which says "Company id". So then I thought I might create another file t...
Django: How to import variables in html templates
I have a django application and what I want to do is change wherever it says "Company id" in my templates. The thing it can be very tedious because I have to make this change in every template which says "Company id". So then I thought I might create another file that can store this entry, which the I can easy custom t...
[ "This is what context processors are for. Define your company name in settings.py, then write a context processor that imports it from there and returns it in a dictionary - it will then be available in every template (as long as you use RequestContext to render the template).\n", "As Blender stated, you need to ...
[ 4, 1, 0 ]
[]
[]
[ "django", "html", "python", "variables" ]
stackoverflow_0005870809_django_html_python_variables.txt
Q: How to fake a soap response in Python? I am trying to test a function in company product. Our software will make a SOAP request like this: Request Header POST /testfunction.php HTTP/1.1 Accept: application/soap+xml, application/xml, text/xml SOAPAction: "http://www.abc.com/testfunction#test" Host: soap.abc.com Con...
How to fake a soap response in Python?
I am trying to test a function in company product. Our software will make a SOAP request like this: Request Header POST /testfunction.php HTTP/1.1 Accept: application/soap+xml, application/xml, text/xml SOAPAction: "http://www.abc.com/testfunction#test" Host: soap.abc.com Content-Length: 461 Connection: Keep-Alive Req...
[ "You could use soaplib to create a real SOAP service which implements your interface and returns dummy data. This should be a bit easier to maintain then creating handwritten static responses, and the code shouldn't be much longer than your web.py-based example.\nHere's a Hello World example.\n" ]
[ 8 ]
[]
[]
[ "python", "simplexmlrpcserver", "soap", "testing", "web.py" ]
stackoverflow_0005870893_python_simplexmlrpcserver_soap_testing_web.py.txt
Q: what's a simple way to search a very long text file for a word in python? I want to create a very simple spell checker using a text file with an alphabetized list of about 80000 common words. What's a simple but efficient way to search the file and find out if it contains a word using python? Should I parse the ...
what's a simple way to search a very long text file for a word in python?
I want to create a very simple spell checker using a text file with an alphabetized list of about 80000 common words. What's a simple but efficient way to search the file and find out if it contains a word using python? Should I parse the word list file into a set, list, dictionary, tuple? Is there an easy way to tak...
[ "Since 80000 words will easily fit in memory, you are best off using a set:\nwords = set(line.strip() for line in open(\"words\"))\n\nThis won't take advantage of the fact that your file is already sorted, but it is the most efficient way anyway. To look up a word w, you can use\nw in words\n\nwhich is amortised O...
[ 5, 1 ]
[]
[]
[ "list", "performance", "python", "search", "spell_checking" ]
stackoverflow_0005871111_list_performance_python_search_spell_checking.txt
Q: Python list and type error I've code this code in Python: if type(data).__name__=='list': print type(data).__name__ print ",".join(data) And it give me this error: print ",".join(data) exceptions.TypeError: sequence item 0: expected string, list found How's that possible?!? Th...
Python list and type error
I've code this code in Python: if type(data).__name__=='list': print type(data).__name__ print ",".join(data) And it give me this error: print ",".join(data) exceptions.TypeError: sequence item 0: expected string, list found How's that possible?!? Thanks in advance for anyhelp.
[ "You appear to have a list of lists. Try:\n\",\".join(str(x) for x in data)\n\n", "str.join() can only join a sequence of strings. Obviously your list contains an item that itself is a list again.\nFurthermore, if you really need to check for the type of an object, a better way to do it is\nif isinstance(data, l...
[ 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "exception", "list", "python", "types" ]
stackoverflow_0005871041_exception_list_python_types.txt
Q: Python Mail Converts Random Characters to '=' I am writing an email application using PyGTK. In almost every message that I am receiving from the server, random characters are replaced by '=' symbols. It's something to do with the character encoding, but I can't figure out what the problem is. Can anyone help? A:...
Python Mail Converts Random Characters to '='
I am writing an email application using PyGTK. In almost every message that I am receiving from the server, random characters are replaced by '=' symbols. It's something to do with the character encoding, but I can't figure out what the problem is. Can anyone help?
[ "I figured it out. When I run get_payload, I have to set decode to True.\nfor mailpart in mailitem.walk():\n if mailpart.get_content_maintype() == 'multipart':\n continue\n message = str(mailpart.get_payload(decode=True))\n\n" ]
[ 1 ]
[]
[]
[ "encoding", "gtk", "imap", "python", "webkit" ]
stackoverflow_0005863396_encoding_gtk_imap_python_webkit.txt
Q: Calling python script from awk most of the solutions out there call awk from python. But i want to do it the other way round. I have a python script that extracts information from a file. However said filename is referenced in a column of the awk script. How do i pass python the argument "%s20s", filename and get...
Calling python script from awk
most of the solutions out there call awk from python. But i want to do it the other way round. I have a python script that extracts information from a file. However said filename is referenced in a column of the awk script. How do i pass python the argument "%s20s", filename and get the input from the standard output?...
[ "You can call external commands using the system function. Does that solve your problem?\n$ awk 'BEGIN { system(\"echo something\") }'\nsomething\n\nBut that only provides the return code. If you need to capture stdin you can do this:\n$ awk 'BEGIN { \"echo something\" | getline; print \"output: \"$0 }'\noutput: so...
[ 3, 3 ]
[]
[]
[ "awk", "python", "shell" ]
stackoverflow_0005870215_awk_python_shell.txt
Q: python list comprehension VS for behaviour EDIT: stupid logic of mine got ahead of me. The none are just the returns from the comprehension call. Ok, I'm running some tests in python, and I ran into a bit of a difference in execution orders, which leads me to an understanding of how it is implemented, but I'd like...
python list comprehension VS for behaviour
EDIT: stupid logic of mine got ahead of me. The none are just the returns from the comprehension call. Ok, I'm running some tests in python, and I ran into a bit of a difference in execution orders, which leads me to an understanding of how it is implemented, but I'd like to run it by you fine people to see if I'm righ...
[ "Your test function has no return statement, thus using it in a list comprehension results in a list of Nones. The interactive python prompt prints out whatever the last statement returns.\nExample:\n>>> def noop(x): pass\n... \n>>> [noop(i) for i in range(5)]\n[None, None, None, None, None]\n\nSo really there's no...
[ 4, 1, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0005871256_list_comprehension_python.txt
Q: How does selenium 2 (webdriver) implement WebElement The scenario I'm considering is basic: page = driver.open_page(URL) linkElement = page.find_elements(XPATH)[0] linkElement.click() (I'm assuming I'm using a remote machine - i.e., remote driver). How does the server know on which element to click. More general...
How does selenium 2 (webdriver) implement WebElement
The scenario I'm considering is basic: page = driver.open_page(URL) linkElement = page.find_elements(XPATH)[0] linkElement.click() (I'm assuming I'm using a remote machine - i.e., remote driver). How does the server know on which element to click. More generally, I couldn't find an overview of the selenium 2 implemen...
[ "You're right, there isn't a good one-size-fits-all \"under-the-covers\" look at how WebDriver implements the various parts of its API, largely because the actual implementation can be very different depending on the browser and the operating system. The closest you'll come is the various pages on the project wiki....
[ 5, 0 ]
[]
[]
[ "implementation", "python", "selenium", "selenium_webdriver", "webdriver" ]
stackoverflow_0005842135_implementation_python_selenium_selenium_webdriver_webdriver.txt
Q: Advanced library and API design I am developing a library that uses CMIS compatible storage as back-end (in my case Alfresco). I would very much like to create a "sexy" API similar to that of Flask-SQLAlchemy and Django. The problem is that I am new to such advanced programming in Python. Here is the imagined way ...
Advanced library and API design
I am developing a library that uses CMIS compatible storage as back-end (in my case Alfresco). I would very much like to create a "sexy" API similar to that of Flask-SQLAlchemy and Django. The problem is that I am new to such advanced programming in Python. Here is the imagined way of using this library: # Here is the ...
[ "Have you taken a look at cmislib? It's a client-side API for CMIS written in Python. It allows you to work with objects in Alfresco (or any other CMIS-compliant repository).\nThe API gives you objects like \"Document\" and \"Folder\". I think you'd have to write some Django middleware to do the model stuff you are...
[ 2 ]
[]
[]
[ "api", "cmis", "python" ]
stackoverflow_0005859390_api_cmis_python.txt
Q: Algorithm to generate pseudorandom numbers serie, reproducible knowing initial seed I have to write a lightweight algorithm to generate pseudorandom infinite numbers series, and strongly dependant by initial seed. In python it should be like seed = 3345 // Common number generator = numgen(seed) whi...
Algorithm to generate pseudorandom numbers serie, reproducible knowing initial seed
I have to write a lightweight algorithm to generate pseudorandom infinite numbers series, and strongly dependant by initial seed. In python it should be like seed = 3345 // Common number generator = numgen(seed) while True: generator.getNext() // With the same seed it produce same numbers As I ...
[ "With the given requirements, you can go for the constant series\ngenerator = itertools.repeat(seed)\n\nThis is\n\nlightweight\nnot necessarily random\nstrongly dependant on the initial seed\nproduces the same series even on a different machine\n\nEdit: To make this an actual answer, here is how to use Python's Mer...
[ 9 ]
[]
[]
[ "algorithm", "generator", "numbers", "python", "series" ]
stackoverflow_0005871452_algorithm_generator_numbers_python_series.txt
Q: Re-binding "select all" in Text widget I'm working with the Text widget and I have an issue about old-school shortcuts that Tk uses. Ie: Select all: Ctrl + / vs Ctrl + a Cut: Ctrl + w vs Ctrl + x Copy: Meta + w vs Ctrl + c Paste: Ctrl + y vs Ctrl + v On Windows, all of them work except Ctrl+a. 1) Is it possible to...
Re-binding "select all" in Text widget
I'm working with the Text widget and I have an issue about old-school shortcuts that Tk uses. Ie: Select all: Ctrl + / vs Ctrl + a Cut: Ctrl + w vs Ctrl + x Copy: Meta + w vs Ctrl + c Paste: Ctrl + y vs Ctrl + v On Windows, all of them work except Ctrl+a. 1) Is it possible to redirect binds, so .bind('<Control-a>') cal...
[ "The default bindings are applied to the widget class. When you do a bind, it affects a specific widget and that binding happens before the class binding. So what is happening is that your binding is happening and then the class binding is happening, which makes it seem as if your binding isn't working.\nThere are ...
[ 15, 4 ]
[]
[]
[ "python", "tk_toolkit", "tkinter", "widget" ]
stackoverflow_0005870561_python_tk_toolkit_tkinter_widget.txt
Q: Selenium-rc Python client : Not able to iterate through the xpath? I am a newbie to Selenium and is implementing selenium-rc with Python client library. I tried traversing through my page's div using xpath(s) elements using the command "sel.get_xpath_count(xpath)". It gives a count of 20, but when I iterate throug...
Selenium-rc Python client : Not able to iterate through the xpath?
I am a newbie to Selenium and is implementing selenium-rc with Python client library. I tried traversing through my page's div using xpath(s) elements using the command "sel.get_xpath_count(xpath)". It gives a count of 20, but when I iterate through every div using for statement and command "sel.get_text(xpath='%s[%d]'...
[ "Your second XPath expression is wrong. Programmers trained in C-style languages frequently make this mistake, because they see [...] and think \"index into an array\", but that's not what brackets do in XPath.\nIf you use sel.get_xpath_count(something), then you need to use sel.get_text(\"xpath=(something)[item_n...
[ 2 ]
[]
[]
[ "python", "selenium_rc" ]
stackoverflow_0005866496_python_selenium_rc.txt
Q: How to select 30 unique random values from database(MySQL) with django? I've read this question: In Django, how do I select 100 random records from the database? And tried to use Content.objects.all().order_by('?')[:30], but this will produce some duplicate items. So how could I select 30 unique random values from...
How to select 30 unique random values from database(MySQL) with django?
I've read this question: In Django, how do I select 100 random records from the database? And tried to use Content.objects.all().order_by('?')[:30], but this will produce some duplicate items. So how could I select 30 unique random values from database?
[ "If you have a manageable number of entries in the database (ie not thousands), this will work, and even though it hits the db twice it will probably be much more efficient than order_by('?').\nimport random\ncontent_pks = Content.objects.values_list('pk', flat=True)\nselected_pks = random.sample(content_pks, 30)\n...
[ 2 ]
[]
[]
[ "database", "django", "django_database", "mysql", "python" ]
stackoverflow_0005871788_database_django_django_database_mysql_python.txt
Q: ways to detect data redundancy between tables with different structures I'm working on a problem that involves multiple database instances, each with different table structures. The problem is, between these tables, there are lots and lots of duplicates, and i need a way to efficiently find them, report them, and ...
ways to detect data redundancy between tables with different structures
I'm working on a problem that involves multiple database instances, each with different table structures. The problem is, between these tables, there are lots and lots of duplicates, and i need a way to efficiently find them, report them, and possibly eliminate them. Eg. I have two tables, the first table, CustomerData...
[ "If I couldn't care for performance, I'd use a high-level practical approach. Use Django (or SQLAlchemy or...) to build your desired models (your tables) and fetch the data to compare. Then use an algorithm for efficiently identifying duplicates (...from lists or dicts,it depends of \"how\" you hold your data). To ...
[ 0 ]
[]
[]
[ "database", "duplicate_data", "mysql", "python", "redundancy" ]
stackoverflow_0005865775_database_duplicate_data_mysql_python_redundancy.txt
Q: How to populate a table while creating the Django model? I have a list of cities (simple cvs file) and I want to populate the citeis table while creating the City model. Class description: class City(models.Model): city = modeld.CharField('city_name', max_length=50) class Meta: berbuse_name =.... ...
How to populate a table while creating the Django model?
I have a list of cities (simple cvs file) and I want to populate the citeis table while creating the City model. Class description: class City(models.Model): city = modeld.CharField('city_name', max_length=50) class Meta: berbuse_name =.... ........... def __unicode__(self): return...
[ "We do something like this, usually.\nimport csv\nfrom my_django_app.forms import CityForm\nwith open( \"my file\", \"rb\" ) as source:\n rdr = csv.DictReader( source )\n for row in rdr:\n form= CityForm( **row )\n if form.is_valid(): \n form.save()\n else:\n print f...
[ 5, 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005871621_django_django_models_python.txt
Q: Django UnicodeEncodeError on QuerySet extra to PostgreSQL if started from shell Hello all I'm using Django 1.2.5 with Python 2.6 on two machines: Ubuntu 11.04 and Debian Lenny. First one is my local dev and second is remote server. I'm using django-fts and postgresql (database is remote and unique for both install...
Django UnicodeEncodeError on QuerySet extra to PostgreSQL if started from shell
Hello all I'm using Django 1.2.5 with Python 2.6 on two machines: Ubuntu 11.04 and Debian Lenny. First one is my local dev and second is remote server. I'm using django-fts and postgresql (database is remote and unique for both installations) to make full text search queries. The intriguing thing is I can do fts query ...
[ "add a u'' to all the string in your example.\nlike u'ts_rank(%s.%s, %s, %d)' % (...)\nand also interpolating variables with % without database escape is bad. \n" ]
[ 1 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0005867614_django_postgresql_python.txt
Q: How do I get a python regular expression to return all text not matching? So, I am successfully matching and extracting some special tagged text using the following regular expression: theString = u"Var 1 value: %%v:123453%%, Var 2 value: %%v:984561%%, Var 3 value: %%v:123456%%" p = re.compile("\%%v:([0-9]*)%%") t...
How do I get a python regular expression to return all text not matching?
So, I am successfully matching and extracting some special tagged text using the following regular expression: theString = u"Var 1 value: %%v:123453%%, Var 2 value: %%v:984561%%, Var 3 value: %%v:123456%%" p = re.compile("\%%v:([0-9]*)%%") theIds = p.findall(theString) That returns [u'123453', u'984561', u'123456'] ...
[ "How about the following?\ntheString = u\"Var 1 value: %%v:123453%%, Var 2 value: %%v:984561%%, Var 3 value: %%v:123456%%\"\np = re.compile(\"\\%%v:([0-9]*)%%\")\nreplacements = [\"Some Value\", \"837\", \"more stuff\"]\nnewString = p.sub(lambda m: replacements.pop(0), theString)\n\nYou can provide a function to re...
[ 2, 2, 0, 0 ]
[]
[]
[ "python", "regex", "replace" ]
stackoverflow_0005872299_python_regex_replace.txt
Q: django forms with jquery well ive been searching for the past 3 hours and I cant seem to find a good tutorial on this ... i`m looking for a tutorial on how to make a form "wizard" with jquery and django (I dont know javascript only basics) I need a 3 step wizard ... first step 2 inputs user password if user a...
django forms with jquery
well ive been searching for the past 3 hours and I cant seem to find a good tutorial on this ... i`m looking for a tutorial on how to make a form "wizard" with jquery and django (I dont know javascript only basics) I need a 3 step wizard ... first step 2 inputs user password if user and password are in db then sho...
[ "If you're using Javascript then the \"step\" process will be faked, basically hiding/showing/validating fields when a user clicks a button, but it will all be in one view. Take a look at the answers to this question for help on building that. This looks like a pretty good tutorial on the topic as well. You won't b...
[ 1 ]
[]
[]
[ "ajax", "django", "forms", "jquery", "python" ]
stackoverflow_0003570660_ajax_django_forms_jquery_python.txt
Q: Numpy: creating a symmetric matrix class based on this answer I was coding a simple class for symmetric matrices in python with numpy, but I'm having (probably a very simple) problem. This is the problematic code: import numpy as np class SyMatrix(np.ndarray): def __init__(self, arr): self = (arr + a...
Numpy: creating a symmetric matrix class
based on this answer I was coding a simple class for symmetric matrices in python with numpy, but I'm having (probably a very simple) problem. This is the problematic code: import numpy as np class SyMatrix(np.ndarray): def __init__(self, arr): self = (arr + arr.T)/2.0 - np.diag(np.diag(arr)) def __s...
[ "There are a few issues here.\n\nWhen subclassing numpy.ndarray(), you should overwrite __new__(), not __init__(). Your line\nfoo = SyMatrix(2)\n\nactually calls numpy.ndarray.__new__() with the parameter 2, incompatible with its signature.\nAssigning to self does absolutely nothing here. It just creates an objec...
[ 3 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0005872235_arrays_numpy_python.txt
Q: Generating json in python for app engine I am somewhat new to python and I am wondering what the best way is to generate json in a loop. I could just mash a bunch of strings together in the loop, but I'm sure there is a better way. Here's some more specifics. I am using app engine in python to create a service tha...
Generating json in python for app engine
I am somewhat new to python and I am wondering what the best way is to generate json in a loop. I could just mash a bunch of strings together in the loop, but I'm sure there is a better way. Here's some more specifics. I am using app engine in python to create a service that returns json as a response. So as an example...
[ "Creating your own JSON is silly. Use json or simplejson for this instead.\n>>> json.dumps(dict(foo=42))\n'{\"foo\": 42}'\n\n", "\nMy question is how do I add to the\n dictionary dynamically? So foreach\n record in my list of records, add a\n record to the dictionary.\n\nYou may be looking to create a list of ...
[ 18, 7, 4 ]
[]
[]
[ "google_app_engine", "json", "python" ]
stackoverflow_0005872144_google_app_engine_json_python.txt
Q: Setting correct permissions on generated zip-file in Django I'm using Django and Python2.6 to generate a zip file of custom-rendered Django templates for each user to download a custom-made zip file. At the moment, the code in views.py looks like this: def download(request): response = HttpResponse(mimetype='a...
Setting correct permissions on generated zip-file in Django
I'm using Django and Python2.6 to generate a zip file of custom-rendered Django templates for each user to download a custom-made zip file. At the moment, the code in views.py looks like this: def download(request): response = HttpResponse(mimetype='application/x-zip-compressed') response['Content-Disposition']...
[ "I think this is an issue with whatever you are using to extract the zip. The permissions seem fine to me:\nzk@fool:~/Downloads% ls -l | grep thefile\n-rwxr-xr-x@ 1 zk staff 9 May 3 06:37 thefile.txt*\n\nWorks fine for me with Archive Utility on osx and window's built-in zip explorer and 7-zip. Inspect...
[ 4, 0 ]
[]
[]
[ "django", "permissions", "python", "zip" ]
stackoverflow_0005848061_django_permissions_python_zip.txt
Q: How can I convert a TypedObject to a nested dictionary in Python? I am using pyAMF and I do receive a TypedObject that is in fact a nested dictionary. I want to convert this to a python dictionary. A: You should be able to wrap it in dict(obj) or call obj.copy() to convert it: >>> type(o) <class 'pyamf.TypedObj...
How can I convert a TypedObject to a nested dictionary in Python?
I am using pyAMF and I do receive a TypedObject that is in fact a nested dictionary. I want to convert this to a python dictionary.
[ "You should be able to wrap it in dict(obj) or call obj.copy() to convert it:\n>>> type(o)\n<class 'pyamf.TypedObject'>\n>>> type(o.copy())\n<type 'dict'>\n>>> o.copy()\n{'abc': 123}\n\n" ]
[ 1 ]
[]
[]
[ "dictionary", "pyamf", "python" ]
stackoverflow_0005872295_dictionary_pyamf_python.txt
Q: Deploying an app to users' appspot I am working on a Python App, which runs on App Engine. Is there a way I can publish the app on each customers' appSpot account, so that the App uses the users' cloud storage? Instead of running the App on my AppSpot account and all the users storing the data on my Cloud space? ...
Deploying an app to users' appspot
I am working on a Python App, which runs on App Engine. Is there a way I can publish the app on each customers' appSpot account, so that the App uses the users' cloud storage? Instead of running the App on my AppSpot account and all the users storing the data on my Cloud space?
[ "No, you cannot do that. The app is hosted and run in the administrator's account which would be you. What you can do is, release the source code and point your users do install it in their appspot account, just like creating a new application.\n", "Yes, absolutely.\nYou just need to have each client create an Ap...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005865349_google_app_engine_python.txt
Q: iPython: unicode in gnome-terminal (linux) Why is this happening in the gnome-terminal? I think it supports utf8, printing unicode shouldn't be a problem. Also, I have these in the .bashrc LANG="en_US.utf8" LANGUAGE="en_US.utf8" LC_ALL="en_US.utf8" export LANG export LANGUAGE export LC_ALL Update: Versions Pyth...
iPython: unicode in gnome-terminal (linux)
Why is this happening in the gnome-terminal? I think it supports utf8, printing unicode shouldn't be a problem. Also, I have these in the .bashrc LANG="en_US.utf8" LANGUAGE="en_US.utf8" LC_ALL="en_US.utf8" export LANG export LANGUAGE export LC_ALL Update: Versions Python 2.7.1, IPython 0.10.1, Disto: Ubuntu 11.04
[ "IPython 0.10 has a serious bug with Unicode. It's fixed in the development version, which will become 0.11, and we're hopefully releasing that in the next couple of weeks. If you're happy running a development version, you can get it here.\n" ]
[ 3 ]
[]
[]
[ "ipython", "linux", "python", "unicode" ]
stackoverflow_0005860713_ipython_linux_python_unicode.txt
Q: Django logging features? I need to run a lot of Django management commands in the crontab and want to log the output of each run to a special timestamped file. Is there a Django or Python module to help me do this or do I just have to roll my own? A: You can use the Python logging package which is part of Pytho...
Django logging features?
I need to run a lot of Django management commands in the crontab and want to log the output of each run to a special timestamped file. Is there a Django or Python module to help me do this or do I just have to roll my own?
[ "You can use the Python logging package which is part of Python, see my answer to another question about elegant setup of logging in Django. You can inspect sys.argv to determine how you want to do logging, e.g. redirect to different files for different commands.\n", "Have a look at django-jogging. It's a breeze ...
[ 3, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002567046_django_python.txt
Q: twistd in Twisted cant be run in window in command prompt i type >>twistd echobot.tac Traceback (most recent call last): File "C:\Python26\Scripts\twistd.py", line 18, in ? from twisted.scripts.twistd import run ImportError: No module named twisted.scripts.twistd the twistd is at C:\Python26\Scripts\twistd.py...
twistd in Twisted cant be run in window
in command prompt i type >>twistd echobot.tac Traceback (most recent call last): File "C:\Python26\Scripts\twistd.py", line 18, in ? from twisted.scripts.twistd import run ImportError: No module named twisted.scripts.twistd the twistd is at C:\Python26\Scripts\twistd.py #!c:\python26\python.exe # Copyright (c) 20...
[ "Try setting path.. something like this in cmd: \nset PYTHONPATH=%PYTHONPATH%;C:\\My_python_lib \n\nand then run twistd\n" ]
[ 2 ]
[]
[]
[ "python", "twisted", "window", "xmpp" ]
stackoverflow_0003450806_python_twisted_window_xmpp.txt
Q: RDFlib 'on disk' store After 2 days of research I (a newby) still can't figure out what 'on disk' stores are available in RDFFlib 3.1.0. If you have a working example, that would be nice to see... For my app I prefer SQLite. I need no access to online RDF stores, I want to store info about relations inside the org...
RDFlib 'on disk' store
After 2 days of research I (a newby) still can't figure out what 'on disk' stores are available in RDFFlib 3.1.0. If you have a working example, that would be nice to see... For my app I prefer SQLite. I need no access to online RDF stores, I want to store info about relations inside the organisation in RDF. Thanks
[ "Here you have an example to make it work with MySQL. I don't think rdflib 3 works with SQLite. \n import rdflib\n from rdflib.Graph import ConjunctiveGraph as Graph\n from rdflib import plugin\n from rdflib.store import Store, NO_STORE, VALID_STORE\n\n configString = \"host=localhost,user=root,passw...
[ 2 ]
[]
[]
[ "python", "rdf", "rdflib" ]
stackoverflow_0005868364_python_rdf_rdflib.txt
Q: Writing the results of a search from a for loop to a file only give one line (one result) I'm not understanding why I'm only getting the first match of word and ln in a logfile that I'm writing to in a loop (there are 50 or more matches). And and it's not well structured like when I print to the screen. Below is t...
Writing the results of a search from a for loop to a file only give one line (one result)
I'm not understanding why I'm only getting the first match of word and ln in a logfile that I'm writing to in a loop (there are 50 or more matches). And and it's not well structured like when I print to the screen. Below is the code. Thanks! Results in file that I'm writing: 343438363939 70642 regex = re.compile(r'(?:3...
[ "This is your problem:\n logfile = open('result3.log', 'w')\n logfile.write(word + '\\n' + ln)\n logfile.close()\n\nEvery time you open the log file like this, it erases everything that was in it before and\nstarts writing from the beginning of the file. You can eith...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005872857_python.txt
Q: AppEngine social application I started developing my application in AppEngine Java, however I noticed that Facebook has officially discontinued the support for the Java API and the third party API was last updated a year ago. Does anybody use Java + Social plugins? How has it been going so far? Should I switch to ...
AppEngine social application
I started developing my application in AppEngine Java, however I noticed that Facebook has officially discontinued the support for the Java API and the third party API was last updated a year ago. Does anybody use Java + Social plugins? How has it been going so far? Should I switch to Python, I'd not want to since, I'm...
[ "I have been using facebook-java-api on Google App Engine for a year now. It does almost all I need it to do (get friends list, get photos, upload photos). It uses the old REST api but I have not seen a deprecation date for the methods I use.\nI also use Apache HTTP Client to do some Graph API calls not available i...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "java", "python" ]
stackoverflow_0004578729_google_app_engine_java_python.txt
Q: Broken bar/coumn chart in matplotlib? Is there a way, in matplotlib, to plot a broken bar/column chart. The case I seek has one bar that is on a larger scale than the others. An example from Excel looks like this: example I have looked in the Matplotlib gallery and documentation and found broken bar methods, but t...
Broken bar/coumn chart in matplotlib?
Is there a way, in matplotlib, to plot a broken bar/column chart. The case I seek has one bar that is on a larger scale than the others. An example from Excel looks like this: example I have looked in the Matplotlib gallery and documentation and found broken bar methods, but they are not quite the same.
[ "Two methods for making a discontinuous axis for a line plot are laid out here. It should be essentially the same process (in either case) for a bar graph. Please leave a comment if either method does not work.\n" ]
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005873106_matplotlib_python.txt
Q: How to calculate the axis of orientation? Previously, I calculated the axis of orientation based on anatomical structures, such as the toes in a paw. But I found that this doesn't work when I can't distinguish between the toes very well or if the 'heel' (blue square) is way off. So I decided to look for better al...
How to calculate the axis of orientation?
Previously, I calculated the axis of orientation based on anatomical structures, such as the toes in a paw. But I found that this doesn't work when I can't distinguish between the toes very well or if the 'heel' (blue square) is way off. So I decided to look for better alternatives and I decided to try and calculate t...
[ "Well, here's an implementation doing the same thing as your code above (and rotating the image by the relevant angle).\nHowever, in the case of your paws, I'm not sure it's going to work as well as it does for a human foot. \nFirst off, for a dog's paw, the \"long\" axis defined this way is along the breadth of t...
[ 8 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0005869891_image_processing_python.txt
Q: Python - Run a bash script for all files in a directory I am creating a Python script to act as a wrapper for some common image-related tasks that I have to do, and here's a part where I am stuck at: There is a Bash script someone wrote for ImageMagick which is located here: http://www.fmwconcepts.com/imagemagick...
Python - Run a bash script for all files in a directory
I am creating a Python script to act as a wrapper for some common image-related tasks that I have to do, and here's a part where I am stuck at: There is a Bash script someone wrote for ImageMagick which is located here: http://www.fmwconcepts.com/imagemagick/autocolor/index.php Essentially, it can only operate on a si...
[ "Here are some ideas:\nfrom glob import glob\nimport subprocess\n\nelif RetouchOption == \"04\":\n ColorMethod = input(\"What method will you use (options are gamma, recolor, none)?: \")\n ClipMode = input(\"What clipping mode will you use (options are together or separate)?: \")\n script = [\"sh\", \"~/au...
[ 1, 1, 0, 0 ]
[ "Have you considered using os.listdir to get all the files in the directory?\nOnce you have a listing of all files in the directory, you can pull out all the JPGs and use the following code to to remove the \".jpg\" from the end of the filename:\n>>> f = 'firstPic.jpg'\n>>> f. replace(\".jpg\", '')\n'firstPic'\n\nH...
[ -1, -1 ]
[ "bash", "filenames", "python" ]
stackoverflow_0005873133_bash_filenames_python.txt
Q: How can I disable web security in selenium through Python? Apparently it's common for google-chrome to get this: http://jira.openqa.org/browse/SRC-740 The key is to start it without security enabled. To disable security, "--disable-web-security", I'm having trouble wondering how to actually specify these command ...
How can I disable web security in selenium through Python?
Apparently it's common for google-chrome to get this: http://jira.openqa.org/browse/SRC-740 The key is to start it without security enabled. To disable security, "--disable-web-security", I'm having trouble wondering how to actually specify these command line arguments, though, so it fails on the open invocation here:...
[ "To get this to work, I had to create an external script to wrap the chrome browser. Place a script somewhere your Selenium server can reach it (mine is at ~/bin/startchrome, and chmod it executable:\n#!/bin/sh\n# chrome expects to be run from the .app dir, so cd into it\n# (the spaces in the path are a Mac thing)...
[ 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0005862210_python_selenium.txt
Q: How to set timezone in python using os.environ example: os.environ['TZ'] = "CST+06CDT,M4.1.0,M10.5.0" I can understand CST, 06 (offset from UTC ?? or GMT) , CDT == Central Daylight Saving Time but What do M4.1.0 and M10.5.0 mean ? Here is what i found: export TZ=EST05EDT EST was taken from the chart below. Fiv...
How to set timezone in python using os.environ
example: os.environ['TZ'] = "CST+06CDT,M4.1.0,M10.5.0" I can understand CST, 06 (offset from UTC ?? or GMT) , CDT == Central Daylight Saving Time but What do M4.1.0 and M10.5.0 mean ? Here is what i found: export TZ=EST05EDT EST was taken from the chart below. Five hours has to be added to get UTC, hence the 05. An...
[ "From the python manual:\n\nThe standard format of the TZ\n environment variable is (whitespace\n added for clarity):\nstd offset [dst [offset\n [,start[/time], end[/time]]]]\nMm.n.d The d‘th day (0 <= d <= 6) or\n week n of month m of the year (1 <= n\n <= 5, 1 <= m <= 12, where week 5 means\n “the last d da...
[ 2 ]
[]
[]
[ "datetime", "python", "timezone" ]
stackoverflow_0005873857_datetime_python_timezone.txt
Q: Why different behaviors between running Python module as an executable vs. Python [filename] So, I created a simple python module, test.py import commands def main(): cmd = 'ls -l' (status, output) = commands.getstatusoutput(cmd) print status, output if __name__ == '__main__': main() When I ran it using...
Why different behaviors between running Python module as an executable vs. Python [filename]
So, I created a simple python module, test.py import commands def main(): cmd = 'ls -l' (status, output) = commands.getstatusoutput(cmd) print status, output if __name__ == '__main__': main() When I ran it using "Python test.py", I got the result that I expected. But when I ran it as an executable (yes, it h...
[ "Add a hash-bang line to the top:\n#!/usr/bin/env python\n\nimport commands\n...\n\nThis tells your system what interpreter to use to execute the script. Without it it doesn't know if it's a shell script, Perl script, Python script, what.\n", "You need the hashbang to be the first line of your script, referencing...
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005874144_python.txt
Q: Error in starting apache2 server while configuring for python Hello i'm trying to configure apache2 server for python, i used this command to install apache2: sudo apt-get install apache2 cd /etc/apache2/mods-enabled/ sudo ln -s ../mods-available/mod_python.load mod_python.load cd /etc/apache2/sites-available/ su...
Error in starting apache2 server while configuring for python
Hello i'm trying to configure apache2 server for python, i used this command to install apache2: sudo apt-get install apache2 cd /etc/apache2/mods-enabled/ sudo ln -s ../mods-available/mod_python.load mod_python.load cd /etc/apache2/sites-available/ sudo gedit default edited the default file to: <Directory /var/www/>...
[ "It looks like there is a space between the leading / and the rest of the path to the module. Is there? If so, remove the space and try again...\n" ]
[ 3 ]
[]
[]
[ "apache2", "mod_python", "python" ]
stackoverflow_0005873534_apache2_mod_python_python.txt
Q: How can I scrape data from a text table using Python? I have the following text and I would like to scrape the data items and save them in excel. Is there a way to do this in Python? text = """ ANNUAL COMPENSATION LONG-TERM COMPENSATION ...
How can I scrape data from a text table using Python?
I have the following text and I would like to scrape the data items and save them in excel. Is there a way to do this in Python? text = """ ANNUAL COMPENSATION LONG-TERM COMPENSATION --------------------------------------- ---------...
[ "Here is some code to get you started:\ntext = \"\"\"JOHN ...\"\"\" # text without the header\n\n# These can be inferred if necessary\ncols = [0, 24, 29, 39, 43, 52, 71, 84, 95, 109, 117]\n\ndb = []\nrow = []\nfor line in text.strip().split(\"\\n\"):\n data = [line[cols[i]:cols[i+1]] for i in xrange((len(cols)-1...
[ 3, 2, 1 ]
[]
[]
[ "python", "scrape" ]
stackoverflow_0005873969_python_scrape.txt
Q: Call method from top class in hierarchy instead of override Let's say I have classes Base(object) and Derived(Base). These both implement a function foo, with Derived.foo overriding the version in Base. However, in one of the methods, say Base.learn_to_foo, I want to call Base.foo instead of the derived version re...
Call method from top class in hierarchy instead of override
Let's say I have classes Base(object) and Derived(Base). These both implement a function foo, with Derived.foo overriding the version in Base. However, in one of the methods, say Base.learn_to_foo, I want to call Base.foo instead of the derived version regardless of whether it was overridden. So, I call Base.foo(self) ...
[ "The answer is NOT to use the super() function. The way you are doing is exactly right as you don't want to invoke the virtual method that is overridden in the super class. Since you seem to want the base class' exact implementation all the time, the only way is to get the base class' unbound method object back, bo...
[ 3, 2, 1 ]
[]
[]
[ "inheritance", "oop", "python" ]
stackoverflow_0005871542_inheritance_oop_python.txt
Q: Is there a native HTML parsing module for Python 3.2? I am trying to parse some html. I would like something like sgmllib but it is deprecated in python 3.2. Is there an alternate module that I can use? Thanks. A: Built-in HTMLParser module: http://docs.python.org/py3k/library/html.parser.html Not native but w...
Is there a native HTML parsing module for Python 3.2?
I am trying to parse some html. I would like something like sgmllib but it is deprecated in python 3.2. Is there an alternate module that I can use? Thanks.
[ "Built-in HTMLParser module:\nhttp://docs.python.org/py3k/library/html.parser.html\nNot native but worth to mention;\nBeautifulSoup:\nhttp://www.crummy.com/software/BeautifulSoup/\n", "Not sure what you mean by native, but I'm a big fan of lxml.\n" ]
[ 8, 4 ]
[]
[]
[ "html", "python", "python_3.x" ]
stackoverflow_0005874648_html_python_python_3.x.txt
Q: Indexing 20M of records with python and mongoDB I would like to mention about my little project, and if I'm on track. I need work with all articles from Medline (http://www.nlm.nih.gov/bsd/licensee/2011_stats/baseline_doc.html). For those are not familiar with Medline database, I add a little information: There a...
Indexing 20M of records with python and mongoDB
I would like to mention about my little project, and if I'm on track. I need work with all articles from Medline (http://www.nlm.nih.gov/bsd/licensee/2011_stats/baseline_doc.html). For those are not familiar with Medline database, I add a little information: There are approx. 20.000.000 of records (83.4 GB disk space)...
[ "\nIs it a good idea? (XML parsing --> JSON --> insert and indexing!)\n\nDoes it work? JSON tends to be smaller than XML, this is probably a good change.\n\nCan I use GridFS and get chunks equivalents to records for each file? How?\n\nGridFS is generally for storing static files like images or video. MongoDB can su...
[ 2 ]
[]
[]
[ "gridfs", "mongodb", "pymongo", "python" ]
stackoverflow_0005869130_gridfs_mongodb_pymongo_python.txt
Q: Python parsing list of string I have list of strings, I'm looking for lines like this: Key: af12d9 Index: 0 Field 1: 1234 Field 2: 1234 Field 3: -10 after finding lines like this, I want to store each one as a dictionary {'key' : af12d9, 'index' : 0, 'field 1' : .... }, then store this dictionary to a list, so I w...
Python parsing list of string
I have list of strings, I'm looking for lines like this: Key: af12d9 Index: 0 Field 1: 1234 Field 2: 1234 Field 3: -10 after finding lines like this, I want to store each one as a dictionary {'key' : af12d9, 'index' : 0, 'field 1' : .... }, then store this dictionary to a list, so I will have a list of dictionaries. I...
[ "Firstly, your regex seems to not work properly. The Key field should have values which could include f, right? So its group should not be ([0-9A-Ea-e]+) but instead ([0-9A-Fa-f]+). Also, it is a good - actually, a wonderful - practice to prefix the regex string with r when dealing with regexes because it avoids p...
[ 5, 1, 0, 0, 0, 0 ]
[]
[]
[ "parsing", "python", "regex", "search" ]
stackoverflow_0005653118_parsing_python_regex_search.txt
Q: error on importing wmi hi when I import wmi module I got this error Traceback (most recent call last): File "", line 1, in import wmi File "C:\Python26\lib\site-packages\wmi.py", line 88, in from win32com.client import GetObject, Dispatch File "C:\Python26\Lib\site-packages\win32com__ini...
error on importing wmi
hi when I import wmi module I got this error Traceback (most recent call last): File "", line 1, in import wmi File "C:\Python26\lib\site-packages\wmi.py", line 88, in from win32com.client import GetObject, Dispatch File "C:\Python26\Lib\site-packages\win32com__init__.py", line 5, in ...
[ "This thread seems relevant:\nhttp://old.nabble.com/Problems-importing-win32com-td24988589.html\nDid you install Python as administrator?\n" ]
[ 0 ]
[]
[]
[ "import", "python", "wmi" ]
stackoverflow_0005874312_import_python_wmi.txt
Q: python usage of lambda to define a __builtin__ - but why? I stumbled upon this python: __builtin__.__dict__['N_'] = lambda x: x class X: doc = N_('some doc for class X') I know conceptually what this does, but what I don't know is why? More precisely, what is the difference between that code and this: class ...
python usage of lambda to define a __builtin__ - but why?
I stumbled upon this python: __builtin__.__dict__['N_'] = lambda x: x class X: doc = N_('some doc for class X') I know conceptually what this does, but what I don't know is why? More precisely, what is the difference between that code and this: class X: doc = 'some doc for class X'
[ "Looks to me like the N_ function needs to be defined (it's probably supposed to look up translations), so he's creating it at the start of the process for anything else that happens in that process.\nI'd assume that another piece of code, perhaps the code for non-English localisation, can replace the N_ function w...
[ 6, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005874965_python.txt
Q: avoiding code duplication in Python code redux This is a followup to an earlier question. I got some good suggestions for that, so I thought I would try my luck again. from itertools import takewhile if K is None: illuminacond = lambda x: x.split(',')[0] != '[Controls]' else: illuminacond = lambda x: x.s...
avoiding code duplication in Python code redux
This is a followup to an earlier question. I got some good suggestions for that, so I thought I would try my luck again. from itertools import takewhile if K is None: illuminacond = lambda x: x.split(',')[0] != '[Controls]' else: illuminacond = lambda x: x.split(',')[0] != '[Controls]' and i < K af=open('a')...
[ "Why not use only one loop, but including the condition inside that loop? Also, you can get rid of the redundancy in that lambda, I think.\nfrom itertools import takewhile\n\nk_is_none = K is None\n\ndef illuminacond(x):\n global i\n global K\n result = x.split(',')[0] != '[Controls]'\n if not k_is_none...
[ 3, 2, 1, 1 ]
[]
[]
[ "code_duplication", "control_flow", "python" ]
stackoverflow_0005874711_code_duplication_control_flow_python.txt
Q: What is causing a negative bias in my super-sampling simulation? I'm developing a little test program to see if it is feasible to add noise to an ADC to gain oversampled bits. A little theory, before we begin. Nyquist's sampling theorem suggests that an increase in one bit of resolution requires four additional sa...
What is causing a negative bias in my super-sampling simulation?
I'm developing a little test program to see if it is feasible to add noise to an ADC to gain oversampled bits. A little theory, before we begin. Nyquist's sampling theorem suggests that an increase in one bit of resolution requires four additional samples, and in general, n more bits requires 2^(n+1) more samples. I'm ...
[ "In sample_adc(..) you probably want to round instead of truncating (systematically round towards negative infinity), i.e. do:\nreturn int(frac * (2 ** adc_res) + 0.5)\n\ninstead of\nreturn int(frac * (2 ** adc_res))\n\nThen the deviations from one are not always on the same side:\n10 bits: 512 volts: 1.0\n11 ...
[ 4, 0, 0 ]
[]
[]
[ "algorithm", "python", "statistics" ]
stackoverflow_0005873307_algorithm_python_statistics.txt
Q: Django History for Custom Dashboard I have decided to use Django-Simple-History for building a history of my models. In turn using that to build the dashboard. I have run into a bit of a snag though. I'm trying to output [User] [added,changed, deleted] [object] on/at [time] but I can't figure it out for the lif...
Django History for Custom Dashboard
I have decided to use Django-Simple-History for building a history of my models. In turn using that to build the dashboard. I have run into a bit of a snag though. I'm trying to output [User] [added,changed, deleted] [object] on/at [time] but I can't figure it out for the life of me. So far I am able to display the ...
[ "Django-Simple-History simply creates a model (and associated database table) that mirrors the object you tie it to and adds four additional fields: history_id, history_date, history_type, and history_object.\nhistory_id: standard primary key\nhistory_date: datetime for when the change occurred\nhistory_type: one o...
[ 9, 1 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0005833905_django_django_models_django_templates_django_views_python.txt
Q: Getting SQL Server messages using ADO and win32com I am currently trying to write a tool that will make it very easy for a non-computer literate user to backup a SQL Server database. To do this I am hoping to use an interesting mix of ADO, win32com and adodbapi. Currently I can easily connect to the server and iss...
Getting SQL Server messages using ADO and win32com
I am currently trying to write a tool that will make it very easy for a non-computer literate user to backup a SQL Server database. To do this I am hoping to use an interesting mix of ADO, win32com and adodbapi. Currently I can easily connect to the server and issues a BACKUP DATABASE T-SQL command. This works, however...
[ "Reading MSDN, it seems only Error objects should get passed to the event handlers. If there are multiple errors, you can get them from the Errors collection of your Connection object. So you should only expect Error objects to get passed to InfoMessage(). If you get PyIUnknown instead, maybe you can try to call Qu...
[ 0 ]
[]
[]
[ "ado", "adodbapi", "python", "sql_server", "win32com" ]
stackoverflow_0005872716_ado_adodbapi_python_sql_server_win32com.txt
Q: Can anyone help with csv2json.py errors please? I'm trying to populate a csv file from the model level, not form..populate once and only once. I've read in many places that poeple use csv2json and them "loaddata" and that is all The thing is that i am getting an error that i didm't see in any other blog or tutoria...
Can anyone help with csv2json.py errors please?
I'm trying to populate a csv file from the model level, not form..populate once and only once. I've read in many places that poeple use csv2json and them "loaddata" and that is all The thing is that i am getting an error that i didm't see in any other blog or tutorial. user@server:/PATH/TO/HOST$ python csv2json.py Isra...
[ "Solved the problem....working amazing :-)\nEDIT: for the rest of you out there, My mistake what that there is a strict format to build the csv file when using the csv2json.py fix. you have to do: \"id, all other fields\", for every line.... i didn't add the id, so it didn't work.... but it is a great and very fact...
[ -1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005875181_django_python.txt
Q: ImportError when trying to import a custom module in Python Note that I searched SO for this error and while there were many similar questions, I didn't find one that addressed this particular issue. I'm working on a Python module that looks like this: /com /company /foo /bar I'm editing a sou...
ImportError when trying to import a custom module in Python
Note that I searched SO for this error and while there were many similar questions, I didn't find one that addressed this particular issue. I'm working on a Python module that looks like this: /com /company /foo /bar I'm editing a source file within the bar directory and attempting to import classe...
[ "The directory containing /com needs to be on the Python path. There are a number of ways to do this:\n\nAt the command line, every time:\nuser@host:~$ PYTHONPATH=/path/to/whatever python some_file.py\nIn your shell configuration (.bashrc, .bash_profile, etc):\nexport PYTHONPATH=/path/to/whatever\nIn Python code (I...
[ 13, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0005875810_module_python.txt
Q: How to initialize a class with data from a python file I'd like to init a class from data stored in a simple python file specified while calling the script. The config file named myconfig.py is : str='home' val=2 flt=7.0 I'd like to call it during class initilization like so. One of the objectives is to define v...
How to initialize a class with data from a python file
I'd like to init a class from data stored in a simple python file specified while calling the script. The config file named myconfig.py is : str='home' val=2 flt=7.0 I'd like to call it during class initilization like so. One of the objectives is to define variable types as well in the file. I know of the configparse...
[ "Well, there are several ways to do this. The easiest way would be to use eval() or exec to evaluate this code within the class scope. But that's also the most dangerous way, especially if these files can be created by someone other than you. In that case, the creator can write malicious code that can pretty much d...
[ 2, 0 ]
[]
[]
[ "configuration", "python", "syntax" ]
stackoverflow_0005875902_configuration_python_syntax.txt
Q: Python and vim on windows? I started learning vim a couple of days ago and surprisingly it felt quite natural to me, I also want to get back to learning python. I thought, why not combine the two? So now I'm looking how to set up a proper python development environment, all my searches turned up either guides for ...
Python and vim on windows?
I started learning vim a couple of days ago and surprisingly it felt quite natural to me, I also want to get back to learning python. I thought, why not combine the two? So now I'm looking how to set up a proper python development environment, all my searches turned up either guides for other OSes (which I just couldn'...
[ "Good choice on VIM!\nHave a look here though:\nhttp://dancingpenguinsoflight.com/2009/02/python-and-vim-make-your-own-ide/\n" ]
[ 7 ]
[]
[]
[ "ide", "python", "vim", "windows" ]
stackoverflow_0005875883_ide_python_vim_windows.txt
Q: python csv.dictreader not working with a data.gov csv Using some random CSV data from data.gov, for example: "Gravesite locations of Veterans and beneficiaries in HAWAII, as of January 2011" http://www.data.gov/raw/4608 I am trying to parse the CSV with python and process each row: randomData = csv.DictReader(ope...
python csv.dictreader not working with a data.gov csv
Using some random CSV data from data.gov, for example: "Gravesite locations of Veterans and beneficiaries in HAWAII, as of January 2011" http://www.data.gov/raw/4608 I am trying to parse the CSV with python and process each row: randomData = csv.DictReader(open('/downloads/ngl_hawaii.csv', 'rb'), delimiter=",") f...
[ "Strange, I get different output from you.\ndata.csv:\n\nd_first_name,d_mid_name,d_last_name,d_suffix,d_birth_date,d_death_date,section_id,row_num,site_num,cem_name,cem_addr_one,cem_addr_two,city,state,zip,cem_url,cem_phone,relationship,v_first_name,v_mid_name,v_last_name,v_suffix,branch,rank,war\n\"Emil\",\"E\",\"...
[ 3, 2, 1, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0005869776_csv_python.txt
Q: Django form.is_valid always returning true I'm new to Django and python and am trying to learn it from a book. In the code below I'm trying to make sure password1 and password2 are the same but it doesn't seem to run the clean_password2 validation because it always returns true even if they have different values. ...
Django form.is_valid always returning true
I'm new to Django and python and am trying to learn it from a book. In the code below I'm trying to make sure password1 and password2 are the same but it doesn't seem to run the clean_password2 validation because it always returns true even if they have different values. import re from django.contrib.auth.models import...
[ "If you are cleaning two fields that depend on each other, you should override the form's clean() method. You can read more here.\n", "Any validator that requires access to more than one field should be part of the clean() method not the clean_<filedname>() method. Check out how django-registration does what yo...
[ 3, 1, 0 ]
[]
[]
[ "django", "python", "validation" ]
stackoverflow_0005875950_django_python_validation.txt
Q: Number of syllables for words in a text I have the following code excerpt to find the number of syllables for all the words in the given input text 'sample.txt' using NLTK : import re import nltk from curses.ascii import isdigit from nltk.corpus import cmudict import nltk.data import pprint d...
Number of syllables for words in a text
I have the following code excerpt to find the number of syllables for all the words in the given input text 'sample.txt' using NLTK : import re import nltk from curses.ascii import isdigit from nltk.corpus import cmudict import nltk.data import pprint d = cmudict.dict() tokenizer = nltk.data.l...
[ "I'm guessing the problem is a key error. Replace your definition with \ndef nsyl(word):\n lowercase = word.lowercase()\n if lowercase not in d:\n return -1\n else:\n return max([len([y for y in x if isdigit(y[-1])]) for x in d[lowercase]])\n\nConversely, you can check to see if the word is in the dicti...
[ 3 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0005876040_nltk_python.txt
Q: Python net activity statistics linux What is the easiest way to get network statistics (bandwidth used, current down/up rate) via Python. I realize it'll have to be a system call to /proc, but is there an easier way or some tool that is available on standard *nix distributions for doing so? Thanks NOTE: I am going...
Python net activity statistics linux
What is the easiest way to get network statistics (bandwidth used, current down/up rate) via Python. I realize it'll have to be a system call to /proc, but is there an easier way or some tool that is available on standard *nix distributions for doing so? Thanks NOTE: I am going to use /proc/net/dev and parse the output...
[ "You could try using http://pypi.python.org/pypi/pynetinfo/ - it would need extending to get the statistics, but that should be fairly trivial. Most of the code is already in place.\nAlternatively you can just parse the output of ip -s link show device_name\n" ]
[ 4 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005876349_linux_python.txt
Q: How can we pass a C structure to Python? I'm a new in both C and Python. These days, I'm learning to embed Python in C. As I am calling Python functions from C, I'd like to know, how can we pass a C structure to Python? thanks alot in advance! A: This documentation on extending and/or embedding Python might get...
How can we pass a C structure to Python?
I'm a new in both C and Python. These days, I'm learning to embed Python in C. As I am calling Python functions from C, I'd like to know, how can we pass a C structure to Python? thanks alot in advance!
[ "This documentation on extending and/or embedding Python might get you started.\nThere is also the ctypes library to dynamically load native DLLs and passing C-like structures in and out of them (completely from within Python).\n", "The cleanest thing to do is probably to create a new type and implement tp_getatt...
[ 2, 2 ]
[ "This is probably not what you're looking for, but we use LCM to share c structs between c/c++, python, java, and matlab programs over udp with multicast. It's very handy for doing robotics.\n" ]
[ -1 ]
[ "c", "cpython", "python" ]
stackoverflow_0005734016_c_cpython_python.txt
Q: What is the new way of checking "callable" methods in python 3.x? I was studying introspection in Python, and as I was getting through basic examples, I found out that the callable built-in function is no longer available in Python 3.1. How can I check if a method is callable now? Thank you A: The callable() bui...
What is the new way of checking "callable" methods in python 3.x?
I was studying introspection in Python, and as I was getting through basic examples, I found out that the callable built-in function is no longer available in Python 3.1. How can I check if a method is callable now? Thank you
[ "The callable() builtin function from Py2.x was resurrected in python3.2.\n", "if hasattr(f, \"__call__\"):\n\nWhat's New In Python 3.0\n", "isinstance(f, collections.Callable)\n\n" ]
[ 23, 8, 4 ]
[]
[]
[ "introspection", "python", "python_3.x" ]
stackoverflow_0002435066_introspection_python_python_3.x.txt
Q: Python library installing macports I would like to install: A. Mod python on a regular Macbookpro (MacOSX 10.6.4) B. And MySQL for Python on the same computer. And the installation is constantly failing. Question 1: Is there a tutorial on how to achieve this on Mac OS? I also hoped that I could use Macports for t...
Python library installing macports
I would like to install: A. Mod python on a regular Macbookpro (MacOSX 10.6.4) B. And MySQL for Python on the same computer. And the installation is constantly failing. Question 1: Is there a tutorial on how to achieve this on Mac OS? I also hoped that I could use Macports for this. I had bad experience with Macports...
[ "This answer is outdated, see Mark's response below\nI had trouble installing python and python libraries on osx, and this is what I ended up doing to fix it:\nUsing macports I installed python26 and python_select. Then use python_select to change from the default python26-apple to python26 (which is from macports)...
[ 0 ]
[]
[]
[ "installation", "macports", "python" ]
stackoverflow_0003147213_installation_macports_python.txt
Q: Toggle comment shortcut in netbeans python? In netbeans the toggle comments shortcut is control + /, which works well for php and ruby but for python it simply does nothing, can someone help? A: Which version of NetBeans are you using? I just tried it in NetBeans 6.9 and it works perfectly in Python source (I ...
Toggle comment shortcut in netbeans python?
In netbeans the toggle comments shortcut is control + /, which works well for php and ruby but for python it simply does nothing, can someone help?
[ "Which version of NetBeans are you using? \nI just tried it in NetBeans 6.9 and it works perfectly in Python source \n(I presume you have Python plugin installed )\nVersion: 0.105 Source: NetBeans Beta\nPlugin Description\nPython support: editing, refactoring, hints, etc.\n" ]
[ 0 ]
[]
[]
[ "ide", "keyboard_shortcuts", "netbeans", "python" ]
stackoverflow_0005876909_ide_keyboard_shortcuts_netbeans_python.txt
Q: How to use ';' (semicolon) in urls, using Google Appengine Using the local dev server, I can use ';' in urls, but as soon as I try the live version hosted by Google, it looks like the ';' and everything afterward is stripped (at least according to request.path_qs). (I would prefer not to encode them if possible, i...
How to use ';' (semicolon) in urls, using Google Appengine
Using the local dev server, I can use ';' in urls, but as soon as I try the live version hosted by Google, it looks like the ';' and everything afterward is stripped (at least according to request.path_qs). (I would prefer not to encode them if possible, it's much less user friendly if the url cannot be constructed by ...
[ "It is a known issue: http://code.google.com/p/googleappengine/issues/detail?id=816\nSo I am afraid you need to use a workaround.\n", "Issue816 has now been fixed, semi-colons are usable with appengine.\n" ]
[ 3, 0 ]
[]
[]
[ "google_app_engine", "python", "url" ]
stackoverflow_0002592540_google_app_engine_python_url.txt
Q: Django + jQuery + Ajax I've a page with a text field at the top, a submit button and below, a list of messages. I want that when you click on submit after you wrote something in the textfield, the application saves the new message in database and display it without refreshing page, with Ajax. The new message shoul...
Django + jQuery + Ajax
I've a page with a text field at the top, a submit button and below, a list of messages. I want that when you click on submit after you wrote something in the textfield, the application saves the new message in database and display it without refreshing page, with Ajax. The new message should appear at the top of messa...
[ "something like this maybe?\ndef send_message(request):\n if request.method == \"POST\":\n message = MessageForm(request.POST)\n message.save()\n\n return HttpResponse(simplejson.dumps({'result' : 'success'}), mimetype='application/javascript')\n\n" ]
[ 4 ]
[]
[]
[ "ajax", "django", "jquery", "python" ]
stackoverflow_0005876954_ajax_django_jquery_python.txt
Q: How to perform a sorting according to rules but with repetition of items to solve circular references? To explain in a clearer way my question I will start by explaining the real-life case I am facing. I am building a physical panel with many words on it that can be selectively lit, in order to compose sentences. ...
How to perform a sorting according to rules but with repetition of items to solve circular references?
To explain in a clearer way my question I will start by explaining the real-life case I am facing. I am building a physical panel with many words on it that can be selectively lit, in order to compose sentences. This is my situation: I know all the sentences that I want to display I want to find out [one of] the short...
[ "If I understand you correctly, this is equivalent to the shortest common supersequence problem. This problem is NP-complete, but there exists approximation algorithms. Google turns up a few papers, including this one.\nThe problem can be solved with a simple DP algorithm in the case of two input sequences, but thi...
[ 10, 6, 2, 1 ]
[]
[]
[ "algorithm", "circular_reference", "language_agnostic", "python", "sorting" ]
stackoverflow_0005784945_algorithm_circular_reference_language_agnostic_python_sorting.txt
Q: How is this invalid syntax? I have a python module that consists of many function definitions, all static. Then at the end I added a class definition however, the interpreter presents me with the following error: Traceback (most recent call last): ...
How is this invalid syntax?
I have a python module that consists of many function definitions, all static. Then at the end I added a class definition however, the interpreter presents me with the following error: Traceback (most recent call last): ...
[ "You have an error on the line(s) before the class. For example:\n$ cat -n pyinvclass.py\n 1 def f():\n 2 return (1, 2\n 3 \n 4 class InvalidPredicateError(Exception):\n 5 pass\n$ python pyinvclass.py\n File \"pyinvclass.py\", line 4\n class InvalidPredicateError(Exception):\n ...
[ 11 ]
[]
[]
[ "class", "definition", "python", "syntax" ]
stackoverflow_0005877353_class_definition_python_syntax.txt
Q: Is Python's SOAPpy library threadsafe? How thread safe is the SOAPpy library for Python? I'm finding the documentation non-existent and no mention of thread safety (for or against) anywhere. Specifically, can threads share a SOAPpy.SOAPProxy object, calling different RPCs? e.g, client = SOAPpy.SOAPProxy(url) thr...
Is Python's SOAPpy library threadsafe?
How thread safe is the SOAPpy library for Python? I'm finding the documentation non-existent and no mention of thread safety (for or against) anywhere. Specifically, can threads share a SOAPpy.SOAPProxy object, calling different RPCs? e.g, client = SOAPpy.SOAPProxy(url) thread1: client.MyFunc() thread2: client.MyFunc...
[ "SOAPpy.SOAPProxy doesn't appear to be thread-safe at first glance. In the version 0.12.0 __call method, there is an assignment (Client.py line 360):\n r, self.namespace = self.transport.call(self.proxy, m, ns, sa,\n encoding = self.encoding,\n ...
[ 1 ]
[]
[]
[ "python", "soap", "thread_safety" ]
stackoverflow_0005876000_python_soap_thread_safety.txt
Q: Inherited but not shared (static) class members in Python I'm writing a little validation API and initialize the constraints for each field in the class' __init__ method. But this setup could principially be done for the class a single time. class Demo(Validatable): def __init__(self): Validatable.__i...
Inherited but not shared (static) class members in Python
I'm writing a little validation API and initialize the constraints for each field in the class' __init__ method. But this setup could principially be done for the class a single time. class Demo(Validatable): def __init__(self): Validatable.__init__(self) self.count = 11 # could be done at...
[ "There are two parts to this question.\n\nHow does one set the values of the Validatable data structures at the subclass level, instead of in the inherited Validatable class; and\nHow does one define the constrain_field method so that it can be called once on class initialization, instead of every time an instance ...
[ 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0005875834_oop_python.txt
Q: Php/Perl/Python/Shell script to rename files based the presence of certain characters in centOS 5.6, i need to recursively rename a series of files in /path. the files that need to be renamed contain groups of special characters in lieu of accented chars. i mapped out the table for conversion here. (What kind of e...
Php/Perl/Python/Shell script to rename files based the presence of certain characters
in centOS 5.6, i need to recursively rename a series of files in /path. the files that need to be renamed contain groups of special characters in lieu of accented chars. i mapped out the table for conversion here. (What kind of encoding was used here anyways?) i have a guess that perl would be best choice for the task,...
[ "That's mis-encoded UTF-8. Use convmv for that.\n>>> print u'Ó'.encode('cp1252').decode('utf-8').encode('cp1252').decode('utf-8')\nÓ\n\n​\n$ convmv --nosmart -f utf-8 -t cp1252 Ó\nStarting a dry run without changes...\nmv \"./Ó\" \"./Ó\"\nÓ exists and differs or --replace option missing - skipped\n...
[ 3 ]
[]
[]
[ "perl", "php", "python", "shell", "unicode" ]
stackoverflow_0005877759_perl_php_python_shell_unicode.txt
Q: Execute a python script stored on a server/network location on a user's local machine using PHP I have a webserver running IIS (Machine A) that is running PHP for me. When a user points their browser to a web page that is hosted on the webserver with a PHP script on it, they need to populate a few forms, and then ...
Execute a python script stored on a server/network location on a user's local machine using PHP
I have a webserver running IIS (Machine A) that is running PHP for me. When a user points their browser to a web page that is hosted on the webserver with a PHP script on it, they need to populate a few forms, and then hit a button that will then run the PHP script, which will fire off a python script I've already buil...
[ "The question is not exactly clear, but from my understanding, you're trying to execute code on the local user's machine and you can't do that via Python.\nYour best bet is to write JavaScript that will do the job for you (a few browsers only as you're working with local storage due to HTML5), or you can have your ...
[ 1, 0 ]
[]
[]
[ "iis", "php", "python" ]
stackoverflow_0005877621_iis_php_python.txt
Q: networkx: edge weight as a calculated value I want to implement a shortest path algorithm with NetworkX library. In my case, my weight function derives the value from other edge attributes. Because weight is a calculated value, I don't want to store it as an extra attribute to avoid the complication e.g. update th...
networkx: edge weight as a calculated value
I want to implement a shortest path algorithm with NetworkX library. In my case, my weight function derives the value from other edge attributes. Because weight is a calculated value, I don't want to store it as an extra attribute to avoid the complication e.g. update the value when other attributes change. NetworkX's ...
[ "The parameter does need to be a key in the edge attribute dictionary. So you need to set an edge attribute in the dictionary to use as a weight. You could assign those in a simple loop before computing the shortest path (and delete them later if you want). \nAlternatively you could modify the Dijkstra algorithm co...
[ 4, 3 ]
[]
[]
[ "graph", "networkx", "python", "shortest_path" ]
stackoverflow_0005859720_graph_networkx_python_shortest_path.txt
Q: Calling another process from python/child process need to access shell I'm calling a C/C++ program from python with Popen, python code should observe behavior of child process and collect some data for his own work. Problem is that C code already uses pipes for calling some shell commands - so after my execution f...
Calling another process from python/child process need to access shell
I'm calling a C/C++ program from python with Popen, python code should observe behavior of child process and collect some data for his own work. Problem is that C code already uses pipes for calling some shell commands - so after my execution from python, C program cannot execute bash shell command. Is there any way in...
[ "From your description, it seems that you are using Popen to execute a command line, which has Popen call a shell.\nYou should instead have Popen call your program directly, like this:\nfrom subprocess import Popen,PIPE\np = Popen(['/my/fancy/program','-myarg1','-myarg2'],stdout=PIPE)\nfrom_process = p.communicate(...
[ 2, 0 ]
[]
[]
[ "c", "c++", "python", "subprocess", "unix" ]
stackoverflow_0002683491_c_c++_python_subprocess_unix.txt
Q: Comparing Object Fields with Django's ORM Is comparing columns in different tables using less-than/greater-than operators supported in Django's ORM? For example, I'm trying to compare two object fields in a Django query, which would have the SQL equivalent of: SELECT a.id FROM mytable a LEFT OUTER JOIN myothertabl...
Comparing Object Fields with Django's ORM
Is comparing columns in different tables using less-than/greater-than operators supported in Django's ORM? For example, I'm trying to compare two object fields in a Django query, which would have the SQL equivalent of: SELECT a.id FROM mytable a LEFT OUTER JOIN myothertable b ON b.id = a.other_id AND a.val < b.someval ...
[ "S.Lott's answer is the way to go. Here's an example of using F:\nclass ModelA(models.Model):\n val = IntegerField()\n model_b = ForeignKey('ModelB')\n\nclass ModelB(models.Model):\n val = IntegerField()\n\n\n>>> from django.db.models import F\n>>> ModelA.objects.filter(val__lt=F('model_b__val'))\n>>> prin...
[ 4 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0005877856_django_django_orm_python.txt
Q: Compile Python Program Linux Is there a way where I can compile my python program (.py) to become just a regular program that I don't haft to run threw the terminal to run it??? Example I don't wanna do this to run it threw the terminal. ./whatever.py Example I wanna be able to make the file like a Windows .exe, b...
Compile Python Program Linux
Is there a way where I can compile my python program (.py) to become just a regular program that I don't haft to run threw the terminal to run it??? Example I don't wanna do this to run it threw the terminal. ./whatever.py Example I wanna be able to make the file like a Windows .exe, but for Linux like the one below, f...
[ "You need to add a Shebang at the first line of your file like this:\n#!/usr/bin/env python\n\nand make your file executable by typing (in a terminal):\nchmod u+x my_file.py\n\n", "If you want to make a frozen binary from python scripts, use cx_Freeze\n" ]
[ 6, 2 ]
[]
[]
[ "compilation", "executable", "python" ]
stackoverflow_0005878086_compilation_executable_python.txt
Q: Python library to detect if a file has changed between different runs? Suppose I have a program A. I run it, and performs some operation starting from a file foo.txt. Now A terminates. New run of A. It checks if the file foo.txt has changed. If the file has changed, A runs its operation again, otherwise, it quit...
Python library to detect if a file has changed between different runs?
Suppose I have a program A. I run it, and performs some operation starting from a file foo.txt. Now A terminates. New run of A. It checks if the file foo.txt has changed. If the file has changed, A runs its operation again, otherwise, it quits. Does a library function/external library for this exists ? Of course it c...
[ "It's unlikely that someone made a library for something so simple. Solution in 13 lines:\nimport pickle\nimport md5\ntry:\n l = pickle.load(open(\"db\"))\nexcept IOError:\n l = []\ndb = dict(l)\npath = \"/etc/hosts\"\nchecksum = md5.md5(open(path).read())\nif db.get(path, None) != checksum:\n print \"fil...
[ 10, 6, 2, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0001912567_file_python.txt
Q: python: what happens when an object is passed in multiprocessing.Process? p = Process(target=f, args=(myObject,)) p.start() p.join() From experimentation, inside of function f(), I can access myObject fine and its members appears to be intact, even though presumably we're in a different process. Printing id(myObj...
python: what happens when an object is passed in multiprocessing.Process?
p = Process(target=f, args=(myObject,)) p.start() p.join() From experimentation, inside of function f(), I can access myObject fine and its members appears to be intact, even though presumably we're in a different process. Printing id(myObject) in the current function and in f() returns the same number. Is Python sec...
[ "The actual process depends on whether you are running unix or windows.\nOn *nix, fork() is used which creates a complete copy of your process. \nOn windows, I believe the object is pickled (see the pickle module) and sent over some IPC channel. \n", "As Winston wrote: on Unix the process will be forked and the f...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005878363_python.txt