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: Python and Django basics I am a Java developer and am going to try out Python/Django for the first time and I had some basic questions from my end. Which are the go-to python forums? Which are the go-to django forums? What are the go-to IDEs? (I use Eclipse for Java) Are there any books you encourage or discourage...
Python and Django basics
I am a Java developer and am going to try out Python/Django for the first time and I had some basic questions from my end. Which are the go-to python forums? Which are the go-to django forums? What are the go-to IDEs? (I use Eclipse for Java) Are there any books you encourage or discourage me from reading? Any final wo...
[ "https://www.djangoproject.com/community/\nhttp://www.python.org/community/lists/\nAll (user) mailing lists are extremely friendly, just make sure not to ask user questions on any of the dev-lists.\n\"Welcome\",\nKlaas\n", "Phenomenal book on python(and it's free) http://diveintopython.net/\nOther than that, the ...
[ 2, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006059744_django_python.txt
Q: Can django-model-utils StatusModel provide human readable status options? I am trying to use the StatusModel feature of Carl Meyer's awesome django-model-utils package to create a model that has a status field. It's a very nice design in which you subclass your model from StatusModel and pass a Choices object to a...
Can django-model-utils StatusModel provide human readable status options?
I am trying to use the StatusModel feature of Carl Meyer's awesome django-model-utils package to create a model that has a status field. It's a very nice design in which you subclass your model from StatusModel and pass a Choices object to a field on the model called STATUS, which automatically creates 'status' and 'st...
[ "You can just use the normal get_FOO_display() method - in this case {{ petition.get_status_display }}\n" ]
[ 5 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0006059908_django_django_models_python.txt
Q: make directory using variables problem i can't make a directory using defined variables, i get an , WindowsError: [Error 183] Cannot create a file when that file already exists: i tried something like this: import os, ConfigParser import Tkinter as tk root = Tk() exp_no = "" config = ConfigParser.ConfigParser(...
make directory using variables problem
i can't make a directory using defined variables, i get an , WindowsError: [Error 183] Cannot create a file when that file already exists: i tried something like this: import os, ConfigParser import Tkinter as tk root = Tk() exp_no = "" config = ConfigParser.ConfigParser() config.read("config.ini") resultado = conf...
[ "I believe that\nos.mkdir(resultado+'/'+en1.get())\n\nis running as\nos.mkdir(resultado+'/')\n\nbecause en1.get() might be empty or concatanation of paths is wrong which results in just resultado.\nCould you verify that en1.get() contains something? And could you use os.path.join?\n", "It sounds like Windows is r...
[ 6, 2 ]
[]
[]
[ "directory", "python", "variables" ]
stackoverflow_0006060496_directory_python_variables.txt
Q: NameError, global not defined when using try,except Edit: Ignore this, I figured it out about 3 seconds after posting this but can't delete it =( I have this try, except code for working with RackSpace cloudfiles try: cacheobject = cachecontainer.get_object('file.jpg') except NoSuchObject as object...
NameError, global not defined when using try,except
Edit: Ignore this, I figured it out about 3 seconds after posting this but can't delete it =( I have this try, except code for working with RackSpace cloudfiles try: cacheobject = cachecontainer.get_object('file.jpg') except NoSuchObject as objectname: raise tornado.web.HTTPError(404) If 'file....
[ "facepalm\nYeah this programming thing's only my job, nothing big\nI have to use the stupid thingy thing don't I\ntry:\n cacheobject = cachecontainer.get_object('file.jpg')\nexcept cloudfiles.errors.NoSuchObject as objectname:\n raise tornado.web.HTTPError(404)\n\nI'll try and not be stupid in future\n", "N...
[ 3, 1, 0 ]
[]
[]
[ "exception_handling", "python", "rackspace_cloud", "tornado" ]
stackoverflow_0006060865_exception_handling_python_rackspace_cloud_tornado.txt
Q: Eclipse for Java is great! Is there an analogon for python? Possible Duplicate: What IDE to use for Python? I want to get serious with python and write bigger projects. And for that I need an IDE, that helps me concentrate more on thinking and less on coding. Until know I used TextMate (Mac), vim, and notepad++ ...
Eclipse for Java is great! Is there an analogon for python?
Possible Duplicate: What IDE to use for Python? I want to get serious with python and write bigger projects. And for that I need an IDE, that helps me concentrate more on thinking and less on coding. Until know I used TextMate (Mac), vim, and notepad++ (Windows). editors like these are good to grab a file for quick ...
[ "PyDev is a Python IDE based on Eclipse.\n", "Eclipse supports Python development.\n", "I recently switch from Eclipse PDT to PHP Storm for my development. I think you should try jetbrain's IDE for Python : http://www.jetbrains.com/pycharm/\n", "With google I found an integretated IDE for Eclipse for Python I...
[ 4, 3, 2, 1, 0 ]
[]
[]
[ "ide", "python" ]
stackoverflow_0006060931_ide_python.txt
Q: Fastest ubuntu image library for annotating I am currently working with images and would like to know the fastest image processing library regarding annotating. I'm currently using this command: convert orig.tif -background Red -density 300 -font /usr/share/fonts/truetype/msttcorefonts/Arial.ttf -pointsize 12 -gra...
Fastest ubuntu image library for annotating
I am currently working with images and would like to know the fastest image processing library regarding annotating. I'm currently using this command: convert orig.tif -background Red -density 300 -font /usr/share/fonts/truetype/msttcorefonts/Arial.ttf -pointsize 12 -gravity south -splice 0x150 -gravity southwest -anno...
[ "Calling things from subprocess.call is always going to have quite a bit of overhead compared to an actual shell (e.g. bash). \nHave you tried using imagemagick's python bindings instead of calling it through subprocess? (Edit: Cancel that... Those bindings are rather outdated. I don't know of any better ones, tho...
[ 2 ]
[]
[]
[ "image_processing", "imagemagick", "python" ]
stackoverflow_0006060421_image_processing_imagemagick_python.txt
Q: What's the difference between a keyword or a statement, and a function call? I was thinking about this recently since Python 3 is changing print from a statement to a function. However, Ruby and CoffeeScript take the opposite approach, since you often leave out parentheses from functions, thereby blurring the dist...
What's the difference between a keyword or a statement, and a function call?
I was thinking about this recently since Python 3 is changing print from a statement to a function. However, Ruby and CoffeeScript take the opposite approach, since you often leave out parentheses from functions, thereby blurring the distinction between keywords/statements and functions. (A function call without paren...
[ "A function is executed within a stack frame, whereas a keyword statement isn't necessarily. A good example is the return statement: If it were a function and would execute in its own stack, there would be no way it could control the execution flow in the way it does.\n", "Keywords and functions are ambiguous. W...
[ 4, 2, 1, 0 ]
[]
[]
[ "coffeescript", "function", "keyword", "python" ]
stackoverflow_0006054672_coffeescript_function_keyword_python.txt
Q: Python / AJAX / JavaScript - HTML page printing twice during GET I currently have an issue with my program in which I'm trying to produce live search (much like Google's) using AJAX. At the moment, its based on a list of cities, so when a user types for example "A" in the form, it will show a list of all cities th...
Python / AJAX / JavaScript - HTML page printing twice during GET
I currently have an issue with my program in which I'm trying to produce live search (much like Google's) using AJAX. At the moment, its based on a list of cities, so when a user types for example "A" in the form, it will show a list of all cities that start with "A". If the user continues to type, for example "Al", it...
[ "How are your events set up?\nIn the image http://img819.imageshack.us/img819/5808/city4p.jpg, I can see that it's called with q= and there's no string to follow so showCity is called with an empty string. That makes your script go the print template path.\nCan you please show the code where showCity gets called?\n...
[ 0 ]
[]
[]
[ "ajax", "cgi", "javascript", "python" ]
stackoverflow_0006061068_ajax_cgi_javascript_python.txt
Q: Why dictionary values aren't in the inserted order? When i declare a list 1,2,3,4 and i do something with it , even just print i get back the same sequence 1,2,3,4. But when i do anything with dictionaries , they always change number sequence , like it is being sorted in a twisted way i can't understand . test1 =...
Why dictionary values aren't in the inserted order?
When i declare a list 1,2,3,4 and i do something with it , even just print i get back the same sequence 1,2,3,4. But when i do anything with dictionaries , they always change number sequence , like it is being sorted in a twisted way i can't understand . test1 = [4,1,2,3,6,5] print test1 test2 = {"c":3,"a":1,"b":2,"d"...
[ "Dictionaries in Python are unordered by definition. Use OrderedDict if you need the order in which values were inserted (it's available in Python 2.7 and 3.x).\n", "dictionary sort order is undefined! Do not rely on it for anything. Look for a sorted dictionary if you really want a sorted dictionary, but usually...
[ 12, 2, 2, 1, 0, 0 ]
[]
[]
[ "dictionary", "python", "sequence" ]
stackoverflow_0006061380_dictionary_python_sequence.txt
Q: How to get value of arguments passed to functions on the stack? Using: traceback.print_stack() I can get: File "x.py", line 20, in <module> y(x) File "x.py", line 11, in y fun(x) File "x.py", line 8, in fun traceback.print_stack() I there any way to get something like this: File "x.py", line ...
How to get value of arguments passed to functions on the stack?
Using: traceback.print_stack() I can get: File "x.py", line 20, in <module> y(x) File "x.py", line 11, in y fun(x) File "x.py", line 8, in fun traceback.print_stack() I there any way to get something like this: File "x.py", line 20, in <module> y(x) WHERE x == 1 File "x.py", line 11, in y ...
[ "You can probably rig something up by using inspect.getargvalues() and accessing the stack frame belonging to your traceback:\n inspect.getargvalues(traceback.tb_frame)\n\nYou'll have to do some work to get the output exactly as desired. The above line is only for the innermost frame, so you'll have to walk up the...
[ 14, 10 ]
[]
[]
[ "python", "stack_trace", "traceback" ]
stackoverflow_0006061744_python_stack_trace_traceback.txt
Q: Facebook news feed, cant find server I have used the code on this site: http://blog.carduner.net/2010/05/26/authenticating-with-facebook-on-the-command-line-using-python/ I am trying to get a news feed from the users facebook account. I have created an application on facebook and put the application ID and Secret ...
Facebook news feed, cant find server
I have used the code on this site: http://blog.carduner.net/2010/05/26/authenticating-with-facebook-on-the-command-line-using-python/ I am trying to get a news feed from the users facebook account. I have created an application on facebook and put the application ID and Secret into the variables in the program. For som...
[ "Replace 127.0.0.1 with 'localhost'. That works for me. This is a low-priority bug in Facebook : http://forum.developers.facebook.net/viewtopic.php?id=82131\n" ]
[ 0 ]
[]
[]
[ "facebook", "facebook_graph_api", "python" ]
stackoverflow_0004601748_facebook_facebook_graph_api_python.txt
Q: python or pyqt - checking mouse button clicked state I need to check if a mouse button is clicked or released. I'm using pyqt - any way to check the mouse button release state in qt or directly in python? I know of pygame module but would prefer not to have to install it. A: Check you doc at PyQt4/doc/html/qt.ht...
python or pyqt - checking mouse button clicked state
I need to check if a mouse button is clicked or released. I'm using pyqt - any way to check the mouse button release state in qt or directly in python? I know of pygame module but would prefer not to have to install it.
[ "Check you doc at PyQt4/doc/html/qt.html#MouseButton-enum\nConstant Value\nQt.NoButton 0x00000000\nQt.LeftButton 0x00000001\nQt.RightButton 0x00000002\nQt.MidButton 0x00000004\nQt.MiddleButton MidButton\nQt.XButton1 0x00000008\nQt.XButton2 0x00000010\n\nA simple example:\n>>> from PyQt4 import QtCore, QtGu...
[ 7 ]
[]
[]
[ "click", "mouse", "pyqt", "python", "release" ]
stackoverflow_0006061839_click_mouse_pyqt_python_release.txt
Q: Python subprocess output to stdout I am using the subprocess module to run binaries from python. To capture the output produced by the binary, I am using: proc = subprocess.Popen (command_args, shell=False, stdout=subprocess.PIPE) out = proc.communicate()[0] #print the output of the child process to stdout print (...
Python subprocess output to stdout
I am using the subprocess module to run binaries from python. To capture the output produced by the binary, I am using: proc = subprocess.Popen (command_args, shell=False, stdout=subprocess.PIPE) out = proc.communicate()[0] #print the output of the child process to stdout print (out) What this does is print the output...
[ "Simply don't send the output to a pipe:\nproc = subprocess.Popen (command_args, shell=False)\nproc.communicate()\n\n" ]
[ 19 ]
[]
[]
[ "python", "stdout", "subprocess" ]
stackoverflow_0006062340_python_stdout_subprocess.txt
Q: Python: efficient counting number of unique values of a key in a list of dictionaries There must be a better way of writing this Python code where I have a list of people (people are dictionaries) and I am trying to find the number of unique values of a certain key (in this case the key is called Nationality and I...
Python: efficient counting number of unique values of a key in a list of dictionaries
There must be a better way of writing this Python code where I have a list of people (people are dictionaries) and I am trying to find the number of unique values of a certain key (in this case the key is called Nationality and I am trying to find the number of unique nationalities in the list of people): no_of_nationa...
[ "A better way is to build the set directly from the dictionaries:\nprint len(set(p['Nationality'] for p in people))\n\n", "There is collections module\nimport collections\n....\ncount = collections.Counter()\nfor p in people:\n count[p['Nationality']] += 1;\nprint 'There are', len(count), 'nationalities in thi...
[ 11, 2, 0, 0 ]
[]
[]
[ "count", "dictionary", "list", "python", "unique" ]
stackoverflow_0006062212_count_dictionary_list_python_unique.txt
Q: How do I use the inet type with Python and postgresql? I am writing a python3 program that uses a postgresql database, I am using py-postgresql: http://python.projects.postgresql.org/ as the database driver. One table stores IP addresses using the inet type. I have created the following prepared statement: aID = d...
How do I use the inet type with Python and postgresql?
I am writing a python3 program that uses a postgresql database, I am using py-postgresql: http://python.projects.postgresql.org/ as the database driver. One table stores IP addresses using the inet type. I have created the following prepared statement: aID = db.prepare('SELECT id FROM a_records WHERE ip = $1 LIMIT 1') ...
[ "I've been having this problem all day, and I could not find any solution, so obviously I found the solution on my own a few minutes after posting here.\nI need to replace $1 with inet($1::varchar), it seems that postgresql does not like it being a string when converting to an inet value, and you must typecast it a...
[ 1, 1, 0 ]
[]
[]
[ "inet", "postgresql", "python" ]
stackoverflow_0006026375_inet_postgresql_python.txt
Q: Problem with urllib2 loading mobile site I'm trying to fetch some data from http://m.finnkino.fi/events/now_showing, but at the moment I'm failing badly because I'm not even able to load the page source with python. At the moment I'm using following code: req = urllib2.urlopen(URL,None,2.5) page = req.read() print...
Problem with urllib2 loading mobile site
I'm trying to fetch some data from http://m.finnkino.fi/events/now_showing, but at the moment I'm failing badly because I'm not even able to load the page source with python. At the moment I'm using following code: req = urllib2.urlopen(URL,None,2.5) page = req.read() print page Here is the traceback for timeout error...
[ "Following snippet works fine. \nimport httplib\nheaders = {\"User-Agent\": \"Mozilla/5.0\"}\nconn = httplib.HTTPConnection(\"m.finnkino.fi\")\nconn.request(\"GET\", \"/events/now_showing\", \"\", headers)\nresponse = conn.getresponse()\nprint response.status, response.reason\ndata = response.read()\nprint data\nco...
[ 3 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0006061306_python_urllib2.txt
Q: How can I wrap a block in jinja2 I basically want to do something like this in my base template: {% if the block 'headline' is not empty %} <div class="something"><h1>{% block headline %}{% end block %}</h1></div> {% endif %} In jinja2 it appears blocks are not variables and you can't get at their contents or tes...
How can I wrap a block in jinja2
I basically want to do something like this in my base template: {% if the block 'headline' is not empty %} <div class="something"><h1>{% block headline %}{% end block %}</h1></div> {% endif %} In jinja2 it appears blocks are not variables and you can't get at their contents or test their values, or anything else but o...
[ "You should be able check the contents of a block using the self.blockname syntax.\n{% if self.headline() is not empty %}\n{# Write out Headline HTML wrapper here #}\n{% endif %}\n\nTo quote from the documentation:\n\nIf you want to print a block multiple times you can however use the special self variable and call...
[ 4 ]
[]
[]
[ "django", "jinja2", "python" ]
stackoverflow_0006062986_django_jinja2_python.txt
Q: compare two python strings that contain numbers UPDATE: I should have specified this sooner, but not all of the names are simply floats. For example, some of them are "prefixed" with "YT". So for example" YT1.1. so, you have the same problem YT1.9 < YT1.11 should be true. I'm really surprised that the string compa...
compare two python strings that contain numbers
UPDATE: I should have specified this sooner, but not all of the names are simply floats. For example, some of them are "prefixed" with "YT". So for example" YT1.1. so, you have the same problem YT1.9 < YT1.11 should be true. I'm really surprised that the string comparison fails.... hello, this should be a pretty simple...
[ "Convert the names to tuples of integers and compare the tuples:\ndef splittedname(s):\n return tuple(int(x) for x in s.split('.'))\n\nsplittedname(s1) > splittedname(s2)\n\nUpdate: Since your names apparently can contain other characters than digits, you'll need to check for ValueError and leave any values that...
[ 13, 1, 1, 0 ]
[ "If you know they are real numbers [*] , simply:\n>>> float(s1) > float(s2)\nTrue\n\n[*] Otherwise, be ready to handle a raised ValueError.\n" ]
[ -3 ]
[ "numbers", "python", "string" ]
stackoverflow_0006062973_numbers_python_string.txt
Q: Difference between yield statement in python and MyHDL I am currently learning MyHDL for my summer project. I have a problem grasping the functioning of yield statement in it. Though its true that the MyHDL is based upon python, it uses its yield statement in a specialized way. the link for the same is : http://ww...
Difference between yield statement in python and MyHDL
I am currently learning MyHDL for my summer project. I have a problem grasping the functioning of yield statement in it. Though its true that the MyHDL is based upon python, it uses its yield statement in a specialized way. the link for the same is : http://www.myhdl.org/doc/current/manual/reference.html#myhdl.always i...
[ "First and foremost: remember that the MyHDL implementation is strictly pure Python. In that sense there is no \"difference\" between a yield statement in MyHDL and in Python.\nMyHDL really is a way to use Python as a HDL. Partially, this is done by implementing some hardware design specific objects in a pure Pyth...
[ 3, 2, 2 ]
[]
[]
[ "myhdl", "python", "yield" ]
stackoverflow_0006044930_myhdl_python_yield.txt
Q: Google App Engine Versioning in the Datastore Google App Engine has the concept of app versions. i.e., you can have multiple versions of your app running concurrently and accessible at different subdomains. For instance: http://1.my-app-name.appspot.com, http://2.my-app-name.appspot.com. What aspects of the app ar...
Google App Engine Versioning in the Datastore
Google App Engine has the concept of app versions. i.e., you can have multiple versions of your app running concurrently and accessible at different subdomains. For instance: http://1.my-app-name.appspot.com, http://2.my-app-name.appspot.com. What aspects of the app are actually "versioned" by this? Is it only the Pyth...
[ "Correct, app version refers only to your uploaded files. Both versions use with the same datastore.\nNote that the datastore itself is schema-less. Each entity is an independent collection of key/value pairs. Two entities of the same kind don't have to share the same set of properties, or property types. db.Model ...
[ 26, 7 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0006063286_google_app_engine_google_cloud_datastore_python.txt
Q: PyQT - copy file to clipboard Is it possible to copy file to a clipboard? As if it was pressed "ctrl+c". So that when I press "ctrl+v" in some folder, it will appear here. http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qclipboard.html - cannot find anything about files. file = 'C:\foo.file' clipboard...
PyQT - copy file to clipboard
Is it possible to copy file to a clipboard? As if it was pressed "ctrl+c". So that when I press "ctrl+v" in some folder, it will appear here. http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qclipboard.html - cannot find anything about files. file = 'C:\foo.file' clipboard = QtGui.QApplication.clipboard() ?...
[ "Clipboard data is modelled with QMimeData class, which can contain a list of URLs, including local filesystem URLs.\nfrom PyQt4 import QtCore, QtGui\n\napp = QtGui.QApplication([])\n\ndata = QtCore.QMimeData()\nurl = QtCore.QUrl.fromLocalFile('c:\\\\foo.file')\ndata.setUrls([url])\n\napp.clipboard().setMimeData(da...
[ 9, 5 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0006062382_pyqt_python.txt
Q: how can I take an specific line in big file which has many similar lines, using python? have different files with same name, in different directories. In these files there are lines which are almost equal, I would like to take out only the last line of these ones( there are more lines after it) and write it in ano...
how can I take an specific line in big file which has many similar lines, using python?
have different files with same name, in different directories. In these files there are lines which are almost equal, I would like to take out only the last line of these ones( there are more lines after it) and write it in another file. So far what I have done: #!/usr/bin/env python import os def cd_grep(): for f...
[ "Not sure about the error you are receiving (after your last edit). \nI have tried to rewrite the code a bit, hope it gives you a result similar to what you need (WARNING: not tested). \nwith open ('comparation', 'a') as write_file:\n for path, dirs, files in os.walk(os.getcwd()):\n for filename in [f for f in ...
[ 2, 0 ]
[]
[]
[ "python", "readline", "text" ]
stackoverflow_0006063669_python_readline_text.txt
Q: On Google App Engine in Python how do you detect if a JPEG uses CMYK color space and how do you convert it to RGB? The Images API in Google App Engine does not appear to handle CMYK JPEG images properly when applying transforms. On the production server the resulting image looks washed out and on the dev server (w...
On Google App Engine in Python how do you detect if a JPEG uses CMYK color space and how do you convert it to RGB?
The Images API in Google App Engine does not appear to handle CMYK JPEG images properly when applying transforms. On the production server the resulting image looks washed out and on the dev server (where GAE uses PIL) the resulting image is darker and less defined. It seems like the API assumes all JPEG files are RGB....
[ "JPEG can refer to both a format standard, JIF, and the most widely-used complying implementation, JFIF.\nUnfortunately, the Images API has no documented support for detection or conversion of JPEGs encoded using Adobe's CMYK-based format. Technically these are valid JPEGs, but support for the format seems to be ex...
[ 3 ]
[]
[]
[ "google_app_engine", "jpeg", "python" ]
stackoverflow_0006063588_google_app_engine_jpeg_python.txt
Q: To use Facebook Javascript or not I'm planning to start a web app that uses the Facebook Python SDK. I found two examples in the sdk, newsfeed and oauth. Since im going to deploy the app at google appengine I'm confused to choose which one to base my project. The oauth example uses OAuth 2.0 directly and the news...
To use Facebook Javascript or not
I'm planning to start a web app that uses the Facebook Python SDK. I found two examples in the sdk, newsfeed and oauth. Since im going to deploy the app at google appengine I'm confused to choose which one to base my project. The oauth example uses OAuth 2.0 directly and the newsfeed example rely on the cookie saved b...
[ "I would think newsfeed, but if there is a difference, it's very small.\n", "If is a Javascript SDK then it runs on the client browser, not in GAE server, so, that should be the one with less ( server ) CPU usage.\n" ]
[ 0, 0 ]
[]
[]
[ "facebook", "oauth", "python" ]
stackoverflow_0006056936_facebook_oauth_python.txt
Q: JSON Encoding with Django adding extra \\ characters I'm trying to create a function that will convert a dictionary containing a message and a Django model instance into JSON, that I can pass back to the client. For example, I have the model Test defined in models.py. from django.db import models class Test(mode...
JSON Encoding with Django adding extra \\ characters
I'm trying to create a function that will convert a dictionary containing a message and a Django model instance into JSON, that I can pass back to the client. For example, I have the model Test defined in models.py. from django.db import models class Test(models.Model): test_field = models.CharField(max_length=40...
[ "Your logic is wrong, unfortunately. Your \"easiest way\", as you state, returns a string - but you don't want a string at that point, you want a dictionary. You end up serializing a string within a string, hence the extra quotes which need to be escaped.\nLuckily, one of the format options for the serialize functi...
[ 5, 1 ]
[]
[]
[ "django", "django_models", "json", "python" ]
stackoverflow_0006064300_django_django_models_json_python.txt
Q: Best online resource to learn Python? I am new to any scripting language. But, Still I worked on scripting a bit like tailoring other scripts to work for my purpose. For me, What is the best online resource to learn Python? [Response Summary:] Some Online Resources: http://docs.python.org/tut/tut.html - Beginner...
Best online resource to learn Python?
I am new to any scripting language. But, Still I worked on scripting a bit like tailoring other scripts to work for my purpose. For me, What is the best online resource to learn Python? [Response Summary:] Some Online Resources: http://docs.python.org/tut/tut.html - Beginners http://diveintopython3.ep.io/ - Inte...
[ "If you need to learn python from scratch - you can start here: http://docs.python.org/tut/tut.html - good begginers guide\nIf you need to extend your knowledge - continue here http://diveintopython3.ep.io/ - good intermediate level book\nIf you need perfect skills - complete this http://www.pythonchallenge.com/ - ...
[ 25, 7, 3, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000070577_python.txt
Q: Accessing fields in model in post procedure in Google App Engine I have a post(self) and I want to add some logic here to add lat and lng (these are computed from google maps) to the data store as defined in my db model. Should I add to data, or should I do it some other way such as with the original class. What i...
Accessing fields in model in post procedure in Google App Engine
I have a post(self) and I want to add some logic here to add lat and lng (these are computed from google maps) to the data store as defined in my db model. Should I add to data, or should I do it some other way such as with the original class. What is the best way to do this? so... class Company(db.Model): company_ty...
[ "The djangoforms help page explains how to add data to your datastore entity. Call save method with commit=False. It returns datastore entity and then you can add fields before saving it with put()\ndef post(self):\n ...\n # This code is after the code above\n if data.is_valid():\n entity=data.save(commit=Fal...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006064273_google_app_engine_python.txt
Q: Python Twisted: how do use different resource hierarchies for localhost connections? I'd like to use one resource hierarchy for localhost connections and another resource hierarchy for all other connections. How would I go about this? publicSite = Site(File("/var/www/")) localhostSite = Site(File("/var/localhost/"...
Python Twisted: how do use different resource hierarchies for localhost connections?
I'd like to use one resource hierarchy for localhost connections and another resource hierarchy for all other connections. How would I go about this? publicSite = Site(File("/var/www/")) localhostSite = Site(File("/var/localhost/")) publicServer = TCPServer(80, publicSite, interface="0.0.0.0") localhostServer = TCPSer...
[ "Instead of binding to 0.0.0.0 for the second server, bind to one or more public addresses on your server. Twisted doesn't provide any APIs for enumerating the addresses on a host, nor for differentiating between public and private addresses (because perhaps your \"public\" address is a 10.x.x.x and a firewall is ...
[ 4 ]
[]
[]
[ "python", "resources", "twisted" ]
stackoverflow_0006064352_python_resources_twisted.txt
Q: How to find the comment tag with BeautifulSoup? I tried soup.find('!--') but it doesn't seem to work. Thanks in advance. Edit: Thanks for the tip on how to find all comments. I have a follow up question. How do I specifically search out for a comment? For example, I have the following comment tag: <!-- <span c...
How to find the comment tag with BeautifulSoup?
I tried soup.find('!--') but it doesn't seem to work. Thanks in advance. Edit: Thanks for the tip on how to find all comments. I have a follow up question. How do I specifically search out for a comment? For example, I have the following comment tag: <!-- <span class="titlefont"> <i>Wednesday 110518</i>(05:00PM)<br ...
[ "You can find all the comments in a document with via the findAll method. See this example showing how to do exactly what you're trying to do Removing elements:\nIn brief, you want this:\ncomments = soup.findAll(text=lambda text:isinstance(text, Comment))\n\nEdit: If you're trying to search within the columns, you ...
[ 24, 0 ]
[]
[]
[ "beautifulsoup", "html", "python", "tags" ]
stackoverflow_0006062210_beautifulsoup_html_python_tags.txt
Q: Classes or closures for simple things in Python I would like to know more about the functions "with memory" implemented as classes vs closures. Consider the (very) simple example: def constant(value): def _inner(): return value return _inner x = constant(5) print(x()) vs. class Constant(): def...
Classes or closures for simple things in Python
I would like to know more about the functions "with memory" implemented as classes vs closures. Consider the (very) simple example: def constant(value): def _inner(): return value return _inner x = constant(5) print(x()) vs. class Constant(): def __init__(self, value): self._value = value ...
[ "In Python 2.6 I get the following:\ndef foo(x):\n def bar():\n return x\n return bar\n\nb = foo(4)\nb.__sizeof__()\n>>> 44\n\nBut using a class:\nclass foo(object):\n def __init__(self,x):\n self.x = x\n def __call__(self):\n return self.x\n\nc = foo(4)\nc.__sizeof__()\n>>> 16\n\nW...
[ 8, 3 ]
[ "If you want performance and only want access to values, then it would be best to use a built-in data type such as a tuple for best performance\n" ]
[ -1 ]
[ "class", "closures", "memory", "performance", "python" ]
stackoverflow_0005430502_class_closures_memory_performance_python.txt
Q: python webkitgtk xmlhttprequest file protocol How to enable xmlhttprequest for file:// protocol in pywebkit ? just like chrome does http://www.google.com/support/forum/p/Chrome/thread?tid=171316324d16747b&hl=en A: Set the enable-file-access-from-file-uris property on WebView: view = webkit.WebView() settings = v...
python webkitgtk xmlhttprequest file protocol
How to enable xmlhttprequest for file:// protocol in pywebkit ? just like chrome does http://www.google.com/support/forum/p/Chrome/thread?tid=171316324d16747b&hl=en
[ "Set the enable-file-access-from-file-uris property on WebView:\nview = webkit.WebView()\nsettings = view.get_settings()\nsettings.set_property('enable-file-access-from-file-uris', 1)\nview.open('file://./foo.html')\n\nExample file foo.html which writes contents of file://./bar.html into the body:\n<html>\n<head><s...
[ 5 ]
[]
[]
[ "file_uri", "gtk", "python", "webkit", "xmlhttprequest" ]
stackoverflow_0006056357_file_uri_gtk_python_webkit_xmlhttprequest.txt
Q: How to insert a newline at middle of a file in python i am a new user of python. Just trying to write a script using python. Can someone help me out. I calculate some values using data from a file, and i want to replace the existing value with the new value in the file along with that i would like to comment out ...
How to insert a newline at middle of a file in python
i am a new user of python. Just trying to write a script using python. Can someone help me out. I calculate some values using data from a file, and i want to replace the existing value with the new value in the file along with that i would like to comment out the existing value so that i can verify whether the new cal...
[ "Output to a new file, line by line, changing what you need. Then replace the old file with the new one.\ninput = open('input.txt','r')\noutput = open('temp.txt','w')\nfor line in input.readlines():\n if line == 'xxx':\n output.write('#' + line)\n output.write('yyy')\n else:\n output.wri...
[ 1, 0 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0006065215_python_python_2.7.txt
Q: Override a module in plone's eggs? I want to override a method (assignment_mapping_from_key) in: eggs/plone.app.portlets-1.1.5.1-py2.4.egg/plone/app/portlets/utils.py ...because when I set a portlet in portlets.xml, I have to use a full path in key attribute and I don't have it (production and development servers...
Override a module in plone's eggs?
I want to override a method (assignment_mapping_from_key) in: eggs/plone.app.portlets-1.1.5.1-py2.4.egg/plone/app/portlets/utils.py ...because when I set a portlet in portlets.xml, I have to use a full path in key attribute and I don't have it (production and development servers have different urls), I want to use a r...
[ "I can't say I would recommend it, but you can have a look at: \n\nhttp://pypi.python.org/pypi/collective.monkeypatcher/1.0.1\n\nwhich may help you do what you want to do, even if it is a bad idea.\nIn general, Plone is designed to be customized inside your own personal module, but not necessarily in the way you de...
[ 4, 1 ]
[]
[]
[ "egg", "plone", "portlet", "python" ]
stackoverflow_0006064454_egg_plone_portlet_python.txt
Q: Is there an Open Source framework for building desktop apps that run in the browser? I'm interested in starting an Open Source project that could be packaged as a desktop application for non-technical end users, but would run in the browser - one existing model would be Google Refine. I'm looking for an existing, ...
Is there an Open Source framework for building desktop apps that run in the browser?
I'm interested in starting an Open Source project that could be packaged as a desktop application for non-technical end users, but would run in the browser - one existing model would be Google Refine. I'm looking for an existing, Open-Source framework that would support this - not the UI portion, but the lower-level ap...
[ "You should be able to build a desktop app that runs in the browser using web2py. Web2py requires no installation or configuration, has no dependencies, and includes a built-in web server and the SQLite RDBMS (as well as a database abstraction layer). The Windows and Mac binaries even include the Python interpreter...
[ 5, 3, 1 ]
[]
[]
[ "desktop", "frameworks", "javascript", "python", "web_applications" ]
stackoverflow_0006063140_desktop_frameworks_javascript_python_web_applications.txt
Q: Email to multiple recipients via Postfix only being received by first address on the list I am using the Python code at the bottom of this question to send the contents of a directory to a list of recipients held within a defined file. Within this file individual addresses are separated by ; and are listed within ...
Email to multiple recipients via Postfix only being received by first address on the list
I am using the Python code at the bottom of this question to send the contents of a directory to a list of recipients held within a defined file. Within this file individual addresses are separated by ; and are listed within a single string. When submitting the command required all is sent without any recorded issue, b...
[ "When you define your message, you should set the To list using a comma-separated list of recipients:\nrecipients = 'foo, bar'\nouter['To'] = recipients\n\nHowever when you call sendmail(), you need to pass it the recipients as a list:\nrcpts = [r.strip() for r in recipients.split(',') if r]\ns.sendmail(sender, rcp...
[ 7 ]
[]
[]
[ "postfix_mta", "python" ]
stackoverflow_0006037184_postfix_mta_python.txt
Q: Quickly Find the Index in an Array Closest to Some Value I have an array of values, t, that is always in increasing order (but not always uniformly spaced). I have another single value, x. I need to find the index in t such that t[index] is closest to x. The function must return zero for x < t.min() and the max...
Quickly Find the Index in an Array Closest to Some Value
I have an array of values, t, that is always in increasing order (but not always uniformly spaced). I have another single value, x. I need to find the index in t such that t[index] is closest to x. The function must return zero for x < t.min() and the max index (or -1) for x > t.max(). I've written two functions to ...
[ "This seems much quicker (for me, Python 3.2-win32, numpy 1.6.0):\nfrom bisect import bisect_left\ndef f3(t, x):\n i = bisect_left(t, x)\n if t[i] - x > 0.5:\n i-=1\n return i\n\n\nOutput:\n[ 10 11 12 ..., 99997 99998 99999]\n37854.22200356027\n37844\n37844\n37844\n37854\n37854\n37854\nf1 0....
[ 7, 1, 1 ]
[]
[]
[ "indexing", "numpy", "performance", "python" ]
stackoverflow_0006065697_indexing_numpy_performance_python.txt
Q: Python/Matplotlib - Figure Borders in wxPython I have a matplotlib figure on a canvas on a wxpython panel. My application is run real-time and the user can re-size the window frame. However, when this happens, the borders around my axes go out of whack. I know I can use the function fig.subplots_adjust to adjust...
Python/Matplotlib - Figure Borders in wxPython
I have a matplotlib figure on a canvas on a wxpython panel. My application is run real-time and the user can re-size the window frame. However, when this happens, the borders around my axes go out of whack. I know I can use the function fig.subplots_adjust to adjust the borders, but the values specified in the functi...
[ "Here is an example of how this can be done. The code defines a function which translates pixel border values into percentages based on the current figure size. It also hooks up an event listener that will adjust the borders when the figure is resized:\nimport numpy\nimport matplotlib.pyplot as plt\n\ndef adjust_b...
[ 5 ]
[]
[]
[ "border", "matplotlib", "python", "wxpython" ]
stackoverflow_0006066091_border_matplotlib_python_wxpython.txt
Q: Python SQL Select statement from a list variable? I am trying to query my sqlite3 db and use values from a list. Here's my code: for i in range(len(infolist)): result = cursor.execute('SELECT COUNT(DISTINCT col1) FROM tablename WHERE col2 = ?', (i...
Python SQL Select statement from a list variable?
I am trying to query my sqlite3 db and use values from a list. Here's my code: for i in range(len(infolist)): result = cursor.execute('SELECT COUNT(DISTINCT col1) FROM tablename WHERE col2 = ?', (infolist[i])) I receive this error: ProgrammingError:...
[ "You need to add a comma to the end of (infolist[i]) right now it's a 22 character string not a tuple. (infolist[i],) should fix that\n", "The second argument to cursor.execute is a sequence and you have passed it a string (which is a sequence of characters). If you are trying to do a 1 element tuple, you need a...
[ 1, 1, 0 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0006066681_python_sql_sqlite.txt
Q: pygtk GtkTreeIter comparision I have a ListStore in PyGTK, which has a bunch of rows. There is a background job processing the data represented by the rows, and when it finishes, it needs to update the row. Of course, to do this, it needs to know which row to update, and is thus keeping an iterator to the row aro...
pygtk GtkTreeIter comparision
I have a ListStore in PyGTK, which has a bunch of rows. There is a background job processing the data represented by the rows, and when it finishes, it needs to update the row. Of course, to do this, it needs to know which row to update, and is thus keeping an iterator to the row around. However, during the background...
[ "Try using the list store's .get_path(iter) method, and compare the resulting paths, instead of comparing the iterators directly.\nUPDATE: You can just call set_value with the invalid iter. gtk will give you a warning but will not throw an exception or anything. It probably just checks whether it's a valid iter any...
[ 0, 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0006065525_gtk_pygtk_python.txt
Q: How to find line number of cursor in Python? I am reading a file in Python. After I read a bunch of lines, is there a convenient function that I can use to get the current line number in the file that the cursor is on? I am trying to refrain from using a counter since I have multiple functions that read the same f...
How to find line number of cursor in Python?
I am reading a file in Python. After I read a bunch of lines, is there a convenient function that I can use to get the current line number in the file that the cursor is on? I am trying to refrain from using a counter since I have multiple functions that read the same file and may move the cursor all over the place. Th...
[ "You can go line-by-line with fileinput:\n\nimport fileinput\nfor line in fileinput.input(encoding=\"utf-8\"):\n process(line)\n\n\n", "Something like enumerate? There's is not really a \"cursor\" per say but the following will give you the current line number while reading a file line-by-line.\nfor i, line in ...
[ 6, 1, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0006066797_file_io_python.txt
Q: Static Object Class / Keys as ForeignKey in Django Model I'm in new territory with Django/Python. I'm building a site where the user selects from a list of available services, and then enters info about the services. I didn't want to keep the service list in the database, becasue that's really more site configurat...
Static Object Class / Keys as ForeignKey in Django Model
I'm in new territory with Django/Python. I'm building a site where the user selects from a list of available services, and then enters info about the services. I didn't want to keep the service list in the database, becasue that's really more site configuration info rather than user info. So I'm setting them as an Obje...
[ "\nIs it possible to use this class as a foreign key in the database? \n\nNo.\nOnly models.Model classes can be used as foreign keys.\n\"Foreign Key\" is a database concept.\nIf you want to have non-database things as foreign keys, they're just strings or numbers and the \"reference\" is a simple mapping that you m...
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0006066444_django_django_models_python.txt
Q: Python - good practice to catch errors I have these files in my project: - main.py - module1.py - module2.py main is the main file that will be directly execute in console. module1 will be imported into main and throws Module1Exception. module2 will be imported into module1, throws Module2Exception and uses lib ...
Python - good practice to catch errors
I have these files in my project: - main.py - module1.py - module2.py main is the main file that will be directly execute in console. module1 will be imported into main and throws Module1Exception. module2 will be imported into module1, throws Module2Exception and uses lib that throws NormalException and CriticalExce...
[ "main should have the responsibility to terminate, not the modules.\nWhat if you wanted to import those modules into another project and you didn't want to terminate the application on an exception?\n" ]
[ 14 ]
[]
[]
[ "python" ]
stackoverflow_0006067018_python.txt
Q: Issue of updating GAE python application When updating my app into GAE by using the following command: python appcfg.py update /home/tom/workspace/DjangoProject I got an error message: mapping values are not allowed here in "/home/tom/workspace/DjangoProject/app.yaml", line 6, column 9 Here is my yaml: applicat...
Issue of updating GAE python application
When updating my app into GAE by using the following command: python appcfg.py update /home/tom/workspace/DjangoProject I got an error message: mapping values are not allowed here in "/home/tom/workspace/DjangoProject/app.yaml", line 6, column 9 Here is my yaml: application:myapp version:1 runtime:python api_version...
[ "After a colon , there has to be space . That's why it was not able to parse your app.yaml.\nTry this\napplication: myapp\nversion: 1\nruntime: python\napi_version: 1\n\nhandlers:\n- url: /\n script: home.py\n\n- url: /index\\.html\n script: home.py\n\n- url: /stylesheets\n static_dir: stylesheets\n\n- url: /(.*...
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0006066737_django_google_app_engine_python.txt
Q: python subprocess.call bash command with process substitution and file redirection In Python I want to call a script that prints to the screen as it executes while also logging the stdout and stderr streams. I have the following line of bash code that I'd like to execute: script.sh > >(tee /tmp/success.log) 2> >(...
python subprocess.call bash command with process substitution and file redirection
In Python I want to call a script that prints to the screen as it executes while also logging the stdout and stderr streams. I have the following line of bash code that I'd like to execute: script.sh > >(tee /tmp/success.log) 2> >(tee /tmp/errors.log >&2) where script.sh is any script that outputs to both stdout and ...
[ "Wrap your command in /bin/bash -c \"your-command-stuff\".\nThen /bin/sh will run bash which will interpret the rest for you. You could also consider using other functions in Python Subprocess to do the redirection, but the above should be quick and effective.\n" ]
[ 3 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0006067173_bash_python.txt
Q: Python tuple question I am reading this http://docs.python.org/dev/library/multiprocessing.html In particular this p = multiprocessing.Process(target=time.sleep, args=(1000,)) I tried the same thing, but if I remove the "," after 1000 it doesn't work. So my question is what is the semantic behind the args=(1000,...
Python tuple question
I am reading this http://docs.python.org/dev/library/multiprocessing.html In particular this p = multiprocessing.Process(target=time.sleep, args=(1000,)) I tried the same thing, but if I remove the "," after 1000 it doesn't work. So my question is what is the semantic behind the args=(1000,) in this case? What is the...
[ "If you just put (1000), Python assumes you're just evaluating the expression as math, hence it gets simplified to just 1000. Think of the result of 5 + (1000) + 4.\nJust as the expression above would get simplified to 1009, here is what your line looks like once things have been simplified:\np = multiprocessing.Pr...
[ 11, 2, 2, 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0006067204_python_tuples.txt
Q: How to select one of table A based on table B in SqlAlchemy? I have two tables Items and ItemDescriptions class Item(Base): __tablename__ = "item" id = Column(Integer, primary_key=True) description_id = Column(Integer, ForeignKey('item_description.id')) class ItemDescription(Base): __tablename__ = ...
How to select one of table A based on table B in SqlAlchemy?
I have two tables Items and ItemDescriptions class Item(Base): __tablename__ = "item" id = Column(Integer, primary_key=True) description_id = Column(Integer, ForeignKey('item_description.id')) class ItemDescription(Base): __tablename__ = "item_description" id = Column(Integer, primary_key=True) Give...
[ "I am a big fan of column_property. Here's a way to do what you want with column_property:\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import *\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\nclass Item(Base):\n __tablename__ = 'item'\n\n id = Column(Integer, primar...
[ 2, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006052615_python_sqlalchemy.txt
Q: Comparing two dates in Django Possible Duplicate: How to compare datetime in Django? I need to compare 2 dates object.submit_date.ctime() > user.last_login.ctime() but always get false. no matter whether last_login it is after the last submit_date A: are comparing wrong, you have to use date() or isoformat...
Comparing two dates in Django
Possible Duplicate: How to compare datetime in Django? I need to compare 2 dates object.submit_date.ctime() > user.last_login.ctime() but always get false. no matter whether last_login it is after the last submit_date
[ "are comparing wrong, you have to use date() or isoformat() instead of ctime()\nLike this:\n\nobject.submit_date.isoformat() > user.last_login.isoformat()\n\nthis includes the time\nor\n\nobject.submit_date.date() > user.last_login.date()\n\n", "If its a datetime object. you can simply compare the datetime ojects...
[ 9, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006067274_django_python.txt
Q: Installing Pycurl on CentOS? I'm finding it to install pycurl on CentOS 5 quite the mission impossible. This is the error I'm getting: >>> import pycurl Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: libcurl.so.4: cannot open shared object file: No such file or directory Som...
Installing Pycurl on CentOS?
I'm finding it to install pycurl on CentOS 5 quite the mission impossible. This is the error I'm getting: >>> import pycurl Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: libcurl.so.4: cannot open shared object file: No such file or directory Some help would be beyond amazing. :...
[ "I know this is an old question, but I was just having this issue and the solution was to add the following soft link:\nln -s /usr/local/lib/libcurl.so.4.1.0 /usr/lib/libcurl.so.4\n\nThis is for libcurl 7.19.\nThe problem appears to be that pycurl is looking for the libcurl so in a different location than where it ...
[ 8, 1, 0 ]
[]
[]
[ "centos", "curl", "linux", "pycurl", "python" ]
stackoverflow_0002684224_centos_curl_linux_pycurl_python.txt
Q: How to make my hangman game can find more than 2 double letter? I had a problem in my hangman program finding more than 2 double letter word. EX:if i had aabc or aaabc in my guess wordlist, then i guess a b c is won't tell me i get right. But if i had abc in guess wordlist, and i guess a b c , then i get right. He...
How to make my hangman game can find more than 2 double letter?
I had a problem in my hangman program finding more than 2 double letter word. EX:if i had aabc or aaabc in my guess wordlist, then i guess a b c is won't tell me i get right. But if i had abc in guess wordlist, and i guess a b c , then i get right. Here what's my code are: while keep_playing: wordlist=["butterfly",...
[ "The end-condition is incorrect because letters_correct is only incremented by one each time (even if the letter occurred multiple times).\nI would change the [victory] end-condition to \"when there are no _'s in guesses\" which means that all the _'s have been replaced which means... (also make sure to take the in...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006067690_python.txt
Q: How to import using a top level path in Python? I'm developing a python framework and want to do imports based on the top-level package (the project name). Users will use the framework by copying the entire framework and writing their own modules within. My current structure looks like this: myapp/ config.py d...
How to import using a top level path in Python?
I'm developing a python framework and want to do imports based on the top-level package (the project name). Users will use the framework by copying the entire framework and writing their own modules within. My current structure looks like this: myapp/ config.py docs/ framework/ main.py utils.py file.py ...
[ "For short: You can't have two modules with the same name one inside the other. You have the myapp folder and the myapp.py file\nThat's because of the order of importing modules.\n\nInside the current directory\nThe current package\nGlobal package folder\n\nSo, if you're trying to import myapp.lib.some_module in co...
[ 2 ]
[]
[]
[ "package", "python" ]
stackoverflow_0006067505_package_python.txt
Q: What's the best compression algorithm for data dumps I'm creating data dumps from my site for others to download and analyze. Each dump will be a giant XML file. I'm trying to figure out the best compression algorithm that: Compresses efficiently (CPU-wise) Makes the smallest possible file Is fairly common I kno...
What's the best compression algorithm for data dumps
I'm creating data dumps from my site for others to download and analyze. Each dump will be a giant XML file. I'm trying to figure out the best compression algorithm that: Compresses efficiently (CPU-wise) Makes the smallest possible file Is fairly common I know the basics of compression, but haven't a clue as to whic...
[ "GZIP with standard compression level should be fine for most cases. Higher compression levels=more CPU time. BZ2 is packing better but is also slower. Well, there is always a trade-off between CPU consumption/running time and compression efficiency...all compressions with default compression levels should be fine....
[ 3 ]
[]
[]
[ "algorithm", "compression", "data_dump", "python" ]
stackoverflow_0006067836_algorithm_compression_data_dump_python.txt
Q: Is it wrong to package Python with my framework? Here's the deal. I am developing a framework whose sole users have extremely messed up python installations on their servers (Linux). They all have multiple versions of Python on their servers and their PYTHONHOME and PYTHONPATH variables are pointing to different v...
Is it wrong to package Python with my framework?
Here's the deal. I am developing a framework whose sole users have extremely messed up python installations on their servers (Linux). They all have multiple versions of Python on their servers and their PYTHONHOME and PYTHONPATH variables are pointing to different versions. Since my framework will require Python 2.6, I...
[ "I'd recommend against it. You'll run into problems between 32b and 64b versions, between different libc versions, noexec locations, wrong selinux/apparmor profiles for custom paths and many other potential problems...\nUnless you're planning to release (and test!) a package for each separate distribution, architec...
[ 2 ]
[]
[]
[ "bundle", "distribution", "frameworks", "python" ]
stackoverflow_0006067785_bundle_distribution_frameworks_python.txt
Q: Why is loading this file taking so much memory? Trying to load a file into python. It's a very big file (1.5Gb), but I have the available memory and I just want to do this once (hence the use of python, I just need to sort the file one time so python was an easy choice). My issue is that loading this file is resu...
Why is loading this file taking so much memory?
Trying to load a file into python. It's a very big file (1.5Gb), but I have the available memory and I just want to do this once (hence the use of python, I just need to sort the file one time so python was an easy choice). My issue is that loading this file is resulting in way to much memory usage. When I've loaded a...
[ "Here is a rough estimate of the memory needed, based on the constants derived from your example. At a minimum you have to figure the Python internal object overhead for each split line, plus the overhead for each string.\nIt estimates 9.1 GB to store the file in memory, assuming the following constants, which are ...
[ 3, 1 ]
[]
[]
[ "memory_management", "python" ]
stackoverflow_0006067373_memory_management_python.txt
Q: What would be a good strategy to implement functionality similar to facebook 'likes'? I have a website where people post comments, pictures, and other content. I want to add a feature that users can like/unlike these items. I use a database to store all the content. There are a few approaches I am looking at: Meth...
What would be a good strategy to implement functionality similar to facebook 'likes'?
I have a website where people post comments, pictures, and other content. I want to add a feature that users can like/unlike these items. I use a database to store all the content. There are a few approaches I am looking at: Method 1: Add a 'like_count' column to the table, and increment it whenever someone likes an i...
[ "Just a crazy idea: Why not just use Facebook's like button? Then, not only do you get that functionality for free, but you can increase the traffic to your website by a huge amount with Facebook wall posts: \"This person likes this site\".\n", "One relation table that does a many-to-many mapping between user and...
[ 3, 1, 1 ]
[]
[]
[ "architecture", "python" ]
stackoverflow_0006067919_architecture_python.txt
Q: How to setup for development of plone products I want to develop a few products for a defined Plone install/version, which I cannot change (3.3.5). What is the best way to organize my source tree, so that I do not have to put a huge plone instance into source control that won't change anyway? I still want to use b...
How to setup for development of plone products
I want to develop a few products for a defined Plone install/version, which I cannot change (3.3.5). What is the best way to organize my source tree, so that I do not have to put a huge plone instance into source control that won't change anyway? I still want to use buildout for local checking, though... What do you re...
[ "Generally speaking, this is done now-a-days with mr.developer. You can use a buildout like this:\n[buildout]\nextends = \n https://raw.githubusercontent.com/plock/pins/master/plone-4-3\n https://raw.githubusercontent.com/plock/pins/master/dev\n\nAnd then add your sources to the auto-checkout parameter in the...
[ 10, 2, 1 ]
[]
[]
[ "buildout", "plone", "python" ]
stackoverflow_0006065614_buildout_plone_python.txt
Q: How do I include strings from a non-tag field as tags using django-tagging? In Django, using the django-tagging app, I want to make it so that items included in a field that isn't a TagField (e.g., authors, in this example) are added to the list of explicitly provided tags when the object is saved. class Publicati...
How do I include strings from a non-tag field as tags using django-tagging?
In Django, using the django-tagging app, I want to make it so that items included in a field that isn't a TagField (e.g., authors, in this example) are added to the list of explicitly provided tags when the object is saved. class Publication(models.Model): title = models.CharField(max_length=200) authors = ...
[ "I think second super(...).save(...) is wrong.\nYou doing all right according docs\n" ]
[ 0 ]
[]
[]
[ "django", "django_tagging", "python" ]
stackoverflow_0006068149_django_django_tagging_python.txt
Q: Detect how I run Python script How do I detect if a script is run from a Windows console or from Komodo debugger without passing different arguments to the script? A: Although I don't know Komodo, I don't think its standard input is interactive, so you could try import sys in_console = sys.__stdin__.isatty() in...
Detect how I run Python script
How do I detect if a script is run from a Windows console or from Komodo debugger without passing different arguments to the script?
[ "Although I don't know Komodo, I don't think its standard input is interactive, so you could try\nimport sys\nin_console = sys.__stdin__.isatty()\n\nin_console will then be true if the invoker provides interactive stdin and you will get what you want, though not in an elegant way.\n" ]
[ 4 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0006068522_python_windows.txt
Q: kill a function after a certain time in windows I've read a lot of posts about using threads, subprocesses, etc.. A lot of it seems over complicated for what I'm trying to do... All I want to do is stop executing a function after X amount of time has elapsed. def big_loop(bob): x = bob start = time.time() ...
kill a function after a certain time in windows
I've read a lot of posts about using threads, subprocesses, etc.. A lot of it seems over complicated for what I'm trying to do... All I want to do is stop executing a function after X amount of time has elapsed. def big_loop(bob): x = bob start = time.time() while True: print time.time()-start This...
[ "Use the building blocks in the multiprocessing module:\nimport multiprocessing\nimport Queue\n\nTIMEOUT = 5\n\ndef big_loop(bob):\n import time\n time.sleep(4)\n return bob*2\n\ndef wrapper(queue, bob):\n result = big_loop(bob)\n queue.put(result)\n queue.close()\n\ndef run_loop_with_timeout():\n...
[ 6, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006068361_python.txt
Q: Problem sending Bytes with pySerial and socat I want to send some bytes via pySerial. I created virtual serial ports with socat for testing purposes: socat PTY,link=./ptyp1,b9600 PTY,link=./ptyp2,b9600 Here's the python code: ser = serial.Serial('./ptyp1') x = struct.pack('B',2) print binascii.hexlify(x) # 02 ...
Problem sending Bytes with pySerial and socat
I want to send some bytes via pySerial. I created virtual serial ports with socat for testing purposes: socat PTY,link=./ptyp1,b9600 PTY,link=./ptyp2,b9600 Here's the python code: ser = serial.Serial('./ptyp1') x = struct.pack('B',2) print binascii.hexlify(x) # 02 ser.write(x) y = ser.read(2) print binascii.hexlify...
[ "The problem was that I read on the same port I wrote to. If I get it right socat \"connects\" the two ports as \"in\" and \"out\". So I have to read on ./ptyp2 if I write to ./ptyp1. After that, everything is fine.\n", "I have installed socat to test your code. I have run this line :\nsocat PTY,link=./ptyp1,b960...
[ 2, 0, 0 ]
[]
[]
[ "pyserial", "python", "socat" ]
stackoverflow_0005523463_pyserial_python_socat.txt
Q: CherryPy : Is there a best way to split the project in multiple files? I'm new to CherryPy, coming from Django. I liked the way Django split the various parts of the project into many files, and I'd like to do the same in CherryPy, instead of having one big file. I think it would be great if I could split the proj...
CherryPy : Is there a best way to split the project in multiple files?
I'm new to CherryPy, coming from Django. I liked the way Django split the various parts of the project into many files, and I'd like to do the same in CherryPy, instead of having one big file. I think it would be great if I could split the project in these parts: application.py : The core of CherryPy, where the server...
[ "Well, I'll answer myself on that one :p\nI found a Google Groups post that poses the basics on how to structure your CherryPy application.\nIn that post, there is a link to a Bitbucket CherryPy application example that is very well structured and could be used as a base example for any CherryPy application.\n" ]
[ 12 ]
[]
[]
[ "cherrypy", "code_organization", "project_organization", "python" ]
stackoverflow_0006068645_cherrypy_code_organization_project_organization_python.txt
Q: How to get 'type' field descriptor from ctypes Structure or Union field I have a structure with different datatype fields. I would like to iterate through the structure fields, check the datatype, and set the field with an appropriate value. I have access to the size and offset of the field through the .size and ....
How to get 'type' field descriptor from ctypes Structure or Union field
I have a structure with different datatype fields. I would like to iterate through the structure fields, check the datatype, and set the field with an appropriate value. I have access to the size and offset of the field through the .size and .offset attribute of the field. How can I get the 'type' attribute of the fiel...
[ "This doesn't appear to be supported in the ctypes API. When the Field repr <Field type=c_long ..> is created, the name is retrieved from the embedded type like this:\nname = ((PyTypeObject *)self->proto)->tp_name;\n\nFor your field the member self->proto points to c_long, yet I find no place in Python 2.7's cfield...
[ 6, 5 ]
[]
[]
[ "ctypes", "descriptor", "python", "types" ]
stackoverflow_0006061225_ctypes_descriptor_python_types.txt
Q: how to use markdown with django? by only in 2 tags I want to use markdown with django. I want to allow use bold and strike tags. Others don't convert. Please teach me. A: Django supports Markdown, but you'll need to install the Python package: http://docs.djangoproject.com/en/1.3/ref/contrib/markup/ A: You can...
how to use markdown with django? by only in 2 tags
I want to use markdown with django. I want to allow use bold and strike tags. Others don't convert. Please teach me.
[ "Django supports Markdown, but you'll need to install the Python package: http://docs.djangoproject.com/en/1.3/ref/contrib/markup/\n", "You can take a look at markdown2 for converting text to html. But if you just want to use bold and strike, maybe you should look for using directly regex/parser.\nA \"secure\" mo...
[ 2, 0 ]
[]
[]
[ "django", "markdown", "python" ]
stackoverflow_0006068847_django_markdown_python.txt
Q: How to configure Python with lighttpd and fastcgi? How to configure Python with lighttpd and fastcgi ? Can anybody give me config files ? A: My serverconfig module can set that up. But it's made to work with a particular framework.
How to configure Python with lighttpd and fastcgi?
How to configure Python with lighttpd and fastcgi ? Can anybody give me config files ?
[ "My serverconfig module can set that up. But it's made to work with a particular framework. \n" ]
[ 1 ]
[]
[]
[ "fastcgi", "lighttpd", "python" ]
stackoverflow_0006068896_fastcgi_lighttpd_python.txt
Q: Find / Generate documentation for Gtk, Gdk, GdkPixbuf, Where can I find proper documentation on the Python objects Gtk, Gdk,... from gi.repository ? I'm stuck with using dir() and it's of the utmost annoyance... To sum it up: heelp! (NOTE: the pygtk doc is too outdated, I'm using pygobject) A: I haven't found o...
Find / Generate documentation for Gtk, Gdk, GdkPixbuf,
Where can I find proper documentation on the Python objects Gtk, Gdk,... from gi.repository ? I'm stuck with using dir() and it's of the utmost annoyance... To sum it up: heelp! (NOTE: the pygtk doc is too outdated, I'm using pygobject)
[ "I haven't found online documentation but you can use the help command from python interactive prompt, like:\n>>> import gi\n>>> help(gi)\n\nHelp on package gi:\n\nNAME\n gi\n\nFILE\n /usr/lib/pymodules/python2.6/gtk-2.0/gi/__init__.py\n\nDESCRIPTION\n...\n\n", "The GTK/GDK documentation can be found here: ...
[ 2, 0 ]
[]
[]
[ "documentation", "pygobject", "python" ]
stackoverflow_0006064798_documentation_pygobject_python.txt
Q: wxpython - Creating Unique GUI Elements With a Loop I am attempting to create a GUI with a large amount of items where there are several sets of the same thing (six labels and six radioboxes). What I want to do (to save space and for a learning experience) is to create some sort of loop to place these elements on ...
wxpython - Creating Unique GUI Elements With a Loop
I am attempting to create a GUI with a large amount of items where there are several sets of the same thing (six labels and six radioboxes). What I want to do (to save space and for a learning experience) is to create some sort of loop to place these elements on the panel I am using. Actually placing these should be ea...
[ "Its been a while since I've done any wxPython coding so I'm a little rusty, but off the top of my head I can think of two ways of doing this other than neurino's solution, although there are other variations. \n\nMethod 1\nKeep references to each widget in a dictionary, using the widgets label as the key, eg \nrbo...
[ 2, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006068739_python_wxpython.txt
Q: How to sort a list by checking values in a sublist in python? I have a list of lists in the following format: [['a',[10]], ['b',[1]], ['c',[5,10]], ['d',[5,1,-10]], ['e',[5,1,-1]]] I would like to sort if in an efficient way in python using the numeric list elements, matching the first element, and when it is the...
How to sort a list by checking values in a sublist in python?
I have a list of lists in the following format: [['a',[10]], ['b',[1]], ['c',[5,10]], ['d',[5,1,-10]], ['e',[5,1,-1]]] I would like to sort if in an efficient way in python using the numeric list elements, matching the first element, and when it is the same, use the second, and so on. The result would be something lik...
[ "I think lists compare like you want, by default, if inverted:\n>>> data = [['a',[10]], ['b',[1]], ['c',[5,10]], ['d',[5,1,-10]], ['e',[5,1,-1]]\n>>> sorted(data, reverse = True, key = lambda pair: pair[1])\n[['a', [10]], ['c', [5, 10]], ['e', [5, 1, -1]], ['d', [5, 1, -10]], ['b', [1]]]\n\nYou had a bracketing err...
[ 5, 1, 0 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0006069093_list_python_sorting.txt
Q: Capturing browser specific rendering of a webpage? Is there any way to capture (image, pdf etc) how a webpage will look like in lets say chrome or I.E? I am guessing there will be different ways to do this for different browsers but is there any API, library or addon that does this? A: Use selenium webdriver (h...
Capturing browser specific rendering of a webpage?
Is there any way to capture (image, pdf etc) how a webpage will look like in lets say chrome or I.E? I am guessing there will be different ways to do this for different browsers but is there any API, library or addon that does this?
[ "Use selenium webdriver (has a python api) to remote control a browser and take a screenshot. Supports all major browsers as far as I'm aware.\n", "Yes there are few wonderful websites providing this service and also some kinds of primitive to some advanced API services for capturing browser screenshots.\nBrowser...
[ 3, 2 ]
[]
[]
[ "firefox", "internet_explorer", "python", "webpage_screenshot" ]
stackoverflow_0006070211_firefox_internet_explorer_python_webpage_screenshot.txt
Q: Issue with SqlAlchemy - "Parent instance is not bound to a Session; lazy load operation..." I have a small thrift server in python that I use do some fast lookups. The server queries mysql via SqlAlchemy on the first request and shoves all returned objects into a dictionary so on subsequent requests no DB call is...
Issue with SqlAlchemy - "Parent instance is not bound to a Session; lazy load operation..."
I have a small thrift server in python that I use do some fast lookups. The server queries mysql via SqlAlchemy on the first request and shoves all returned objects into a dictionary so on subsequent requests no DB call is needed. I just get the object from the dict and then call some of the object methods needed to gi...
[ "You probably cache objects between the requests, and when the commit happens, session object is getting cleared, invalidating your objects. If you start your server via some multithreaded web server that starts workers as needed, that explains why there's no pattern.\nIf you dont want to get the bottom of this and...
[ 10 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0004253176_python_sqlalchemy.txt
Q: Explanation of python code snippet >>numpy.nonzero(row == max(row))[0][0]<< from a script using numpy What does this peace of python code row = R[i,] j = numpy.nonzero(row == max(row))[0][0] do, assuming this output: command # output of python ---------------------------------- R.shape # (224, 24) type(R) #...
Explanation of python code snippet >>numpy.nonzero(row == max(row))[0][0]<< from a script using numpy
What does this peace of python code row = R[i,] j = numpy.nonzero(row == max(row))[0][0] do, assuming this output: command # output of python ---------------------------------- R.shape # (224, 24) type(R) # <type 'numpy.ndarray'> type(row) # <type 'numpy.ndarray'> type(j) # <type 'numpy.int64'> (I'll provide ...
[ "The two lines appear to be a roundabout way of saying j = np.argmax(R[i]), i.e. find the column index of the largest element in the i-th row of R, and store the result in j.\n", "Perhaps an example will help:\nIn []: R= arange(12).reshape(4, 3)\nIn []: R\nOut[]: \narray([[ 0, 1, 2],\n [ 3, 4, 5],\n ...
[ 8, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006070542_numpy_python.txt
Q: nth order fourier series curve fitting in Python I've been looking for a way to code a snippet in Python which calculate for any n-th order of Fourier series curve fitting. To calculate a certain order of Fourier series curve fitting, say 3 order is quite simple, however to do it where the order n is variable, sti...
nth order fourier series curve fitting in Python
I've been looking for a way to code a snippet in Python which calculate for any n-th order of Fourier series curve fitting. To calculate a certain order of Fourier series curve fitting, say 3 order is quite simple, however to do it where the order n is variable, still not workable yet. Perhaps somebody has done it, but...
[]
[]
[ "Well the formula is \nn-th cos_coeff = (2/T)*integral(-T/2,T/2, f(t)*cos(n*t*2*pi/2)dt)\nn-th sin coeff = (2/T)*integral(-T/2,T/2, f(t)*sin(n*t*2*pi/2)dt)\n\nCheck scypi and scipy.integrate for details on integration.\nHere it should be\ncos_coeff(f, T, N) = (2/T)*quad(lambda t: f(t)*cos(N*t*2*math.pi/2),-T/2,T/2)...
[ -2 ]
[ "curve_fitting", "fft", "python" ]
stackoverflow_0006069936_curve_fitting_fft_python.txt
Q: Align TeX equations in matplotlib I have the following lines to annotate TeX on my matplotlib plot: import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) rc('font', family='serif') r = 1 v = 2 i = 3 notes = r"\noindent$R_L = {0}\\ V_2 = {1}\\ I_2 = {2}$".format(r, v, i) plt.annotate(...
Align TeX equations in matplotlib
I have the following lines to annotate TeX on my matplotlib plot: import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) rc('font', family='serif') r = 1 v = 2 i = 3 notes = r"\noindent$R_L = {0}\\ V_2 = {1}\\ I_2 = {2}$".format(r, v, i) plt.annotate(notes, xy=(5,5), xytext=(7,7)) plt.show...
[ "Use eqnarray.\nA simplified version of your code:\n#!/usr/bin/python\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\n\nrc('text', usetex=True)\nrc('font', family='serif')\n\nr = 1\nv = 2\ni = 3\n\nplt.plot([1,2,3],[2,3,4],'ro-')\n\nplt.text(2,2,r\"\\begin{eqnarray*}R_L&= 0\\\\ V_2&= 1\\\\ I_2&= 2\\end...
[ 4 ]
[]
[]
[ "alignment", "math", "matplotlib", "python", "tex" ]
stackoverflow_0006068827_alignment_math_matplotlib_python_tex.txt
Q: Python - cant access a variable within the class I have a basic python question. I'm working on a class foo and I use __init__(): to do some actions on a value: class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet When I e...
Python - cant access a variable within the class
I have a basic python question. I'm working on a class foo and I use __init__(): to do some actions on a value: class foo(): def __init__(self,bar=None): self.bar=bar if bar is None: isSet=False else: isSet=True print isSet When I execute the code I get: NameError: name 'isSet' is not ...
[ "Wrong indentation, it should be this instead, otherwise you're exiting the function.\nclass foo():\n def __init__(self,bar=None):\n self.bar=bar\n\n if bar is None: \n isSet=False \n else:\n isSet=True\n\n print isSet\n\n", "It depends on what you are trying to do. You probably want isS...
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006069690_python.txt
Q: Python "myfirst.py" fails to "import mySecond.py". Both resources are in same package "test" My main module was loaded with 'execFile', then i'm trying to import a .py module which is located in the same package as both my Runner java class as the main .py module. But i'm not succeeding yet. My scenario; My packag...
Python "myfirst.py" fails to "import mySecond.py". Both resources are in same package "test"
My main module was loaded with 'execFile', then i'm trying to import a .py module which is located in the same package as both my Runner java class as the main .py module. But i'm not succeeding yet. My scenario; My package structure: / /test/ /test/Runner.java /test/myfirst.py /test/mySecond.py /test/__ini...
[ "An answer for your update.\nYou can use a standalone Jython.jar that contains the libs.\nYou can get this jar by installing jython in standalone mode, or simply by copying the lib directory in the root of the standard Jython jar.\nA reference on that : Jython FAQ on distributing scripts\n", "It sounds like Pytho...
[ 2, 1 ]
[]
[]
[ "import", "java", "jython", "python", "resources" ]
stackoverflow_0006058945_import_java_jython_python_resources.txt
Q: how to create a between matrix calculations class in python? I am trying to create a class that will be able to make all possible calculations between matrix. the input is a matrix (doesn't matter the size), and on that matrix the class should do any calculations - either multiply, combine or substract. The differ...
how to create a between matrix calculations class in python?
I am trying to create a class that will be able to make all possible calculations between matrix. the input is a matrix (doesn't matter the size), and on that matrix the class should do any calculations - either multiply, combine or substract. The different functions are as follow: I need to have in this class: __init_...
[ "Do you need to create this yourself? If not, there is already an excellent implementation of this in numpy\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006071648_python.txt
Q: I am looking for a vxml (voicexml) parser in python language I am looking for a vxml (voicexml) parser in python language. Need to use the parsed vxml tags and interact with freeswitch to run IVR. Can anyone help me with any kind of opensource vxml parsers? A: Isn't any standard XML parser enough? You could just...
I am looking for a vxml (voicexml) parser in python language
I am looking for a vxml (voicexml) parser in python language. Need to use the parsed vxml tags and interact with freeswitch to run IVR. Can anyone help me with any kind of opensource vxml parsers?
[ "Isn't any standard XML parser enough? You could just write a quick wrapper to get the elemenents you're interested in (although xpath will also do that for you).\nTo verify correctness, the VXML schema / definition should be enough (as long as your chosen XML parser supports them)\nIf XML parser is too low level, ...
[ 1 ]
[]
[]
[ "freeswitch", "ivr", "parsing", "python", "vxml" ]
stackoverflow_0006071395_freeswitch_ivr_parsing_python_vxml.txt
Q: Can I print HTML as it would be viewed in a web page without tags in python? I want to print html to a document but I want it formatted as it would be viewed in a web page. I have the following code: from BeautifulSoup import BeautifulSoup, NavigableString html = """ <B>THIS IS A TABLE</B> </div> <center> <table...
Can I print HTML as it would be viewed in a web page without tags in python?
I want to print html to a document but I want it formatted as it would be viewed in a web page. I have the following code: from BeautifulSoup import BeautifulSoup, NavigableString html = """ <B>THIS IS A TABLE</B> </div> <center> <table width="100%" align="center" cellspacing="0" cellpadding="0" border="0" style="fon...
[ "Assuming you really do want to write this as a text file, you could look into using lynx as a renderer for html to text.\nIf you just want to be able to open the html file you wrote and have it appear exactly as it would in a web browser, I suggest saving it as tmp.html and opening it with a web browser.\n", ".....
[ 3, 0 ]
[]
[]
[ "html", "printing", "python", "webpage" ]
stackoverflow_0006071638_html_printing_python_webpage.txt
Q: entropy minimization for inhomogeneity correction in python Does somebody know about a entropy minimization implementation in python? I want to use this to correct inhomogeneity in histology images. Reference about the algorithm I am talking about. A: I suspect that you'll have to hack something together yoursel...
entropy minimization for inhomogeneity correction in python
Does somebody know about a entropy minimization implementation in python? I want to use this to correct inhomogeneity in histology images. Reference about the algorithm I am talking about.
[ "I suspect that you'll have to hack something together yourself, maybe using PIL and pyentropy.\n" ]
[ 0 ]
[]
[]
[ "entropy", "python" ]
stackoverflow_0006070996_entropy_python.txt
Q: how to deal with japanese word using python xlrd this is my code: #!/usr/bin/python #-*-coding:utf-8-*- import xlrd,sys,re data = xlrd.open_workbook('a.xls',encoding_override="utf-8") a = data.sheets()[0] s='' for i in range(a.nrows): if 9<i<20: #stage print a.row_values(i)[1].decode('...
how to deal with japanese word using python xlrd
this is my code: #!/usr/bin/python #-*-coding:utf-8-*- import xlrd,sys,re data = xlrd.open_workbook('a.xls',encoding_override="utf-8") a = data.sheets()[0] s='' for i in range(a.nrows): if 9<i<20: #stage print a.row_values(i)[1].decode('shift_jis')+'\n' but it show : ???? ???????? ?????? ??...
[ "Background: In a \"modern\" (Excel 97-2003) XLS file, text is effectively stored as Unicode. In older files, text is stored as 8-bit strings, and a \"codepage\" record tells how it is encoded e.g. the integer 1252 corresponds to the encoding known as cp1252 or windows-1252. In either case, xlrd presents extracted ...
[ 2, 0 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0006069476_python_xlrd.txt
Q: Best Python framework for embedded system ( memory 64MB, HD 256MB) I have one doubt. I need to write site on embedded system ( memory 64MB, HD 256MB ), I already have Python there and SQLite. I thought to use Django for this, but I heard that Django uses memory a lot. What framework is the best choice for me ( I n...
Best Python framework for embedded system ( memory 64MB, HD 256MB)
I have one doubt. I need to write site on embedded system ( memory 64MB, HD 256MB ), I already have Python there and SQLite. I thought to use Django for this, but I heard that Django uses memory a lot. What framework is the best choice for me ( I need to have session and access to sqlite )?
[ "If you need only simple features, the embedded http server of python simplehttpserver it a good choice.\nIf you need more advanced features, it seems that CherryPy is a serious candidate as an embedded WebServer as it is able to run on an android platform.\n" ]
[ 4 ]
[]
[]
[ "cherrypy", "django", "python" ]
stackoverflow_0006072135_cherrypy_django_python.txt
Q: Creating a Dictionary from a List of 2-Tuples I have a list of 2-tuples like this: l = [('a', 1), ('b', 2)] and I want to be able to map this onto a dictionary object, so that I can do something like l.a #=> 1 So I tried this, but why does it fail? d = reduce(lambda y,x : y.update({x[0]:x[1]}),l,{}) This gives...
Creating a Dictionary from a List of 2-Tuples
I have a list of 2-tuples like this: l = [('a', 1), ('b', 2)] and I want to be able to map this onto a dictionary object, so that I can do something like l.a #=> 1 So I tried this, but why does it fail? d = reduce(lambda y,x : y.update({x[0]:x[1]}),l,{}) This gives the error: AttributeError: 'NoneType' object has ...
[ ">>> l = [('a', 1), ('b', 2)]\n>>> d = dict(l)\n>>> d['a']\n1 \n\n", "Why not just do this:\nd = dict(l)\n\nAlso, to answer your question, your solution is failing because y (which is a 2-tuple) has no method update, since it's not a dict. Thankfully, what you're doing is built right in.\n" ]
[ 21, 4 ]
[]
[]
[ "dictionary", "python", "reduce" ]
stackoverflow_0006072470_dictionary_python_reduce.txt
Q: Enabling appliances with web2py on GAE Hi I'm trying web2py for a simple web app I deployed to app engine. I can access the admin interface at /admin but it won't accept me uploading appliances / applications ie those files named .w2p. It says "unable to install application " even though the application is stated ...
Enabling appliances with web2py on GAE
Hi I'm trying web2py for a simple web app I deployed to app engine. I can access the admin interface at /admin but it won't accept me uploading appliances / applications ie those files named .w2p. It says "unable to install application " even though the application is stated to be compatible with web2py on GAE. I tried...
[ "The GAE filesystem is read-only, so you're not going to be able to use the web2py admin interface to upload/unpack .w2p files (the admin application is expecting to be able to unzip the .w2p file into a filesystem, which it cannot do on GAE). You also will not be able to edit files via the admin interface on GAE. ...
[ 3 ]
[]
[]
[ "google_app_engine", "python", "web2py" ]
stackoverflow_0006071348_google_app_engine_python_web2py.txt
Q: how to know the progress of each thread? im new in python and i have created an uploading program with multi threading, my problem is i have only one progress bar that displays the progress of each thread. im using python pyqt4 QThread. Is there a way to know whats the progress of each uploading thread? here are s...
how to know the progress of each thread?
im new in python and i have created an uploading program with multi threading, my problem is i have only one progress bar that displays the progress of each thread. im using python pyqt4 QThread. Is there a way to know whats the progress of each uploading thread? here are some parts of the code. class Worker(QThread): ...
[ "You need to create a counter object that's shared between all threads. Each time a thread completes a download it locks with a QMutex increments the count and unlocks you can then send your signal and modify the progress bar(although you may want to make sure it doesn't update too often)\n" ]
[ 2 ]
[]
[]
[ "pyqt4", "python", "qthread" ]
stackoverflow_0006066746_pyqt4_python_qthread.txt
Q: Unpickling problem in python under apache (mod_python) I'm writing a web application that talks over network socket to a server that I develop in python. To simplify things I decided to pack the data into a class and transfer it after pickling. To test the concept I've written a code that pickles the class and unp...
Unpickling problem in python under apache (mod_python)
I'm writing a web application that talks over network socket to a server that I develop in python. To simplify things I decided to pack the data into a class and transfer it after pickling. To test the concept I've written a code that pickles the class and unpickles it but it doesn't work. Same code runs in python inte...
[ "Yes, this is the case.\nYou cannot easily use pickled classes, functions or class instances with mod_python.\nThis document describes the problem from the point of view of Sessions, but still applies to your usage:\nhttp://www.dscpl.com.au/wiki/ModPython/Articles/IssuesWithSessionObjects\nBasic problem:\n\nThe sou...
[ 1 ]
[]
[]
[ "apache", "pickle", "python" ]
stackoverflow_0006072845_apache_pickle_python.txt
Q: Batching datastore ancestor-queries Let's say I have: class ParentKind(db.Model): """These are the parents.""" class ChildKind(db.Model): """Children. Their parents are ParentKind objects.""" I then create different parent objects, parent_1 and parent_2. How can I query 5 children op parent_1 and 10 chil...
Batching datastore ancestor-queries
Let's say I have: class ParentKind(db.Model): """These are the parents.""" class ChildKind(db.Model): """Children. Their parents are ParentKind objects.""" I then create different parent objects, parent_1 and parent_2. How can I query 5 children op parent_1 and 10 children of parent_2 in one query? (e.g. an o...
[ "You can't. You'd have to run this as 2 queries and merge the results locally.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0006073022_google_app_engine_google_cloud_datastore_python.txt
Q: django forms and filtering So i have this jobs select form that should allow a user to: 1) select a filterBy set of radio buttons. This lets the user select which method he wants to filter a list by. (this will perform a GET with a 'filterBy' query string 2) allow a user to filter the list by an object from a co...
django forms and filtering
So i have this jobs select form that should allow a user to: 1) select a filterBy set of radio buttons. This lets the user select which method he wants to filter a list by. (this will perform a GET with a 'filterBy' query string 2) allow a user to filter the list by an object from a comobox that is the result of #1. ...
[ "Use request.REQUEST (see: Django Request and Response Objects). It holds the values of both request.POST and request.GET. \nAlso, when using dictionaries in Python, you should always verify that the key you're trying to access exists. This can be done in one of two ways:\n1) Explicitly test for key in dictionary\n...
[ 1, 0 ]
[]
[]
[ "django", "filtering", "python", "query_string" ]
stackoverflow_0006072836_django_filtering_python_query_string.txt
Q: Python Library for Browser-Based Twitter Oauth I would love to find a Python library for Twitter that supports a browser-based application type, so the user can just hit "authorize" and have Twitter return them to the callback url, as opposed to copying and pasting a PIN number. I've tried just about every library...
Python Library for Browser-Based Twitter Oauth
I would love to find a Python library for Twitter that supports a browser-based application type, so the user can just hit "authorize" and have Twitter return them to the callback url, as opposed to copying and pasting a PIN number. I've tried just about every library, and they all rely on the PIN method.
[ "I'm pretty sure tweepy allows the redirect method: http://code.google.com/p/tweepy/\n" ]
[ 0 ]
[]
[]
[ "oauth", "python", "twitter" ]
stackoverflow_0006073537_oauth_python_twitter.txt
Q: Python ctypes return values question Why if i have this simple code void voidFunct() { printf("voidFunct called!!!\n"); } I compile it as a dynamic library with gcc -c LSB.c -o LSB.o gcc -shared -Wl -o libLSB.so.1 LSB.o And i call function from a python interpreter, using ctypes >>> from ctypes import * ...
Python ctypes return values question
Why if i have this simple code void voidFunct() { printf("voidFunct called!!!\n"); } I compile it as a dynamic library with gcc -c LSB.c -o LSB.o gcc -shared -Wl -o libLSB.so.1 LSB.o And i call function from a python interpreter, using ctypes >>> from ctypes import * >>> dll = CDLL("./libLSB.so.1") >>> return...
[ "From the docs:\n\nclass ctypes.CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)\n\nInstances of this class represent loaded shared libraries. Functions in these libraries use the standard C calling convention, and are assumed to return int.\n\nIn short, you defined voidFunct() as a...
[ 33, 7 ]
[]
[]
[ "ctypes", "dynamic_library", "python", "return_value" ]
stackoverflow_0006073599_ctypes_dynamic_library_python_return_value.txt
Q: Regex: Match brackets both greedy and non greedy I'm using python regular expression module, re . I need to match anything inside '(' ')' on this two phrases, but "not so greedy". Like this: show the (name) of the (person) calc the sqrt of (+ (* (2 4) 3)) The result should return, from phrase 1: name person The...
Regex: Match brackets both greedy and non greedy
I'm using python regular expression module, re . I need to match anything inside '(' ')' on this two phrases, but "not so greedy". Like this: show the (name) of the (person) calc the sqrt of (+ (* (2 4) 3)) The result should return, from phrase 1: name person The result should return from phrase 2: + (* (2 4) 3) Th...
[ "Pyparsing makes it easy to write simple one-off parsers for stuff like this:\n>>> text = \"\"\"show the (name) of the (person)\n...\n... calc the sqrt of (+ (* (2 4) 3))\"\"\"\n>>> import pyparsing\n>>> for match in pyparsing.nestedExpr('(',')').searchString(text):\n... print match[0]\n...\n['name']\n['person']\...
[ 7, 0, 0 ]
[ "As long as the brackets are not nested, you can use a lazy regex:\n\\(.*?\\)\n\nWhile you can theoretically parse a limited amount of nesting in a regex, it's very hard and not worth the effort. It's much easier to do that using a custom python function. See this answer for a good explanation.\n" ]
[ -3 ]
[ "python", "regex", "regex_greedy" ]
stackoverflow_0006071784_python_regex_regex_greedy.txt
Q: Python script not working in linux I have this python script #!/usr/bin/env python import datetime, os from time import gmtime, strftime to_backup = "/home/vmware/tobackup" var1 = datetime.datetime.now().strftime('%b-%d-%I%p') for f in os.listdir(to_backup): if(os.path.isfile(f)): print f + " is a fil...
Python script not working in linux
I have this python script #!/usr/bin/env python import datetime, os from time import gmtime, strftime to_backup = "/home/vmware/tobackup" var1 = datetime.datetime.now().strftime('%b-%d-%I%p') for f in os.listdir(to_backup): if(os.path.isfile(f)): print f + " is a file" if(os.path.isdir(f)): pri...
[ "Ok you have permission, but you aren't in the right directory when you list through the files. list_dir gives you a list of dirs/files without their path, and os.path.isfile('one') and os.path.isdir('one') will check whether the directory 'one' exists in the current directory (wherever you launched the script fro...
[ 5, 4, 2 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0006073188_linux_python.txt
Q: Automation Excel From Python getting "TypeError: 'unicode' object is not callable" on Range.Address As per the Title, when I run the below code in Python 2.6 I get the below error on line: print range.Address(RowAbsolute=False, ColumnAbsolute=False)" I know what the error means but the MSDN page (http://msdn.m...
Automation Excel From Python getting "TypeError: 'unicode' object is not callable" on Range.Address
As per the Title, when I run the below code in Python 2.6 I get the below error on line: print range.Address(RowAbsolute=False, ColumnAbsolute=False)" I know what the error means but the MSDN page (http://msdn.microsoft.com/en-us/library/aa174749(v=office.11).aspx) said this is valid and has an example in it. I hav...
[ "Range.Address is a parameterized property. It provides a value when accessed like a property, but can be called like a method with parameters as well. PyWin32 does not support parameterized properties directly. It works around this by providing a GetXXXXX method for each property that supports parameters. Use:...
[ 4 ]
[]
[]
[ "com", "excel", "python" ]
stackoverflow_0006072851_com_excel_python.txt
Q: django compound querysets I have this filtering mechanism that works, however, it is not very elegant. There has to be a better way to write this. Any recommendations would be greatly appreciated. The user is able to select from multiple filters to filter the list: forms.py class FilterForm(forms.Form): def ...
django compound querysets
I have this filtering mechanism that works, however, it is not very elegant. There has to be a better way to write this. Any recommendations would be greatly appreciated. The user is able to select from multiple filters to filter the list: forms.py class FilterForm(forms.Form): def __init__(self, *args, **kwargs)...
[ "initial = dict(request.POST)\n# The dictionary key is the field name retrieved from the POST request\n# The first list item is the model to query\n# The second list item is the \"jobs\" field to query\ndict_models = {'group': [Group, 'group']],\n 'host': [Host, 'host'],\n 'location': [Location, 'colo'],\n ...
[ 2, 1 ]
[]
[]
[ "django", "django_queryset", "forms", "python" ]
stackoverflow_0006073754_django_django_queryset_forms_python.txt
Q: Matplotlib histogram with log Laplacian PDF (be sure to check out the EDIT at the end of the post before reading too deeply into the source) I'm plotting a histogram of a population that seems to be of log Laplacian distribution: I'm trying to draw a line of best fit for it to verify my hypothesis, but I'm having...
Matplotlib histogram with log Laplacian PDF
(be sure to check out the EDIT at the end of the post before reading too deeply into the source) I'm plotting a histogram of a population that seems to be of log Laplacian distribution: I'm trying to draw a line of best fit for it to verify my hypothesis, but I'm having problems getting meaningful results. I'm using t...
[ "\nYour laplace() function does not seem to be a Laplace distribution. Besides, numpy.log() is a natural logarithm (base e), not decimal.\nYour histogram does not seem to be normalized, while the distribution is. \n\nEDIT:\n\nDon't use blanket imports from pyplot import *, it'll bite you.\nIf you're checking consi...
[ 1, 1 ]
[]
[]
[ "histogram", "matplotlib", "python" ]
stackoverflow_0006068873_histogram_matplotlib_python.txt
Q: sending object (recursive data structures) by XML-RPC in python I need to send an object through XML-RPC in python. My object consist of composite data type to populate a tree structure: class Node(object): '''Composite data type ''' def __init__(self, pData, pParent=None): self.mData = pData self.mParent ...
sending object (recursive data structures) by XML-RPC in python
I need to send an object through XML-RPC in python. My object consist of composite data type to populate a tree structure: class Node(object): '''Composite data type ''' def __init__(self, pData, pParent=None): self.mData = pData self.mParent = pParent self.mChildren = [] self.mParent is reference to its p...
[ "Look at \nhttp://www.xs4all.nl/~irmen/pyro3/\nwhen you want to transfer Python objects over the wire. \nSince XMLRPC is based on XML -as the name implies - you can not transfer Python objects over the wire without serialization.\n" ]
[ 1 ]
[]
[]
[ "composite", "python", "recursive_datastructures", "xml_rpc", "xmlrpclib" ]
stackoverflow_0006074047_composite_python_recursive_datastructures_xml_rpc_xmlrpclib.txt
Q: redirecting system call output in python I wish to execute os.system('ls') in python. the return value of this statement is an error code integer..but I want to get the contents of the present directory as a string. How to accomplish this? A: os.listdir(".") In general, if you want to call a function and get t...
redirecting system call output in python
I wish to execute os.system('ls') in python. the return value of this statement is an error code integer..but I want to get the contents of the present directory as a string. How to accomplish this?
[ "os.listdir(\".\")\n\nIn general, if you want to call a function and get the arguments, you should use subprocess.Popen(). But a lot of the basic directory stuff is in the os module so you don't have to do that.\n", "Python as build-in functionality like os.listdir() or os.walk() for listing stuff\non the filesys...
[ 2, 0 ]
[]
[]
[ "pipe", "python", "redirect", "system_calls" ]
stackoverflow_0006074034_pipe_python_redirect_system_calls.txt
Q: Get a json dictionary from xml file Possible Duplicate: easiest way to parse xml in python I need to parse a file which looks like an xml file but have no XML declaration. Here is an example of XML file: <connection name="name_1"> <parameter name="user" value="user_value_1"/> <parameter name="password" value...
Get a json dictionary from xml file
Possible Duplicate: easiest way to parse xml in python I need to parse a file which looks like an xml file but have no XML declaration. Here is an example of XML file: <connection name="name_1"> <parameter name="user" value="user_value_1"/> <parameter name="password" value="psw_1"/> </connection> <connection nam...
[ "Your XML is invalid and won't be parsed properly, as it doesn't contain a main element. Here's a valid version:\n<connections>\n <connection name=\"name_1\">\n <parameter name=\"user\" value=\"user_value_1\"/>\n <parameter name=\"password\" value=\"psw_1\"/>\n </connection>\n\n <connection name=\"name_2\"...
[ 2 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0006074176_python_xml.txt
Q: Interacting with a gtk.container while gtk.main() is executing? Experimenting with a battery monitor icon at the moment in Python using pygtk and egg.trayicon to create an icon to display a battery icon/tooltip. I seem to be able to add the icon and the tooltip text, but when it then reaches the gtk.main() stage I...
Interacting with a gtk.container while gtk.main() is executing?
Experimenting with a battery monitor icon at the moment in Python using pygtk and egg.trayicon to create an icon to display a battery icon/tooltip. I seem to be able to add the icon and the tooltip text, but when it then reaches the gtk.main() stage I need a way to modify these so it can then show the updated values. I...
[ "This example works for me:\n# -*- Mode: Python -*-\n# vi:si:et:sw=4:sts=4:ts=4\n\nimport gobject\nimport gtk\nfrom egg import trayicon\n\nlabel = gtk.Label(\"Over here\")\n\ndef callback(widget, ev):\n label.set_text(\"You found me\")\n\ndef timeout():\n label.set_text(\"What are you waiting for?\")\n\ntray ...
[ 3 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0006072639_gtk_pygtk_python.txt
Q: Make a list of a class's methods and dynamically call the methods on the class Is it possible to get a list of class's methods and then invoke the methods on an instance of the class? I have come across code that makes a list of a class's methods, but I haven't found an example that also invokes the methods on an...
Make a list of a class's methods and dynamically call the methods on the class
Is it possible to get a list of class's methods and then invoke the methods on an instance of the class? I have come across code that makes a list of a class's methods, but I haven't found an example that also invokes the methods on an instance of the class. Given the class: class Test: def methodOne(self): pri...
[ "Use getattr(a,methodname) to access the actual method, given the string name, methodname:\nimport inspect\nimport types\n\nclass Test(object):\n def methodOne(self):\n print('one')\n def methodTwo(self):\n print('two')\n\na = Test() \nmethodList = [n for n, v in inspect.getmembers(a, inspect.ismet...
[ 9, 2, 2, 1 ]
[ "for method in methodList: eval (\"a.%s()\" % method)\n\nFor method without parameters except self.\n" ]
[ -3 ]
[ "class", "methods", "python" ]
stackoverflow_0006074122_class_methods_python.txt
Q: how to scroll a Tix ScrolledWindow Using Python, how can I programmatically scroll (not using the scrollbars) the window in a Tix ScrolledWindow? The normal way would be to call xview / yview, but those calls do not seem to be available. Googling suggest that it is not possible at all, but I hope for something bet...
how to scroll a Tix ScrolledWindow
Using Python, how can I programmatically scroll (not using the scrollbars) the window in a Tix ScrolledWindow? The normal way would be to call xview / yview, but those calls do not seem to be available. Googling suggest that it is not possible at all, but I hope for something better.
[ "st = tix.ScrolledText(parent)\nst.text.see('end')\n\n" ]
[ 0 ]
[]
[]
[ "python", "scrolledwindow", "tix" ]
stackoverflow_0004256280_python_scrolledwindow_tix.txt
Q: Installing Python modules with local Python build I have python 2.7 installed locally in ~/Python2.7/ and I need the psycopg2 module. But when I try to install it with easy_install or compile it manually, I get error: invalid Python installation: unable to open /usr/local/lib/python2.7/config/Makefile (No such fil...
Installing Python modules with local Python build
I have python 2.7 installed locally in ~/Python2.7/ and I need the psycopg2 module. But when I try to install it with easy_install or compile it manually, I get error: invalid Python installation: unable to open /usr/local/lib/python2.7/config/Makefile (No such file or directory) I tried to change a line in ~/Python2....
[ "Check the command line options: http://packages.python.org/distribute/easy_install.html#command-line-options and try fiddling around with your --install-dir . The local install would also need to be in the PYTHONPATH environment variable. If you are trying to install everything locally, try using pip, instead of...
[ 2 ]
[]
[]
[ "python", "python_module" ]
stackoverflow_0006074606_python_python_module.txt
Q: Using optparse in Python Is there a way I can configure optparse in Python to not take the beginning -? So instead of %program -d optionvalue I get %program d optionvalue Currently, when I try to do parser.add_option('d', '--database') i get the following error: optparse.OptionError: invalid option string 'd': ...
Using optparse in Python
Is there a way I can configure optparse in Python to not take the beginning -? So instead of %program -d optionvalue I get %program d optionvalue Currently, when I try to do parser.add_option('d', '--database') i get the following error: optparse.OptionError: invalid option string 'd': must be at least two character...
[ "In short, no.\n\nan argument used to supply extra\n information to guide or customize the\n execution of a program. There are many\n different syntaxes for options; the\n traditional Unix syntax is a hyphen\n (“-“) followed by a single letter,\n e.g. -x or -F. Also, traditional Unix\n syntax allows multiple...
[ 6, 1, 0 ]
[]
[]
[ "command_line_arguments", "customization", "optparse", "python" ]
stackoverflow_0006066596_command_line_arguments_customization_optparse_python.txt