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: Area under a parabola revisited I was unable to go from the previous question because I was not a member of the website so I was unable to comment on it when I returned. Here is my question: To find the area of a region bounded by the graph y=x^2 and the x-axis on the interval [a,b] we can approximate the region b...
Area under a parabola revisited
I was unable to go from the previous question because I was not a member of the website so I was unable to comment on it when I returned. Here is my question: To find the area of a region bounded by the graph y=x^2 and the x-axis on the interval [a,b] we can approximate the region by drawing a number of "thin" rectangl...
[ "Okay, by changing the function to y = x and trying some known input values, I conclude that it works fine:\n0 .. 1 => 0.5\n0 .. 2 => 2.0\n1 .. 2 => 1.5\n0 .. 9 => 40.5\n\nIf you want it all in one function, just get rid of parabola(), remove the first parameter from the approx_area() function (and call), then c...
[ 3, 1 ]
[]
[]
[ "python", "sage" ]
stackoverflow_0004476091_python_sage.txt
Q: Qscrollarea do not display scollbar and layouts pops out of place I spent last night trying to get this QScrollArea to work without any luck. What I am trying to do is to add a top horizontal menu layout and a scrollable vertical content layout beneath the menu. The scrollbar is not visible and the content layout ...
Qscrollarea do not display scollbar and layouts pops out of place
I spent last night trying to get this QScrollArea to work without any luck. What I am trying to do is to add a top horizontal menu layout and a scrollable vertical content layout beneath the menu. The scrollbar is not visible and the content layout pops out of place as soon as I add new elements to it (by click one of ...
[ "This looks wrong:\nself.scrollArea = QtGui.QScrollArea() \nself.scrollArea.setWidget( self.lowerWidget ) \n\nlayout.addWidget( self.lowerWidget )\n\nYou add lowerWidget to the scrollarea, just to add it to the layout in the next step, which removes lowerWidget from the scrollarea and reparent its top lev...
[ 3 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0004476072_pyqt_python_qt.txt
Q: django, what is related_name for? and how do i create shared columns to use across project? I was trying to design a model in django with some auditing fields. Such as created at, created by, updated at and updated by. Those four columns are going to be repeated across all my models in different applications. My ...
django, what is related_name for? and how do i create shared columns to use across project?
I was trying to design a model in django with some auditing fields. Such as created at, created by, updated at and updated by. Those four columns are going to be repeated across all my models in different applications. My first question, is there a way to put those columns and can include them in my class each time i ...
[ "Try this: \nclass AbstractClass(models.Model):\n created_at=models.DateField(\"Created at\")\n created_by=models.ForeignKey(User, db_column=\"created_by\", related_name=\"poll_user_created_by\")\n updated_at=models.DateTimeField(\"Updated at\")\n updated_by=models.ForeignKey(User, db_column=\"updated_...
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004479103_django_python.txt
Q: How to stop infinite recursion when Python objects trigger each other's updates? I'm using PyGTK and the gtk.Assistant widget. On one page I have six comboboxes, which initially have the same contents (six numbers). When the users selects a number in one of those comboboxes, this number should no longer be availab...
How to stop infinite recursion when Python objects trigger each other's updates?
I'm using PyGTK and the gtk.Assistant widget. On one page I have six comboboxes, which initially have the same contents (six numbers). When the users selects a number in one of those comboboxes, this number should no longer be available in the other five boxes (unless it's present as a duplicate in the original list). ...
[ "The simplest fix for this sort of problem is generally to figure out if you're going to need to change the contents of the object (the combobox, in your case) and then only apply changes if you're actually changing something. This way you'll only propagate update events as far as they do something.\nThis should lo...
[ 3 ]
[]
[]
[ "exit", "pygtk", "python", "recursion" ]
stackoverflow_0004479185_exit_pygtk_python_recursion.txt
Q: Different Python versions on single PC I want to install different versions of Python (and related packages and IDEs) on a single PC and keep them independent. I like the pythonxy but runs on Python 2.6, but I also wat to try Eric5 with Python3.1. How can I keep thess different install separated ? A: On Windows...
Different Python versions on single PC
I want to install different versions of Python (and related packages and IDEs) on a single PC and keep them independent. I like the pythonxy but runs on Python 2.6, but I also wat to try Eric5 with Python3.1. How can I keep thess different install separated ?
[ "On Windows, this is trivial. You just install both, they get put in different directories.\nOn Linux, this is less so, but still fairly simple. Install from source, and use make altinstall instead of make install.\n" ]
[ 1 ]
[]
[]
[ "installation", "python" ]
stackoverflow_0004479295_installation_python.txt
Q: Invalid Block Tag i=0, in Django I was going through Appengine's Getting Started guide for python, while reading up templates,I modified the code(which is a simple guestbook) to include simple numbering next to the guestbook entries. In index.html i added the (what I thought would be) relevant code. index.html (I...
Invalid Block Tag i=0, in Django
I was going through Appengine's Getting Started guide for python, while reading up templates,I modified the code(which is a simple guestbook) to include simple numbering next to the guestbook entries. In index.html i added the (what I thought would be) relevant code. index.html (I have added {%i=0%} on line 3,{%i+=1%}...
[ "From http://www.djangobook.com/en/beta/chapter04/\n{% for item in todo_list %}\n <p>{{ forloop.counter }}: {{ item }}</p>\n{% endfor %}\n\n", "It depends on what you need it for. If you need the actual count, you can use a for loop in the template: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#...
[ 2, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0004479317_django_google_app_engine_python.txt
Q: Virtualenvwrapper .hook: Permission Denied I've used virtualenvwrapper previously, but I'm having problems running it on a new computer. My .bashrc file is updated per the instructions: export WORKON_HOME=$DEV_HOME/projects source /usr/local/bin/virtualenvwrapper.sh But when source is run, I get the following: ...
Virtualenvwrapper .hook: Permission Denied
I've used virtualenvwrapper previously, but I'm having problems running it on a new computer. My .bashrc file is updated per the instructions: export WORKON_HOME=$DEV_HOME/projects source /usr/local/bin/virtualenvwrapper.sh But when source is run, I get the following: bash: /25009.hook: Permission denied bash: /2500...
[ "Try storing your virtualenvs directory somewhere you are guaranteed not to have any permissions errors (and maybe even try using the absolute path). Also, are you sure you created the 'projects' directory manually? \nFor reference, my bashrc file looks something like this:\nexport WORKON_HOME=/srv/.virtualenvs/\ne...
[ 1 ]
[]
[]
[ "dollar_sign", "python", "virtualenv", "wrapper" ]
stackoverflow_0002597257_dollar_sign_python_virtualenv_wrapper.txt
Q: Django - Python: Spawn a process and return I've been searching for an answer to this for awhile, it's possible that I haven't been searching for the right information though. I'm trying to send data to a server, and once received the server executes a python script based on that data. I have been trying to spawn ...
Django - Python: Spawn a process and return
I've been searching for an answer to this for awhile, it's possible that I haven't been searching for the right information though. I'm trying to send data to a server, and once received the server executes a python script based on that data. I have been trying to spawn a thread and return, but I can't figure out how t...
[ "Have a look at Celery. It's quite nice in that you can accept the request, and it offload it quickly to workers, and return. It's simple to use.\nhttp://celeryproject.org/\n", "Most simply, you can do this with subprocess.Popen. See here for some information regarding the subprocess module:\nhttp://docs.pyth...
[ 3, 1, 1 ]
[]
[]
[ "django", "multithreading", "python" ]
stackoverflow_0004475048_django_multithreading_python.txt
Q: Python-for statements understanding I am a little confused as to what a for statement does/works in python. Can anyone be able to explain to me on how it works? A: For loops allow you to express a repetitive action. For example, if we want to print a list we could do the following: mylist = ['apples', 'oranges...
Python-for statements understanding
I am a little confused as to what a for statement does/works in python. Can anyone be able to explain to me on how it works?
[ "For loops allow you to express a repetitive action. \nFor example, if we want to print a list we could do the following:\nmylist = ['apples', 'oranges', 'pears']\n\nitem = mylist[0]\nprint item\n\nitem = mylist[1]\nprint item\n\nitem = mylist[2]\nprint item\n\nThis can be expressed more concisely, as follows:\nmyl...
[ 4, 2, 1, 1, 0 ]
[]
[]
[ "python", "sage" ]
stackoverflow_0004479069_python_sage.txt
Q: Is pylons project alive? I am wondering what is status of pylons. I currently know sth about django and trying to learn sth new and found pylons might be a good next step but it is still active? I mean it don't have sense to learn sth which is not currently active and supported for begginers so here is my questio...
Is pylons project alive?
I am wondering what is status of pylons. I currently know sth about django and trying to learn sth new and found pylons might be a good next step but it is still active? I mean it don't have sense to learn sth which is not currently active and supported for begginers so here is my question. Best regards
[ "Yes, it's very much alive, and recent developments are highly exciting:\nhttp://docs.pylonsproject.org/en/latest/docs/pyramid.html\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0004479833_python.txt
Q: How to implement an "undo" feature using Python/Django I have a Django application where I allow a user to import a CSV file with contact data (membership #, first name, last name, etc). When they import the file, the application checks the database for a matching record and either: 1) inserts a new record if no ...
How to implement an "undo" feature using Python/Django
I have a Django application where I allow a user to import a CSV file with contact data (membership #, first name, last name, etc). When they import the file, the application checks the database for a matching record and either: 1) inserts a new record if no match exists, or 2) updates the existing data with the new d...
[ "Take a look at django-reversion. It provides version control for Django models. Can be easily added to existing project.\nIt doesn't employ \"current\" pointer approach. Instead, it serializes object each time it's being saved and stores it in a separate Version model with generic foreign key pointing to this obje...
[ 11, 3, 1 ]
[]
[]
[ "django", "python", "undo", "undo_redo" ]
stackoverflow_0004479781_django_python_undo_undo_redo.txt
Q: Partially transparent scatter plot, but with a solid color bar In Python, with Matplotlib, how to simply do a scatter plot with transparency (alpha < 1), but with a color bar that represents their color value, but has alpha = 1? Here is what one gets, with from pylab import *; scatter(range(10), arange(0, 100, 10)...
Partially transparent scatter plot, but with a solid color bar
In Python, with Matplotlib, how to simply do a scatter plot with transparency (alpha < 1), but with a color bar that represents their color value, but has alpha = 1? Here is what one gets, with from pylab import *; scatter(range(10), arange(0, 100, 10), c=range(10), alpha=0.2); color_bar = colorbar(): How can the colo...
[ "Alright, I found one way to do it, that looks relatively clean: (using the ColorBar object from the question)\ncolor_bar.set_alpha(1)\ncolor_bar.draw_all()\n# pylab.draw() or pyplot.draw() might be necessary\n\nIt would be great to get a confirmation that this is the most robust way to proceed, though! :)\n", "T...
[ 44, 15 ]
[]
[]
[ "colorbar", "matplotlib", "python", "scatter" ]
stackoverflow_0004478725_colorbar_matplotlib_python_scatter.txt
Q: Python GStreamer webcam viewer I'working on this nice example that shows a webcam output in a GTK widget with python and GStreamer: http://pygstdocs.berlios.de/pygst-tutorial/webcam-viewer.html here is the code: #!/usr/bin/env python import sys, os import pygtk, gtk, gobject import pygst pygst.require("0.10") imp...
Python GStreamer webcam viewer
I'working on this nice example that shows a webcam output in a GTK widget with python and GStreamer: http://pygstdocs.berlios.de/pygst-tutorial/webcam-viewer.html here is the code: #!/usr/bin/env python import sys, os import pygtk, gtk, gobject import pygst pygst.require("0.10") import gst class GTK_Main: def __init...
[ "Thanks to OpenCV I managed to rewrite everything with wxPython (which i know better than pyGTK). Here is a full working example (whith snapshot!), if anyone interested.\nAlso checkout the OpenCV wiki here: http://opencv.willowgarage.com/wiki/wxpython\nimport wx\nimport opencv.cv as cv\nimport opencv.highgui as gui...
[ 4, 2 ]
[]
[]
[ "gstreamer", "pygtk", "python" ]
stackoverflow_0003139747_gstreamer_pygtk_python.txt
Q: Posting to Django server from java applet I have to send some string from Java applet(invoked from template) to my django server, what would implementation of java applet part might look like? A: Here's a link to code snippet,which helps you in sending http requests to server http://www.aviransplace.com/2008/01/...
Posting to Django server from java applet
I have to send some string from Java applet(invoked from template) to my django server, what would implementation of java applet part might look like?
[ "Here's a link to code snippet,which helps you in sending http requests to server\nhttp://www.aviransplace.com/2008/01/08/make-http-post-or-get-request-from-java/\n" ]
[ 0 ]
[]
[]
[ "client_side", "django", "java", "python" ]
stackoverflow_0004480624_client_side_django_java_python.txt
Q: Implement Comet / Server push in Google App Engine in Python How can I implement Comet / Server push in Google App Engine in Python? A: We just announced the Channel API to do comet push with App Engine apps: http://googleappengine.blogspot.com/2010/05/app-engine-at-google-io-2010.html If you're at Google IO, I'...
Implement Comet / Server push in Google App Engine in Python
How can I implement Comet / Server push in Google App Engine in Python?
[ "We just announced the Channel API to do comet push with App Engine apps: http://googleappengine.blogspot.com/2010/05/app-engine-at-google-io-2010.html\nIf you're at Google IO, I'll be talking about this at 1pm tomorrow (on the APIs track): http://code.google.com/events/io/2010/sessions/building-real-time-apps-app-...
[ 69, 3, 2, 1, 0, 0 ]
[]
[]
[ "channel_api", "comet", "google_app_engine", "python", "server_push" ]
stackoverflow_0001285150_channel_api_comet_google_app_engine_python_server_push.txt
Q: How come I'm getting this Python error in my code? import urllib, urllib2 def URLRequest(url, params, method="GET"): if method == "POST": return urllib2.Request(url, data=urllib.encode(params)) <<<< 31 else: return urllib2.Request(url + "?" + urllib.encode(params)) 'module' object has no ...
How come I'm getting this Python error in my code?
import urllib, urllib2 def URLRequest(url, params, method="GET"): if method == "POST": return urllib2.Request(url, data=urllib.encode(params)) <<<< 31 else: return urllib2.Request(url + "?" + urllib.encode(params)) 'module' object has no attribute 'encode', line 31
[ "The error message is correct: the urllib module does not have an encode() function. The function name is urlencode(), so you would call:\nurllib.urlencode(params)\n\nPython docs for the function: http://docs.python.org/library/urllib.html#urllib.urlencode\n" ]
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0004480867_python.txt
Q: Print list items with a header If I have a list defined as list=['Ford','Mustang','1966','red'] and try to print it my output would look like: Ford Mustang 1966 red But how can I achieve to have a heading so the output would look like: Brand Modell Year Color Ford Mustang 1966 Red That would look much more profes...
Print list items with a header
If I have a list defined as list=['Ford','Mustang','1966','red'] and try to print it my output would look like: Ford Mustang 1966 red But how can I achieve to have a heading so the output would look like: Brand Modell Year Color Ford Mustang 1966 Red That would look much more professional.
[ "LAYOUT = \"{!s:10} {!s:14} {!s:4} {!s:10}\"\n\nyourList = [\"Ford\",\"Mustang\",1966,\"Red\"]\n\nprint LAYOUT.format(\"Brand\",\"Modell\",\"Year\",\"Color\")\nprint LAYOUT.format(*yourList)\n\nproduces output in columns which will line up (so long as you don't exceed the field width specifiers!), ie\nBrand Mo...
[ 6, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004479200_list_python.txt
Q: Improving BeautifulSoup Perf SO I have the following set of code parsing delicious information. It prints data from a Delicious page in the following format Bookmark | Number of People Bookmark | Number of People etc... I used to use the following method to find this info. def extract (soup): links = soup.fi...
Improving BeautifulSoup Perf
SO I have the following set of code parsing delicious information. It prints data from a Delicious page in the following format Bookmark | Number of People Bookmark | Number of People etc... I used to use the following method to find this info. def extract (soup): links = soup.findAll('a',rel='nofollow') for ...
[ "I don't understand why you are assigning to vote – twice. The first assignment is unnecessary and indeed quite heavy, since it must parse the whole document – on each iteration. Why?\n vote = BeautifulSoup(html)\n vote = bookmark.findAll('span', attrs={'class': 'delNavCount'})\n\n", "If you are concerned abo...
[ 3, 3, 0 ]
[]
[]
[ "beautifulsoup", "delicious_api", "mechanize", "python", "web_crawler" ]
stackoverflow_0004481424_beautifulsoup_delicious_api_mechanize_python_web_crawler.txt
Q: How can I listen for a mouse event in Python on Mac? I need to listen for global mouse events(not bound to an app) on my Mac in an app written in Python. I'm using PyObjC, but I can't figure out how to do it. Plain ObjC examples or other Python techniques also appreciated. My code so far: from Quartz import * def ...
How can I listen for a mouse event in Python on Mac?
I need to listen for global mouse events(not bound to an app) on my Mac in an app written in Python. I'm using PyObjC, but I can't figure out how to do it. Plain ObjC examples or other Python techniques also appreciated. My code so far: from Quartz import * def MyFunction(proxy, type, event): print event CGEventTa...
[ "The fourth parameter of CGEventTapCreate is CGEventMask eventsOfInterest, and you gave it kCGEventLeftMouseDown which is an enum of type _CGEventType. Instead of the integer constant, you need to flip the appropriate bit in the bitmask. You can do this using CGEventMaskBit\nSo instead of this:\ntap = CGEventTapCre...
[ 3, 1 ]
[ "First, CGEventTapCreate and CGEventTapCreateForPSN leak some memory when they\nare called. This is needed to avoid memory management problems. It is therefore\nadvisable not to call these functions, are at least call them a small number\nof times.\nNow, a mouse event works something like this:\nevt = CGEventCreate...
[ -1 ]
[ "mouseevent", "objective_c", "pyobjc", "python" ]
stackoverflow_0002337196_mouseevent_objective_c_pyobjc_python.txt
Q: Understanding the implementation of Euclid's Algorithm for GCF in Python Euclid's Algorithm for GCF of two numbers is: GCF(a, b)=GCF(b, a mod b). I have seen this implemented in Python as follows: def gcf(a, b): return b and gcf(b, a%b) or a I don't understand how to parse this function or specifically how ...
Understanding the implementation of Euclid's Algorithm for GCF in Python
Euclid's Algorithm for GCF of two numbers is: GCF(a, b)=GCF(b, a mod b). I have seen this implemented in Python as follows: def gcf(a, b): return b and gcf(b, a%b) or a I don't understand how to parse this function or specifically how boolean logic is applied to integers. For example, gcf(42, 56) = 14. When I wa...
[ "Python boolean operators 'or' and 'and' don't return boolean values. They return one of the values they are comparing.\n0 or n - returns n\n0 and n - returns 0\na and b or c is just a trick to implement the (a ? b : c) syntax in C.\nRead section 4.6 of Dive into Python for a great description of python's boolean o...
[ 2, 1, 1, 0 ]
[]
[]
[ "algorithm", "factorization", "python" ]
stackoverflow_0004481313_algorithm_factorization_python.txt
Q: Python + Mechanize Async Tasks So I have this bit of python code that runs through a delicious page and scrapes some links off of it. The extract method contains some magic that pull out the required content. However, running the page fetches one after another is pretty slow - is there a way to do this async in py...
Python + Mechanize Async Tasks
So I have this bit of python code that runs through a delicious page and scrapes some links off of it. The extract method contains some magic that pull out the required content. However, running the page fetches one after another is pretty slow - is there a way to do this async in python so i can launch several get req...
[ "Beautiful Soup is pretty slow, if you want better performance use lxml instead or if you have many CPU's perhaps you can try using multiprocessing with queues.\n" ]
[ 1 ]
[]
[]
[ "mechanize", "multithreading", "python", "scrape", "web_crawler" ]
stackoverflow_0004481049_mechanize_multithreading_python_scrape_web_crawler.txt
Q: Understanding Python Classes or Customising the Django UserAdmin model I'm attempting to override some of the behaviour of the Django UserAdmin model. Particularly, I'd like to hide the 'superuser' field from non-superusers. So, my approach is this: class ModelAdmin(BaseModelAdmin): "Encapsulates all admin op...
Understanding Python Classes or Customising the Django UserAdmin model
I'm attempting to override some of the behaviour of the Django UserAdmin model. Particularly, I'd like to hide the 'superuser' field from non-superusers. So, my approach is this: class ModelAdmin(BaseModelAdmin): "Encapsulates all admin options and functionality for a given model." # ... def has_change_p...
[ "If you just want to forbid users to promote themselves to superuser, override YourUserAdmin.get_readonly_fields():\nclass YourUserAdmin(admin.ModelAdmin):\n ...\n def get_readonly_fields(self, request, obj=None):\n if request.user.is_superuser:\n return None\n try:\n retur...
[ 1, 0 ]
[]
[]
[ "django_admin", "django_models", "python" ]
stackoverflow_0004321001_django_admin_django_models_python.txt
Q: Division by zero: int vs. float Dividing an int by zero, will throw an exception, but a float won't - at least in Java. Why does a float have additional NaN info, while an int type doesn't? A: The representation of a float has been designed such that there are some special combination of bits reserved to store s...
Division by zero: int vs. float
Dividing an int by zero, will throw an exception, but a float won't - at least in Java. Why does a float have additional NaN info, while an int type doesn't?
[ "The representation of a float has been designed such that there are some special combination of bits reserved to store special values such as NaN, infinity, etc.\nThere are no unused representations for an int type - every bit pattern corresponds to an integer. This has many advantages:\n\nThe range of an integer ...
[ 8, 3, 1, 1, 1, 1 ]
[]
[]
[ "c#", "java", "math", "python", "vb.net" ]
stackoverflow_0004480020_c#_java_math_python_vb.net.txt
Q: Watching a property for changes I need a function similar to gobject.io_add_watch but for a variable. For example it needs to watch the variable stop initialized to stop = False and when stop is changed to True it must call a function. I can't have a separate thread watching the variable in a loop with a time.slee...
Watching a property for changes
I need a function similar to gobject.io_add_watch but for a variable. For example it needs to watch the variable stop initialized to stop = False and when stop is changed to True it must call a function. I can't have a separate thread watching the variable in a loop with a time.sleep. Is there such a function or a way ...
[ "Use a property in a class:\nclass Stopwatch(object):\n def __init__(self, callback):\n self._stop = False\n self.callback = callback\n\n @property\n def stop(self): return self._stop\n\n @stop.setter\n def stop(self, value):\n self._stop = value\n if value: self.callback(...
[ 20 ]
[]
[]
[ "python", "variables", "watch" ]
stackoverflow_0004481844_python_variables_watch.txt
Q: Minimizing a Tk Window I have a window I made with Tkinter, I'd like to be able to minimize it. This is in Windows 7 FYI. A: >>> import Tkinter >>> w = Tkinter.Tk() >>> w.wm_state('iconic') Should work and minimize the window to the taskbar. To minimize it to the taskbar as a button: w.iconify()
Minimizing a Tk Window
I have a window I made with Tkinter, I'd like to be able to minimize it. This is in Windows 7 FYI.
[ ">>> import Tkinter\n>>> w = Tkinter.Tk()\n>>> w.wm_state('iconic')\n\nShould work and minimize the window to the taskbar.\nTo minimize it to the taskbar as a button:\nw.iconify()\n\n" ]
[ 22 ]
[]
[]
[ "python", "tkinter", "windows_7" ]
stackoverflow_0004481880_python_tkinter_windows_7.txt
Q: Migrating from CPython to Jython I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code. Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar? From readin...
Migrating from CPython to Jython
I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code. Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar? From reading the Jython site, most of the problem...
[ "First off, I have to say the Jython implementation is very good. Most things \"just work\". \nHere are a few things that I have encountered:\n\nC modules are not available, of course. \nopen('file').read() doesn't automatically close the file. This has to do with the difference in the garbage collector. This can c...
[ 10, 8, 5, 3, 3, 2 ]
[]
[]
[ "cpython", "jython", "migration", "python" ]
stackoverflow_0000420792_cpython_jython_migration_python.txt
Q: What is the best django app that can allow users to log in using their twitter account? I'd like to allow users to login into my Django site via their Twitter account. What are my options? A: Django-SocialAuth can help you. Here are link with example project and docs. http://uswaretech.com/blog/2009/08/django-...
What is the best django app that can allow users to log in using their twitter account?
I'd like to allow users to login into my Django site via their Twitter account. What are my options?
[ "Django-SocialAuth can help you.\nHere are link with example project and docs. \nhttp://uswaretech.com/blog/2009/08/django-socialauth-login-via-twitter-facebook-openid-yahoo-google/\n" ]
[ 1 ]
[]
[]
[ "django", "python", "twitter" ]
stackoverflow_0004481849_django_python_twitter.txt
Q: How to send binary file via REST in Python? I'm trying to upload a PDF file for docstoc but I haven't got any luck. I've tried the restclient library for python but I have no idead how to upload/send a binary file lika a PDF. Could you guys provide examples on how to do this? I'd really appreciate it. A: I see t...
How to send binary file via REST in Python?
I'm trying to upload a PDF file for docstoc but I haven't got any luck. I've tried the restclient library for python but I have no idead how to upload/send a binary file lika a PDF. Could you guys provide examples on how to do this? I'd really appreciate it.
[ "I see that is has been asked before. The idea is treat PDF as another file, but send the file as multipart/form-data. This answer here points you to two recipes which can be used to accomplish this. \n" ]
[ 0 ]
[]
[]
[ "python", "rest" ]
stackoverflow_0004481945_python_rest.txt
Q: String Sort based on some Format I have a string which needs to be sorted based on the sort_fmt. Ex: If the string is 'abdcdfs' & the sort_fmt is 'dacg'. Upon sort, the output should be 'ddacfbs'. As you see, there might be characters in input string that are not present in the order string and vice-versa. The cha...
String Sort based on some Format
I have a string which needs to be sorted based on the sort_fmt. Ex: If the string is 'abdcdfs' & the sort_fmt is 'dacg'. Upon sort, the output should be 'ddacfbs'. As you see, there might be characters in input string that are not present in the order string and vice-versa. The characters of input string that are not p...
[ "You are trying to implement counting sort which is indeed O(n) under certain conditions. However your implementation has two bugs near the end which mean that the actual time complexity of your implementation is O(n2 + n*m):\nfor ch in s:\n if ch not in sort_fmt: # <--- \"in\" requires a linear search. O(n*m)\...
[ 6, 0 ]
[]
[]
[ "python", "sorting", "string" ]
stackoverflow_0004482453_python_sorting_string.txt
Q: How can google app engine report progress back on file upload I have been trying to use an ajax-style file upload component (like the dojox file upload component) with google app engine, and have a progress bar. The javascript side of things is fine, but i am wondering how to organise things on the server side? ...
How can google app engine report progress back on file upload
I have been trying to use an ajax-style file upload component (like the dojox file upload component) with google app engine, and have a progress bar. The javascript side of things is fine, but i am wondering how to organise things on the server side? Is is possible to access the data as it is being uploaded within go...
[ "You can limit file size on a client site using swfupload. \nIt's a flash component with javascript api that exposes flash uploading capabilities.\nThe check of a file size is done in the client browser. (in function CheckFileSize) \nThe library has also other goodies like progress bar, check it home page for full...
[ 1, 1, 1 ]
[]
[]
[ "google_app_engine", "progress_bar", "python" ]
stackoverflow_0001515978_google_app_engine_progress_bar_python.txt
Q: not enough arguments passed to __init__() What is the error below? Also, is there a better way to implement the following classes? #!/usr/bin/python class Datacenters: def __init__(self,name,location,cpu,mem): self.name=name self.location=location self.cpu=cpu ...
not enough arguments passed to __init__()
What is the error below? Also, is there a better way to implement the following classes? #!/usr/bin/python class Datacenters: def __init__(self,name,location,cpu,mem): self.name=name self.location=location self.cpu=cpu self.mem=mem def getparam(se...
[ "The error is that you pass in five arguments, but the __init__ needs six. Count them:\ndef __init__(self,name,location,cpu,mem,obj):\n\nSix arguments. You call it like so:\nWS.__init__(obj,name,location,cpu,mem)\n\nFive arguments. The first one, self is missing. What you should ask yourself is why you don't have ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004482682_python.txt
Q: How to access static members of outer class from an inner class constructor? How to get this to work: class ABC(object): C1 = 1 class DEF(object): def __init__(self, v=ABC.C1): self.v = v a = ABC() From the inner class DEF, I cannot access the constant "C1". I tried with "ABC.C1" and...
How to access static members of outer class from an inner class constructor?
How to get this to work: class ABC(object): C1 = 1 class DEF(object): def __init__(self, v=ABC.C1): self.v = v a = ABC() From the inner class DEF, I cannot access the constant "C1". I tried with "ABC.C1" and "C1" alone but to no avail. Please advise.
[ "I advice you to not nest classes. Why do you do that? There is no reason to do that, ever. This works:\n>>> class ABC(object):\n... C1 = 1\n... \n>>> class DEF(object):\n... def __init__(self, v=ABC.C1):\n... self.v = v\n... \n>>> a = ABC()\n>>> d = DEF()\n>>> d.v\n1\n\nThe reason your code doesn...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004482672_python.txt
Q: embeding a list in class property and calling it's values If I have class as following: class theater: def __init__(self): self.__seatMatrix=[10]*5 self.__seats=seating[0] self.__rows=len(seating) How can I implement a get/setter to update the values for seats? The idea is that seating...
embeding a list in class property and calling it's values
If I have class as following: class theater: def __init__(self): self.__seatMatrix=[10]*5 self.__seats=seating[0] self.__rows=len(seating) How can I implement a get/setter to update the values for seats? The idea is that seating=[10]*5, 5 rows with 10 seats. I've been turning my head around...
[ "Don't forget the return statement in your function implementation. Unlike some other languages, Python does not automatically return the last expression that was evaluated in the function. The return value from a function with no return statement is None.\nIn this case, your getseats() method should be:\ndef getse...
[ 4, 1, 1 ]
[]
[]
[ "class", "list", "python" ]
stackoverflow_0004482878_class_list_python.txt
Q: How to execute python code from within a python method? I'm writing a deployment engine for our code. I plan to put a "deploy.py" in each project directory and then decide what projects need to be deployed, having the "deploy.py" of each project execute his logic for proper deployment configuration. How would you...
How to execute python code from within a python method?
I'm writing a deployment engine for our code. I plan to put a "deploy.py" in each project directory and then decide what projects need to be deployed, having the "deploy.py" of each project execute his logic for proper deployment configuration. How would you recommend doing this? I've been thinking about "executing" t...
[ "You can use the __import__ function to do dynamic imports.\n" ]
[ 2 ]
[]
[]
[ "continuous_integration", "deployment", "python" ]
stackoverflow_0004482966_continuous_integration_deployment_python.txt
Q: Python/Tkinter: Using the new ttk.Notebook widget (custom font, trapping tab focus/mouseover) I'm using the new ttk.Notebook widget available in Python 2.7 and Python 3.1. I'm struggling with the following tasks: How to change the font associated with notebook tab captions. I want to use a named font object whose...
Python/Tkinter: Using the new ttk.Notebook widget (custom font, trapping tab focus/mouseover)
I'm using the new ttk.Notebook widget available in Python 2.7 and Python 3.1. I'm struggling with the following tasks: How to change the font associated with notebook tab captions. I want to use a named font object whose size a user controls. (Could a ttk.Style help me here?) How can I bind to tab specific keyboard fo...
[]
[]
[ "We're actually answering these questions in the Tkinter mailing list; in fact, I have mixed feelings about saying anything in Stackoverflow apart from, \"See the mailing list\". It's surely fair to note, though, that this answers the question about fonts, and this heads a thread on tab events. \n" ]
[ -1 ]
[ "python", "tkinter", "ttk" ]
stackoverflow_0004451378_python_tkinter_ttk.txt
Q: uploading file in django and python? <input type="file" name="doc-file" multiple/> file_path = request.FILES.get('doc-file') My return value of file_path is None But when I do file_path = request.POST.get('doc-file') it returns filename . What is the best way to upload a file in python and django? A: It...
uploading file in django and python?
<input type="file" name="doc-file" multiple/> file_path = request.FILES.get('doc-file') My return value of file_path is None But when I do file_path = request.POST.get('doc-file') it returns filename . What is the best way to upload a file in python and django?
[ "It sounds like you might be forgetting to include enctype=\"multipart/form-data\" in your form tag. See Django's docs on file uploads for details.\nEdit: formatting\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004483020_django_python.txt
Q: change the label of the radiobutton I'm creating a menu in Tkinter. After my menu has been created I'd like to be able to change the label of the radiobutton. Something similar to the .configure method. How do I go about this? I want to be able to change the radiobuttons text from "Hello" to "Hello!". Snippet: ...
change the label of the radiobutton
I'm creating a menu in Tkinter. After my menu has been created I'd like to be able to change the label of the radiobutton. Something similar to the .configure method. How do I go about this? I want to be able to change the radiobuttons text from "Hello" to "Hello!". Snippet: self.B3Me = Tkinter.Menu(self, tearoff...
[ "To modify the label use the entryconfig method. You give this method an index which can be the integer position of the item, or the label itself. For example:\nself.B3Me.entryconfig(\"Hello\", label=\"Goodbye!\")\n\n" ]
[ 1 ]
[]
[]
[ "python", "radio_button", "tkinter", "tkinter_menu" ]
stackoverflow_0004482055_python_radio_button_tkinter_tkinter_menu.txt
Q: Is this the right way to write a POST function in Python? def URLRequest(url, params, method="POST"): h = Http() res, content = h.request(url, method, urllib.urlencode(params)) r = {} r['res'] = res r['content'] = content return r Suppose I want to POST {"key":"value"} to a url (REST). Is ...
Is this the right way to write a POST function in Python?
def URLRequest(url, params, method="POST"): h = Http() res, content = h.request(url, method, urllib.urlencode(params)) r = {} r['res'] = res r['content'] = content return r Suppose I want to POST {"key":"value"} to a url (REST). Is this function the right way to do it?
[ "If it works it is correct. You can make it shorter though:\ndef URLRequest(url, params, method=\"POST\"):\n res, content = Http().request(url, method, urllib.urlencode(params))\n return {'res':res, 'content':content}\n\n" ]
[ 2 ]
[]
[]
[ "http", "post", "python" ]
stackoverflow_0004483032_http_post_python.txt
Q: How to encrypt my data on the server side using django This is my demand: User content is ultimately stored on the server side, but the preservation of data is encrypted Server side, that is, site technical staff, can not have any way to decrypt the contents of the user, as the user's password as stored on the s...
How to encrypt my data on the server side using django
This is my demand: User content is ultimately stored on the server side, but the preservation of data is encrypted Server side, that is, site technical staff, can not have any way to decrypt the contents of the user, as the user's password as stored on the server side is a long list of md5 encrypted characters. For en...
[ "Encrypt and decrypt on the client, never store key in the server side.\nSee jsencryption for an example of client side encryption.\n", "If you use javascript obfuscator chances are high it might be cracked, obfuscation is not encryption.\nYou should hash the conten on the serverside using md5. \nCan you be more ...
[ 1, 0 ]
[]
[]
[ "django", "javascript", "jquery", "python" ]
stackoverflow_0004481944_django_javascript_jquery_python.txt
Q: Search and merge objects by its parameters I'm trying to create a method to merge multiple parametrized configuration file sections into one. Each section can have specific section parameters and contains a payload of configuration variables. There is an examples of a few sections: [MySection] foo = defaultbar...
Search and merge objects by its parameters
I'm trying to create a method to merge multiple parametrized configuration file sections into one. Each section can have specific section parameters and contains a payload of configuration variables. There is an examples of a few sections: [MySection] foo = defaultbar [MySection|color=red|shape=circle] foo = b...
[ "This will merge them in order, with the last one being the most important:\nparameters = {}\nparameters.update(sections[0])\nparameters.update(sections[6])\nparameters.update(sections[1])\nparameters.update(sections[3])\nparameters.update(sections[5])\nparameters.update(sections[4])\nparameters.update(sections[7])...
[ 0 ]
[]
[]
[ "python", "search" ]
stackoverflow_0004482910_python_search.txt
Q: How can I accurately gauge the CPU time of a python process? I'm designing a distributed system where a master node starts a bunch of worker nodes on remote machines. Since I am using Python and want to take advantage of the fact each physical machine has several cores, I want to run multiple worker nodes per mach...
How can I accurately gauge the CPU time of a python process?
I'm designing a distributed system where a master node starts a bunch of worker nodes on remote machines. Since I am using Python and want to take advantage of the fact each physical machine has several cores, I want to run multiple worker nodes per machine (GIL etc). Additionally, each worker node may vary quite a bit...
[ "The quick answer, at least for linux, is to use getrusage along with a kernel that has a higher resolution timer. \nThe reason my initial tests gave the terrible precision of 10ms was because apparently 64-bit ubuntu is configured to a 100hz timer by default.\n" ]
[ 1 ]
[]
[]
[ "python", "timing" ]
stackoverflow_0004483182_python_timing.txt
Q: Failed to get the HTTP POST request body using Twisted I was trying to get the HTTP POST request body by using t.p.basic.LineReceiver but failed. My code is listed below: from twisted.internet import reactor, protocol from twisted.protocols import basic class PrintPostBody(basic.LineReceiver): def __init__(se...
Failed to get the HTTP POST request body using Twisted
I was trying to get the HTTP POST request body by using t.p.basic.LineReceiver but failed. My code is listed below: from twisted.internet import reactor, protocol from twisted.protocols import basic class PrintPostBody(basic.LineReceiver): def __init__(self): self.line_no = 0 def lineReceived(self, li...
[ "I suspect you didn't see the request body printed out because it didn't contain any newlines or end with a newline. So it got into the parse buffer of your PrintPostBody instance and sat there forever, waiting for a newline to indicate that a full line had been received. LineReceiver won't call the lineReceived ...
[ 7 ]
[]
[]
[ "http", "python", "twisted" ]
stackoverflow_0004481644_http_python_twisted.txt
Q: Download images from Mechanical Turk I have a bunch of urls in Mechanical Turk where I can download the uploaded images from. I wrote a Python script to download all the files. However, I have to be logged in to Mechanical Turk to access the files first. Is there an API or best practice for downloading a large ...
Download images from Mechanical Turk
I have a bunch of urls in Mechanical Turk where I can download the uploaded images from. I wrote a Python script to download all the files. However, I have to be logged in to Mechanical Turk to access the files first. Is there an API or best practice for downloading a large number of files from Mechanical Turk?
[ "Boto http://boto.cloudhackers.com/ is a Python wrapper for Amazon Web Services, including Mechanical Turk; see the Mechanical Turk API reference at http://boto.cloudhackers.com/ref/mturk.html\nAlternatively you could use urllib2, mechanize, or Scrapy to grab them directly. All three will support either basic authe...
[ 4 ]
[]
[]
[ "mechanicalturk", "python" ]
stackoverflow_0004483531_mechanicalturk_python.txt
Q: python ... working with numbers I wanted to know if there is another command to make it shorter: noes = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15'] this is the command I use so its has to do with years. A: noes = map(str, range(1, 16)) assuming you really want strings. If n...
python ... working with numbers
I wanted to know if there is another command to make it shorter: noes = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15'] this is the command I use so its has to do with years.
[ "noes = map(str, range(1, 16)) assuming you really want strings. If not, then noes = range(1, 16) will suffice.\n", "If you're after a list of strings, you can use:\n>>> x = [str(n) for n in range(1,16)] # or xrange if you wish\n>>> x\n['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '1...
[ 8, 6, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004483127_python.txt
Q: Error when inheriting an abstract class with foreign keys I have the below code written in django from django.db import models from django.contrib.auth.models import User class AuditColumns(models.Model): created_at=models.DateField("Created at") created_by=models.ForeignKey(User, db_column="created_by", ...
Error when inheriting an abstract class with foreign keys
I have the below code written in django from django.db import models from django.contrib.auth.models import User class AuditColumns(models.Model): created_at=models.DateField("Created at") created_by=models.ForeignKey(User, db_column="created_by", related_name="poll_user_created_by") updated_at=models.Date...
[ "Related names are provided by the Django ORM to enable you to easily find all models that key into the current model. So if you have a key from a Foo to a Bar, the instance of Bar will have, by default, an attribute called foo_set that would give you a list of all Foos that are linked to that specific Bar.\nYou ca...
[ 8 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004483508_django_python.txt
Q: Grabbing non-HTML data from a website using python I'm trying to get the current contract prices on this page to a string: http://www.cmegroup.com/trading/equity-index/us-index/e-mini-sandp500.html I would really like a python 2.6 solution. It was easy to get the page html using urllib, but it seems like this numb...
Grabbing non-HTML data from a website using python
I'm trying to get the current contract prices on this page to a string: http://www.cmegroup.com/trading/equity-index/us-index/e-mini-sandp500.html I would really like a python 2.6 solution. It was easy to get the page html using urllib, but it seems like this number is live and not in the html. I inspected the element...
[ "It looks like the numbers in the table are filled in by Javascript, so just fetching the HTML with urllib or another library won't be enough since they don't run the javascript. You'll need to use a library like PyQt to simulate the browser rendering the page/executing the JS to fill in the numbers, then scrape th...
[ 2, 1, 0 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0004481505_python_python_2.6.txt
Q: Speed of swig wrappers If I were to write several classes in c++ then use swig to do the conversion so I could later use them in python, would they run faster or slower than if I completely rewrote them in python? Or is there no noticable speed difference? A: The quality and speed of wrappers generated by SWIG i...
Speed of swig wrappers
If I were to write several classes in c++ then use swig to do the conversion so I could later use them in python, would they run faster or slower than if I completely rewrote them in python? Or is there no noticable speed difference?
[ "The quality and speed of wrappers generated by SWIG is very good, and they will probably perform just as good as handcrafted wrappers. \nFrom my experience, the wrappers themselves are very thin and add very little overhead to the native functions they wrap, making it a perfectly valid choice to use wrapped librar...
[ 6 ]
[]
[]
[ "c++", "performance", "python", "swig" ]
stackoverflow_0004476663_c++_performance_python_swig.txt
Q: Python garbage collector documentation I'm looking for documents that describes in details how python garbage collection works. I'm interested what is done in which step. What objects are in these 3 collections? What kinds of objects are deleted in each step? What algorithm is used for reference cycles finding? Ba...
Python garbage collector documentation
I'm looking for documents that describes in details how python garbage collection works. I'm interested what is done in which step. What objects are in these 3 collections? What kinds of objects are deleted in each step? What algorithm is used for reference cycles finding? Background: I'm implementing some searches tha...
[ "\nPython Garbage Collection\ngc module docs\nDetails on Garbage Collection for Python\n\nThere's no definitive resource on how Python does its garbage collection (other than the source code itself), but those 3 links should give you a pretty good idea.\nUpdate\nThe source is actually pretty helpful. How much you g...
[ 128 ]
[]
[]
[ "garbage_collection", "python" ]
stackoverflow_0004484167_garbage_collection_python.txt
Q: Designing classes in python I am designing a class which produces information like cpu usage,disk usage,Mem usage,...... for 3 systems,lets say data centers which has many workstations and work stations has many PCs.So the CPU usage and the other parameters are required for all the 3 levels(Datacenters, Workstati...
Designing classes in python
I am designing a class which produces information like cpu usage,disk usage,Mem usage,...... for 3 systems,lets say data centers which has many workstations and work stations has many PCs.So the CPU usage and the other parameters are required for all the 3 levels(Datacenters, Workstations, Pcs). Please suggest is the ...
[ "Some suggestions:\n\nUse 4-spaces indentation\nUse properties instead of getters, provide single properties, not a single one for all parameters (because parameters might be added later or by subclassing). In order to use properties, derive the base class from object (new style classes)\nUse singular class names, ...
[ 3, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004482136_python.txt
Q: Writing XML to file corrupts files in python I'm attempting to write contents from xml.dom.minidom object to file. The simple idea is to use 'writexml' method: import codecs def write_xml_native(): # Building DOM from XML xmldoc = minidom.parse('semio2.xml') f = codecs.open('codified.xml', mode='w', e...
Writing XML to file corrupts files in python
I'm attempting to write contents from xml.dom.minidom object to file. The simple idea is to use 'writexml' method: import codecs def write_xml_native(): # Building DOM from XML xmldoc = minidom.parse('semio2.xml') f = codecs.open('codified.xml', mode='w', encoding='utf-8') # Using native writexml() met...
[ "Hmm, though this should work:\nxml = minidom.parse(\"test.xml\")\nwith codecs.open(\"out.xml\", \"w\", \"utf-8\") as out:\n xml.writexml(out)\n\nyou may alternatively try:\nwith codecs.open(\"test.xml\", \"r\", \"utf-8\") as inp:\n xml = minidom.parseString(inp.read().encode(\"utf-8\"))\nwith codecs.open(\"o...
[ 10, 0 ]
[]
[]
[ "file_io", "minidom", "python", "xml" ]
stackoverflow_0004484228_file_io_minidom_python_xml.txt
Q: What are the benefits of pip and virtualenv? So everyone is telling me to use pip and virtualenv but no-one is able to explain me how it is better than my current approach. The main reason for people to use pip and virtualenv seems to be that everyone else is using it... I'm sure there are very good reasons to use...
What are the benefits of pip and virtualenv?
So everyone is telling me to use pip and virtualenv but no-one is able to explain me how it is better than my current approach. The main reason for people to use pip and virtualenv seems to be that everyone else is using it... I'm sure there are very good reasons to use PIP and virtualenv but I haven't been able to fin...
[ "virtualenv really shines when you have a number of projects, and don't want them to all share the same Python installation. For example, you could have two project with conflicting requirements.\n", "\"All non-python-only dependencies (PIL, psycopg2, ...) are documented in a README and installed at the system l...
[ 19, 9, 3, 2 ]
[]
[]
[ "django", "pip", "python" ]
stackoverflow_0004483888_django_pip_python.txt
Q: Read HEAD contents from HTML i need small script in python. Need to read custom block in a web file. #!/usr/bin/python # -*- coding: utf-8 -*- import urllib2 req = urllib2.Request('http://target.com') response = urllib2.urlopen(req) the_page = response.read() print the_page # Here is all page source with html tag...
Read HEAD contents from HTML
i need small script in python. Need to read custom block in a web file. #!/usr/bin/python # -*- coding: utf-8 -*- import urllib2 req = urllib2.Request('http://target.com') response = urllib2.urlopen(req) the_page = response.read() print the_page # Here is all page source with html tags, but # i need rea...
[ "To parse HTML, we use a parser, such as BeautifulSoup.\nOf course you can parse it using a regular expression, but that is something you should never do. Just because it works for some cases doesn't mean it is the standard way of doing it or is the proper way of doing it. If you are interested in knowing why, read...
[ 1, 0, 0 ]
[]
[]
[ "html", "html_parsing", "python" ]
stackoverflow_0004484357_html_html_parsing_python.txt
Q: Python: Converting ('Monday', 'Tuesday', 'Wednesday') to 'Monday to Wednesday' I'm getting a sequence of day of the week. Python code of what I want to do: def week_days_to_string(week_days): """ >>> week_days_to_string(('Sunday', 'Monday', 'Tuesday')) 'Sunday to Tuesday' >>> week_days_to_string(('...
Python: Converting ('Monday', 'Tuesday', 'Wednesday') to 'Monday to Wednesday'
I'm getting a sequence of day of the week. Python code of what I want to do: def week_days_to_string(week_days): """ >>> week_days_to_string(('Sunday', 'Monday', 'Tuesday')) 'Sunday to Tuesday' >>> week_days_to_string(('Monday', 'Wednesday')) 'Monday and Wednesday' >>> week_days_to_string(('Sund...
[ "I would approach this problem by:\n\nCreating a dict mapping day names to their sequential index\nConverting my input day names to their sequential indices\nLooking at the resulting input indices and asking if they are sequential\n\nHere's how you can do that, using calendar.day_name, range and some for comprehens...
[ 5, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "date", "datetime", "python" ]
stackoverflow_0004482050_date_datetime_python.txt
Q: Invalid literal for int with base 10: '' >>> n = ''.join(i for i in x if i.isdigit()) >>> n.isdigit() True >>> x.isdigit() False >>> previous = 0 >>> next = 100 >>> answer = 0 >>> for i in range(0,100): ... answer += int(n[previous:next]) ... previous = next ... next += 100 ... Traceback (most recen...
Invalid literal for int with base 10: ''
>>> n = ''.join(i for i in x if i.isdigit()) >>> n.isdigit() True >>> x.isdigit() False >>> previous = 0 >>> next = 100 >>> answer = 0 >>> for i in range(0,100): ... answer += int(n[previous:next]) ... previous = next ... next += 100 ... Traceback (most recent call last): File "<stdin>", line 2, in <m...
[ "n might be numeric, but at some stage you're going past the length of n such that n[previous:next] contains no characters at all. The empty string '' cannot be converted to an int, hence the error which tells the full story: invalid literal for int() with base 10: ''.\n>>> int('')\nTraceback (most recent call last...
[ 7 ]
[]
[]
[ "casting", "python", "slice" ]
stackoverflow_0004484728_casting_python_slice.txt
Q: How Enable Extended MQL When Reading From Freebase API Freebase contains a fair amount of documentation but lacks some specific examples of working code for many scenarios. One of them is how to implement (in Python, using the Python Freebase library) a query using their eMQL service. Which is an extended version...
How Enable Extended MQL When Reading From Freebase API
Freebase contains a fair amount of documentation but lacks some specific examples of working code for many scenarios. One of them is how to implement (in Python, using the Python Freebase library) a query using their eMQL service. Which is an extended version of their MQL service. The documentation states that you ne...
[ "And the answer is simple - pass the envelope setting (in this case 'extended=true' to the mqlread function.\nresult = freebase.sandbox.mqlread(query, extended=True)\n\nOf course note the capitalization of T in True.\n" ]
[ 2 ]
[]
[]
[ "freebase", "mql", "python" ]
stackoverflow_0004479748_freebase_mql_python.txt
Q: Adding new forms to a Django formset based on POST data I am trying to populate a Django formset using data from a POST request. I am able to display the formset properly and instantiate it again mostly alright, but I'm having an issue where the formset is ending up with 2 blank rows at the end, which is undesira...
Adding new forms to a Django formset based on POST data
I am trying to populate a Django formset using data from a POST request. I am able to display the formset properly and instantiate it again mostly alright, but I'm having an issue where the formset is ending up with 2 blank rows at the end, which is undesirable. Below is the function we've been using in views.py: for...
[ "In your views.py:\n- formset = DepositFormSet(initial=formset.cleaned_data)\n+ data = formset.cleaned_data\n+ if data[-1]=={}:\n+ data=data[:-1]\n+ formset = DepositFormSet(initial=data)\n\nIt looks pretty much like a feature than like a bug ;)\n", "I've...
[ 2, 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0001948052_django_django_forms_python.txt
Q: How To Escape Characters When Reading JSON I need to write out all the variables in this JSON response: "result": { "\/common\/topic\/weblink": [ { "url": "http:\/\/www.boardgamegeek.com\/boardgame\/13", "description": "BoardGameGeek" } ], "id": "\/en\/settlers_of_catan"...
How To Escape Characters When Reading JSON
I need to write out all the variables in this JSON response: "result": { "\/common\/topic\/weblink": [ { "url": "http:\/\/www.boardgamegeek.com\/boardgame\/13", "description": "BoardGameGeek" } ], "id": "\/en\/settlers_of_catan" } So to get the id: result.id But how do I ...
[ "\"\\/common\\/topic\\/weblink\" resolves to the string /common/topic/weblink. Any API accessing the decoded content should use the resulting unescaped data; the escaping is just part of JSON's encoding.\nThis works fine, using the standard JSON module included in Python, which I strongly recommend you use rather ...
[ 2, 0, 0 ]
[]
[]
[ "freebase", "json", "mql", "python" ]
stackoverflow_0004484762_freebase_json_mql_python.txt
Q: Extract data from HTML in PHP or Python I need to extract this data and display a simple graph out of it. Something like Equity Share Capital -> array (30.36, 17, 17 .... etc) would help. <html:tr> <html:td>Equity Share Capital</html:td> <html:td class="numericalColumn">30.36</html:td> <html:td class="numericalCo...
Extract data from HTML in PHP or Python
I need to extract this data and display a simple graph out of it. Something like Equity Share Capital -> array (30.36, 17, 17 .... etc) would help. <html:tr> <html:td>Equity Share Capital</html:td> <html:td class="numericalColumn">30.36</html:td> <html:td class="numericalColumn">17.17</html:td> <html:td class="numeric...
[ "A good place to start looking would be the python module BeautifulSoup which extracts the text and places it into a table.\nAssuming you've loaded the data into a variable called raw:\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(raw)\n\nfor x in soup.findAll(\"html:td\"):\n if x.string == \"Equ...
[ 5, 2, 2 ]
[]
[]
[ "php", "python" ]
stackoverflow_0004484985_php_python.txt
Q: Running python2.6 selftest.py gives me this error /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python: can't open file 'selftest.py': [Errno 2] No such file or directory When I do which python I get /opt/local/bin/python So the selftest.py is looking in the wrong...
Running python2.6 selftest.py gives me this error
/opt/local/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python: can't open file 'selftest.py': [Errno 2] No such file or directory When I do which python I get /opt/local/bin/python So the selftest.py is looking in the wrong place but how would I fix this? The python manage.py ...
[ "It's hard to tell what is going on without more information, like exactly what you typed and the contents of the selftest.py file. But a more important question is: why are you going to the trouble of installing PIL from scratch? From the the paths you show (/opt/local/) you are apparently already using MacPorts...
[ 0 ]
[]
[]
[ "django", "macos", "python", "python_imaging_library" ]
stackoverflow_0004483526_django_macos_python_python_imaging_library.txt
Q: How can I compress repetitive characters to a single character using RE in Python? I want to be able to replace any consecutive occurrences of punctuation characters in a string with a single occurrence. For example: "I went to the park...." => "I went to the park." "Are you serious??!!???!" => "Are you serious?...
How can I compress repetitive characters to a single character using RE in Python?
I want to be able to replace any consecutive occurrences of punctuation characters in a string with a single occurrence. For example: "I went to the park...." => "I went to the park." "Are you serious??!!???!" => "Are you serious?!?!" The first thing that came to mind was to: for char in string.punctuation: text =...
[ "You could try:\ntext = re.sub(r\"([\" + re.escape(string.punctuation) + r\"])\\1+\", r\"\\1\", text)\n\nThis uses re.escape() to ensure that the punctuation characters are properly escaped as necessary. The \\1 backreferences refer to the part within the parentheses (), which is the first punctuation character mat...
[ 4, 3 ]
[]
[]
[ "compression", "python", "regex", "repeat" ]
stackoverflow_0004485154_compression_python_regex_repeat.txt
Q: Recursive __dict__ call on python object? Is there a clean way to have dict called on all attributes of a python object? Specifically, when I call dict on a my object, I get this: {'edges': [<dawg.Edge instance at 0x107aa0200>, <dawg.Edge instance at 0x10a581a70>, <dawg.Edge instance at 0x10...
Recursive __dict__ call on python object?
Is there a clean way to have dict called on all attributes of a python object? Specifically, when I call dict on a my object, I get this: {'edges': [<dawg.Edge instance at 0x107aa0200>, <dawg.Edge instance at 0x10a581a70>, <dawg.Edge instance at 0x10656a680>]} but I'd like that output to be the ...
[ "I think the repr solution would be cleaner, but you can also get what you want by adding this line after getting the dictionary you describe above (im calling it d1)\nd2 = {'edges' : map(lambda x: x.getDict(), d1['edges'])}\n\nOR with list comprehension instead of map\nd2 = {'edges' : [i.getDict() for i in d1['edg...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004485120_python.txt
Q: Python subprocess Popen Why its not working? :| import subprocess p = subprocess.Popen([r"snmpget","-v","1","-c","public","-Oqv","","-Ln","192.168.1.1 1.3.6.1.2.1.2.2.1.10.7"],stdout=subprocess.PIPE).communicate()[0] print p Run script: root@OpenWrt:~/python# python w.py root@OpenWrt:~/python# its printin...
Python subprocess Popen
Why its not working? :| import subprocess p = subprocess.Popen([r"snmpget","-v","1","-c","public","-Oqv","","-Ln","192.168.1.1 1.3.6.1.2.1.2.2.1.10.7"],stdout=subprocess.PIPE).communicate()[0] print p Run script: root@OpenWrt:~/python# python w.py root@OpenWrt:~/python# its printing empty line :| Bu on the sam...
[ "I see you have an empty string in your args:\n... ,\"-Oqv\",\"\",\"-Ln\", ...\n ^^\n\nIs that possibly causing a problem for snmpget?\nYou've got two arguments in one, too:\n\"192.168.1.1 1.3.6.1.2.1.2.2.1.10.7\"\n\nThat should be split in two:\n\"192.168.1.1\", \"1.3.6.1.2.1.2.2.1.10.7\"\n\nWhen typing...
[ 2, 1, 0 ]
[]
[]
[ "popen", "python", "snmp", "subprocess" ]
stackoverflow_0004485270_popen_python_snmp_subprocess.txt
Q: Google App Engine - Issue running python shell commands from Aptana Studio Hi I'm somewhat of a newbie to python and I'm using app engine and Aptana Studio - I need to run some python shell commands so that i can complete the tasks in this Tutorial on how to set up 118 and django. I have got this all working but i...
Google App Engine - Issue running python shell commands from Aptana Studio
Hi I'm somewhat of a newbie to python and I'm using app engine and Aptana Studio - I need to run some python shell commands so that i can complete the tasks in this Tutorial on how to set up 118 and django. I have got this all working but i don't understand how i run the python commands to compile the dictionarys such ...
[ "So after quite a while I found another answer to your question, which was mine before too lol...\nThere is a tutorial on python on Google App Engine that explains how to set your python command line interface up and running in no time, and coming from someone like me, I really mean it in no time. \nThere are step...
[ 3 ]
[]
[]
[ "aptana", "google_app_engine", "python" ]
stackoverflow_0002895504_aptana_google_app_engine_python.txt
Q: Deploy python application I am developing an application for managers that might be used in a large organisation. The app is improved and extended step by step on a frequent (irregular) basis. The app will have SQL connections to several databases and has a complex GUI. What would you advise to deploy the app ? Ba...
Deploy python application
I am developing an application for managers that might be used in a large organisation. The app is improved and extended step by step on a frequent (irregular) basis. The app will have SQL connections to several databases and has a complex GUI. What would you advise to deploy the app ? Based on my current (limited) kno...
[ "If possible, make the application run without any installation procedure, and provide it on a network share (e.g. with a fixed UNC path). You didn't specify the client operating system: if it's Windows, create an MSI that sets up something in the start menu that will still make the application launch from the netw...
[ 1 ]
[]
[]
[ "client_server", "python", "rich_internet_application" ]
stackoverflow_0004485404_client_server_python_rich_internet_application.txt
Q: binary numbers? I am using the python shell to figure out how the print command works in python. When I type in print 01 1 print 010 8 print 0100 64 print 030 24 What's going on here? Is it just base 2? Why does the "one" in the second position print as 8? Shoul...
binary numbers?
I am using the python shell to figure out how the print command works in python. When I type in print 01 1 print 010 8 print 0100 64 print 030 24 What's going on here? Is it just base 2? Why does the "one" in the second position print as 8? Shouldn't it be 2 if i...
[ "Starting a number with a zero marks it as octal in Python 2. This has been recognized as confusing, surprising and also inconsistent, as starting with 0x will mark it as hexadecimal. Therefore, in Python 3, starting with 0 is invalid, and you get octal by starting with 0o. You can also start with 0b to mark it as ...
[ 12, 5, 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "binary", "python" ]
stackoverflow_0004485550_binary_python.txt
Q: How to retain the selection when updating a PyGTK combobox? This is a follow-up to a question I asked yesterday. What I want to do is to get a set of PyGTK-comboboxes to get updated whenever a value is selected in one of them. Initially they all contain the same items to choose from, but when a value is selected t...
How to retain the selection when updating a PyGTK combobox?
This is a follow-up to a question I asked yesterday. What I want to do is to get a set of PyGTK-comboboxes to get updated whenever a value is selected in one of them. Initially they all contain the same items to choose from, but when a value is selected this value should no longer be available in any of the other combo...
[ "You could lock the code with a boolean in the top of your function from being executed by the additional signals that will call it while you fill the combo boxes.\nif self.changed_single_score_locked:\n return\nelse:\n self.changed_single_score_locked = True\n\n\nstore what was selected\nclear box\nrepopulat...
[ 1 ]
[]
[]
[ "combobox", "pygtk", "python" ]
stackoverflow_0004485042_combobox_pygtk_python.txt
Q: Google App Engine: Browser to Server persistent connection I've been playing around with the Google App Engine channel API to create a real-time multiplayer game similar to http://rawkets.com/. Since this API is basically "one way" (doesn't enable a persistent browser-to-server connection), I am just issuing new ...
Google App Engine: Browser to Server persistent connection
I've been playing around with the Google App Engine channel API to create a real-time multiplayer game similar to http://rawkets.com/. Since this API is basically "one way" (doesn't enable a persistent browser-to-server connection), I am just issuing new AJAX POST requests (JQuery) at about 30/second. It seems to be...
[ "There are two major problems with creating long-lived connections yourself.\n\nYou can't stream output from the server, it will be buffered then sent when the handler exits.\nYour app will not be auto-scaled if your requests do not return in under 1,000ms.\n\nAs sje397 mentions, the Channel API currently does not ...
[ 1, 0, 0 ]
[]
[]
[ "ajax", "channel_api", "google_app_engine", "jquery", "python" ]
stackoverflow_0004482217_ajax_channel_api_google_app_engine_jquery_python.txt
Q: Predefined text replacements in C++ and Python As a hobby project, I had like to implement a Morse code encoder and decoder in C++ and Python (both). I was wondering the right data structure I should use for that. Not only is this question related to this specific project, but in general, when one has to make pred...
Predefined text replacements in C++ and Python
As a hobby project, I had like to implement a Morse code encoder and decoder in C++ and Python (both). I was wondering the right data structure I should use for that. Not only is this question related to this specific project, but in general, when one has to make predefined text replacements, what is the best and the f...
[ "from collections import defaultdict\n\nmorsecode = [('a','._'), ('b','_...'), ('c','_._.')]\ncodedict = defaultdict(lambda:' ')\nfor k,v in morsecode:\n codedict[k] = v\n\ntomorse = lambda x: ' '.join([codedict[chr] for chr in x])\n\nprint tomorse('bab cab')\n\nGives: \n_... ._ _... _._. ._ _...\n\n", "In P...
[ 3, 2, 2, 2, 1, 1, 0 ]
[]
[]
[ "c++", "python", "text" ]
stackoverflow_0003718304_c++_python_text.txt
Q: Registering and Deleting an Account I hate to come with another problem on the same day, let alone two, but now I need a way to register and delete accounts. Here's the entire script: accounts={'Robrajow':'password', 'Hacker':'hack', 'Noob':'lololol1'} option1=0 option2=0 loop=1 while loop==1: print "Welcome t...
Registering and Deleting an Account
I hate to come with another problem on the same day, let alone two, but now I need a way to register and delete accounts. Here's the entire script: accounts={'Robrajow':'password', 'Hacker':'hack', 'Noob':'lololol1'} option1=0 option2=0 loop=1 while loop==1: print "Welcome to Telemology! You can login, register, de...
[ "Here's a pretty complete rewrite:\nimport hashlib\nimport getpass\n\nclass Auth(object):\n class UserNameTakenError(Exception):\n pass\n\n def __init__(self, userDict):\n self._users = {name:self.hash(pwd) for name,pwd in userDict.iteritems()}\n\n def hash(self, pw):\n return hashlib....
[ 4, 3, 0 ]
[]
[]
[ "account", "passwords", "python" ]
stackoverflow_0004485075_account_passwords_python.txt
Q: slice operator understanding Possible Duplicate: good primer for python slice notation I am a little confused as to what the slice operator does in python. Can anyone explain to me how it works? A: The slice operator is a way to get items from lists, as well as change them. See http://docs.python.org/tutorial...
slice operator understanding
Possible Duplicate: good primer for python slice notation I am a little confused as to what the slice operator does in python. Can anyone explain to me how it works?
[ "The slice operator is a way to get items from lists, as well as change them. See http://docs.python.org/tutorial/introduction.html#lists.\nYou can use it to get parts of lists, skipping items, reversing lists, and so on:\n>>> a = [1,2,3,4]\n>>> a[0:2] # take items 0-2, upper bound noninclusive\n[1, 2]\n>>> a[0:-1]...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0004486382_python.txt
Q: Running a Python Script using Cron? I have a python script that I'd like to add to cron. The script has +x permission on it. How shall I add it to crontab? (say, I want it to run every minute). Important: when I navigate (using the shell) to the script's folder, I cannot run it using "./script_name.py"; it doesn't...
Running a Python Script using Cron?
I have a python script that I'd like to add to cron. The script has +x permission on it. How shall I add it to crontab? (say, I want it to run every minute). Important: when I navigate (using the shell) to the script's folder, I cannot run it using "./script_name.py"; it doesn't work. Yet, when I run it using "Python s...
[ "From cron you should be running the script as script_name.py and your script meets the following criteria:\n\nExecutable bit is set\nThe script's hash-bang is set correctly eg. #!/usr/bin/env python\nit is accessible from the PATH\n\ne.g. place it in /usr/local/bin/ or /opt/local/bin/ (and they are accessible to y...
[ 8 ]
[]
[]
[ "cron", "linux", "python", "ubuntu_10.04" ]
stackoverflow_0004486472_cron_linux_python_ubuntu_10.04.txt
Q: JSON response not a true string when passed to HTML template? I'm confused by the following behavior: Using Freebase-Python, I send a request to the Freebase API that is a query for a JSON response. I get the response, for example: "status": "200 OK", "code": "\/api\/status\/ok", "result": { "\/common...
JSON response not a true string when passed to HTML template?
I'm confused by the following behavior: Using Freebase-Python, I send a request to the Freebase API that is a query for a JSON response. I get the response, for example: "status": "200 OK", "code": "\/api\/status\/ok", "result": { "\/common\/topic\/weblink": [ { "url": "http:\/\/www.boardgame...
[ "In the django template language dictionary-, list index and attribute lookups are made using a dot ('.').\nFor that reason it should be something like {{ result.mylink.0.url }}, but this will most like not work using slashes in the key!\n" ]
[ 2 ]
[]
[]
[ "django", "freebase", "html", "json", "python" ]
stackoverflow_0004486306_django_freebase_html_json_python.txt
Q: Python Microsoft Speech API Error: SPERR_NO_DRIVER from CmdLoadFromFile This question may well go unanswered, but I would dearly like some help on the matter. I found a snippet of code for dealing with Microsoft's Speech API in Python, and then went and learned about W3C's "Speech Recognition Grammar Specification...
Python Microsoft Speech API Error: SPERR_NO_DRIVER from CmdLoadFromFile
This question may well go unanswered, but I would dearly like some help on the matter. I found a snippet of code for dealing with Microsoft's Speech API in Python, and then went and learned about W3C's "Speech Recognition Grammar Specification Version 1.0". I boiled it down to this: >>> import win32com.client >>> liste...
[ ".wav data is the most basic sort of sound data - raw sampling of a wave-form, \"how loud is the sound\" 8000 to 44000 times per second.\nA wave driver lets your computer get this raw data from a microphone or send it to a speaker.\nIf your computer has a sound card, it should already have this installed. Are you d...
[ 0 ]
[]
[]
[ "api", "microsoft_speech_api", "python", "speech" ]
stackoverflow_0004485911_api_microsoft_speech_api_python_speech.txt
Q: Trying to learn programming; I suck at command prompt I know this is really basic but it is frustrating. I'm using Python 2 to try and create my first program (in Windows 7 64bit). Every guide I look at says to install Python2, then go to the command prompt and type python. But... I get an error, because python...
Trying to learn programming; I suck at command prompt
I know this is really basic but it is frustrating. I'm using Python 2 to try and create my first program (in Windows 7 64bit). Every guide I look at says to install Python2, then go to the command prompt and type python. But... I get an error, because python.exe is not in that directory. So I change to the "python2...
[ "You need to add c:\\Python27\\ to your path. Try this explanation.\n", "You have basically two possibilities:\n\nUse the full path to the Python interpreter when starting you program, e.g. c:\\Python2.7\\python.exe HelloWorld\nAdd the directory of the Python interpreter to your PATH environment variable. I can't...
[ 4, 3, 0 ]
[]
[]
[ "command_line", "python" ]
stackoverflow_0004486481_command_line_python.txt
Q: mod user_dir and wsgi I am trying to setup a public_html/django_app folder, where all urls like ~/{username}/django would execute the .wsgi file located there. The idea is to checkout our project inside of the django folder, and have it work for everyone without further apache config. Right now, our project is run...
mod user_dir and wsgi
I am trying to setup a public_html/django_app folder, where all urls like ~/{username}/django would execute the .wsgi file located there. The idea is to checkout our project inside of the django folder, and have it work for everyone without further apache config. Right now, our project is running in /var/www/project_na...
[ "Answer: \n\nWSGIScriptAliasMatch\n ^/~([^/]+)/django_app\n /home/$1/public_html/django_app/core.wsgi\n\n" ]
[ 1 ]
[]
[]
[ "apache2", "django", "python", "wsgi" ]
stackoverflow_0004486353_apache2_django_python_wsgi.txt
Q: Django "Display once" in templates I've got a for loop in my django template that prints out a whole bunch of results (each result is time stamped). I want to print an arbitrary piece of data (for example a <hr />) once the timestamp reaches a certain value but I only want to print it once. {% for result in set %}...
Django "Display once" in templates
I've got a for loop in my django template that prints out a whole bunch of results (each result is time stamped). I want to print an arbitrary piece of data (for example a <hr />) once the timestamp reaches a certain value but I only want to print it once. {% for result in set %} {% if some_time > result.time %} <hr ...
[ "You can use builtin ifchanged template tag:\n{% ifchanged %}\n {% if some_time > result.time %}\n <hr />\n {% endif %}\n{% endifchanged %}\n\n" ]
[ 4 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004486501_django_django_templates_python.txt
Q: Throwing a custom error in a module meant to be imported by arbitrary modules (library) I'm building a python library that implements a task queue. If for whatever reason the thread that processes the tasks dies, and the option to restart the thread isn't set, I need to throw an exception. Is this something that I...
Throwing a custom error in a module meant to be imported by arbitrary modules (library)
I'm building a python library that implements a task queue. If for whatever reason the thread that processes the tasks dies, and the option to restart the thread isn't set, I need to throw an exception. Is this something that I should just throw a RuntimeException for? I don't want to throw a custom exception since the...
[ "Throw a custom exception. If the user of the library needs to catch that exception, they can import it.\nFor instance, take pickle.PicklingError:\n>>> import pickle\n>>> pickle.dumps(type(None))\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"C:\\Python27\\lib\\pickle.py\", l...
[ 2 ]
[]
[]
[ "custom_exceptions", "exception", "exception_handling", "python" ]
stackoverflow_0004486153_custom_exceptions_exception_exception_handling_python.txt
Q: Django unique_together does not allow ForeignKey field across applications when syncdb is executed I'm trying to create a unique constraint on my TranslationRequest model listed below. TranslationRequest has a foreign key relationship with a MachineTranslator model, which exists in another Django application. When...
Django unique_together does not allow ForeignKey field across applications when syncdb is executed
I'm trying to create a unique constraint on my TranslationRequest model listed below. TranslationRequest has a foreign key relationship with a MachineTranslator model, which exists in another Django application. When I try to run syncdb, I get the error: Error: One or more models did not validate: wt_articles.translati...
[ "i dont' know if it is a typo but i see s \",\" comma at the end of the line where you declare your translator = models.ForeignKey(MachineTranslator)\nThis is why maybe the attribute is ot seens\n" ]
[ 0 ]
[]
[]
[ "django_models", "foreign_keys", "python", "sqlite", "unique" ]
stackoverflow_0004389367_django_models_foreign_keys_python_sqlite_unique.txt
Q: MSN with Python I have plans to create a simple bot for a game I run and have it sit on MSN and answer queries. I want to use Python to do this and googled around and found MSNP. I thought "great" and "how awesome" but it appears that it's about 5 years old and oddly enough doesn't connect to MSN as they've probab...
MSN with Python
I have plans to create a simple bot for a game I run and have it sit on MSN and answer queries. I want to use Python to do this and googled around and found MSNP. I thought "great" and "how awesome" but it appears that it's about 5 years old and oddly enough doesn't connect to MSN as they've probably changed one or two...
[ "I don't know of anything equivalent, but you can look at the source to libpurple and roll your own without a terrible amount of difficulty.\n", "If you're prepared to do some hard work with the original source code, you could update it to support the current version of the MSN protocol:\nhttp://msnpiki.msnfanati...
[ 1, 1, 1 ]
[]
[]
[ "msn", "python" ]
stackoverflow_0000490929_msn_python.txt
Q: vectors in python structs is there a way to store vectors in structs in python? specifically, im trying to do: struct data{ string name // name of event string location // location of event vector <int> times // times the event happens in 24 hour format }; im not sure how to do it wit...
vectors in python structs
is there a way to store vectors in structs in python? specifically, im trying to do: struct data{ string name // name of event string location // location of event vector <int> times // times the event happens in 24 hour format }; im not sure how to do it with the structs module, since ive...
[ "It's not clear from your question, but if you just want a similar structure in Python you can use a list in place of the vector<int>.\ndata = ('John','Los Angeles, CA',[1,2,3,4,5,6])\n\nAnother alternative is to use a namedtuple:\n>>> import collections\n>>> Data = collections.namedtuple('Data','name location time...
[ 2, 1 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0004485913_c++_python.txt
Q: Python Script Not Working Via Cron? I have a python script that runs another python script. that 'other script' (script being run) takes ~ 45[min] to complete. When the 'execution' script is run from Ubuntu's shell, it all works perfectly. I added an entry to cron to run the 'execution' python script. It seems to...
Python Script Not Working Via Cron?
I have a python script that runs another python script. that 'other script' (script being run) takes ~ 45[min] to complete. When the 'execution' script is run from Ubuntu's shell, it all works perfectly. I added an entry to cron to run the 'execution' python script. It seems to run at first, but the program is termina...
[ "There are usually a few common misunderstandings made when trying to run things from cron.\n\nThere is no session. If you have code that needs a session you have to do additional setup.\nThe PATH and other environment variables are almost always different between your user session and the cron execution environme...
[ 8 ]
[]
[]
[ "cron", "linux", "python", "ubuntu" ]
stackoverflow_0004487145_cron_linux_python_ubuntu.txt
Q: Displaying unicode characters using python I have a string that prints out like this print a \u4f53\u91cd\u8a08 I am using eclipse and the console can print unicode characters, I have tested it like this. print u'\u4f53\u91cd\u8a08' 体重計 It prints out correctly, how can I make the string in the variable a to be p...
Displaying unicode characters using python
I have a string that prints out like this print a \u4f53\u91cd\u8a08 I am using eclipse and the console can print unicode characters, I have tested it like this. print u'\u4f53\u91cd\u8a08' 体重計 It prints out correctly, how can I make the string in the variable a to be printed like above. Thanks very much for advance....
[ "Perhaps...\nprint unicode(a)\n\nwould do the trick?\nIf the string itself actually has escaped escapes in it (i.e. if you were to write it, it'd be something more like u'\\\\u4f53\\\\u91cd\\\\u8a08'), then use:\nprint a.decode('unicode-escape')\n\n", "Decode using the unicode-escape codec.\n>>> print '\\\\u4f53\...
[ 3, 2 ]
[]
[]
[ "python", "string", "unicode" ]
stackoverflow_0004487499_python_string_unicode.txt
Q: Plotting terrain data with matplotlib plot_surface I'm trying to plot terrain elevation data with matplotlib. I build up a nx3 numpy array, with each row containing the x, y, z coordinates of my points (they're regularly spaced in a grid on the x, y plane). I am attempting to plot it with this code: fig = plt.fi...
Plotting terrain data with matplotlib plot_surface
I'm trying to plot terrain elevation data with matplotlib. I build up a nx3 numpy array, with each row containing the x, y, z coordinates of my points (they're regularly spaced in a grid on the x, y plane). I am attempting to plot it with this code: fig = plt.figure() ax = fig.gca(projection='3d') print desiredData...
[ "As the error suggests, \nValueError: need more than 1 value to unpack\n\nYou are using a 1D-array but plot_surface expects 2D arrays for X, Y and Z. \nAnd that is why you get the ValueError. \n" ]
[ 4 ]
[]
[]
[ "matplotlib", "numpy", "plot", "python" ]
stackoverflow_0004487549_matplotlib_numpy_plot_python.txt
Q: What is the right way to add an `if` to a generator expression in Python? this is my code : s = ''.join('%s: %s </br>' % (a,getattr(user, a) ) for a in dir(user)) and i want to add a if in this code , so i write : s = ''.join('%s: %s </br>' % (a,getattr(user, a) if !a.index('__') ) for a in dir(user)) i think it...
What is the right way to add an `if` to a generator expression in Python?
this is my code : s = ''.join('%s: %s </br>' % (a,getattr(user, a) ) for a in dir(user)) and i want to add a if in this code , so i write : s = ''.join('%s: %s </br>' % (a,getattr(user, a) if !a.index('__') ) for a in dir(user)) i think it is not right , what is the right way to add a if in the for loop , thanks
[ "You want the condition to evaluate on each iteration through the loop at the end, like this:\ns = ''.join('%s: %s </br>' % \n (a,getattr(user, a)) for a in dir(user) if '__' not in a\n )\n\nEdit: Sorry, fixed the parentheses to the appropriate nesting.\nEdited: Changed the conditional (didn...
[ 1, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0004487929_loops_python.txt
Q: How can I make 'AJAX templates' in Pylons? I've been getting into Pylons lately and was wondering how I could go about easily integrating AJAX functionality into my websites. Basically, lets say I had a login form that usually gets accessed via site.com/user/login. Now, generally, this will be handled via somethin...
How can I make 'AJAX templates' in Pylons?
I've been getting into Pylons lately and was wondering how I could go about easily integrating AJAX functionality into my websites. Basically, lets say I had a login form that usually gets accessed via site.com/user/login. Now, generally, this will be handled via something like: class UserController(BaseController): ...
[ "All modern Javascript libraries set an \"X-Requested-With: XMLHttpRequest\" header in their AJAX wrappers. As a convenience, Pylons sets the request.is_xhr boolean if it finds this header.\nConditional inheritance is a little tricky in Mako because of how <%inherit> is handled, but here's what you do:\n\nChange th...
[ 3, 2, 1 ]
[]
[]
[ "ajax", "javascript", "pylons", "python" ]
stackoverflow_0003385181_ajax_javascript_pylons_python.txt
Q: System V shared memory in Python? How can I make use of the shmat(), shmdt(), shmctl(), shmget() calls from Python? Are they hidden somewhere in the standard library? Update0 I'm after System V bindings that can be found in the Ubuntu repositories, or Python standard libraries (now or in future releases). A: If ...
System V shared memory in Python?
How can I make use of the shmat(), shmdt(), shmctl(), shmget() calls from Python? Are they hidden somewhere in the standard library? Update0 I'm after System V bindings that can be found in the Ubuntu repositories, or Python standard libraries (now or in future releases).
[ "If you don't want to use any non-standard Python libraries, perhaps you could wrap the functions you need yourself using ctypes?\n", "Google finds sysv_ipc.\n", "This page offers a feature matrix to help you choose between the posix_ipc, sysv_ipc, and shm modules.\n", "The processing package also supports sh...
[ 6, 4, 4, 2 ]
[]
[]
[ "ipc", "python", "shared_memory", "sysv" ]
stackoverflow_0002219604_ipc_python_shared_memory_sysv.txt
Q: Embedded Python - Blocking operations in time module I'm developing my own Python code interpreter using the Python C API, as described in the Python documentation. I've taken a look on the Python source code and I tried to follow the same steps that are carried out in the standard interpreter when executing a py ...
Embedded Python - Blocking operations in time module
I'm developing my own Python code interpreter using the Python C API, as described in the Python documentation. I've taken a look on the Python source code and I tried to follow the same steps that are carried out in the standard interpreter when executing a py file. These steps (sequence of C API function calls) are b...
[ "You need to provide more detail.\n\nHow does your interpreter's behavior differ from the standard interpreter?\nIf you just want to run arbitrary source files, why are you not calling one of the higher level interfaces, like PyRun_SimpleFile? Did your code call Py_Initialize?\n\n" ]
[ 1 ]
[]
[]
[ "api", "c", "embedded_language", "python", "time" ]
stackoverflow_0003196609_api_c_embedded_language_python_time.txt
Q: Problem with defining variables in python I'm trying to write some xml by this piece of code docs = XmlReportGenerator() docs.AddMatchRow('FC Barcelona','Madryt','5:0') docs.Save() and I wrote my own method: from lxml import etree class XmlReportGenerator: """""" root = etree.Element('results') doc =...
Problem with defining variables in python
I'm trying to write some xml by this piece of code docs = XmlReportGenerator() docs.AddMatchRow('FC Barcelona','Madryt','5:0') docs.Save() and I wrote my own method: from lxml import etree class XmlReportGenerator: """""" root = etree.Element('results') doc = etree.ElementTree(root) #----------------...
[ "Python is explicit. Instance variables must be prepended with self.. Class variables must be prepended with then name of the class.\nHere's a fixed version. The original SubElement call was incorrect as well:\nfrom lxml import etree\n\n# derive from 'object' if Python 2.X (it is default in Python 3.X)\nclass Xm...
[ 3, 2 ]
[]
[]
[ "lxml", "python", "variables" ]
stackoverflow_0004488207_lxml_python_variables.txt
Q: Is there a function that can turn a string into a hash? Ideally, 14 characters? Or, whatever works. A: hashlib This module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 as well as RS...
Is there a function that can turn a string into a hash?
Ideally, 14 characters? Or, whatever works.
[ "hashlib\nThis module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 as well as RSA’s MD5 algorithm.\n", "14 hex digits is 56 bits.\n14 base64 digits is 84 bits.\nmd5 is 128 bits, and ...
[ 5, 1 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0004488619_hash_python.txt
Q: message passing in python I read about this metaphor that objects use message passing while passing a message to another object. is it possible to capture/log such messages! This is for my learning purposes, but thought it would be necessary a handly tool for a provenance system! A: You might want to look at AOP...
message passing in python
I read about this metaphor that objects use message passing while passing a message to another object. is it possible to capture/log such messages! This is for my learning purposes, but thought it would be necessary a handly tool for a provenance system!
[ "You might want to look at AOP (Aspect Oriented Programming).\nIn essence it allows you to capture object events such method invocation and apply some logic to them. In your case it'd be just print out some traces.\nHave a look at A Lightweight Approach to Aspect-Oriented Programming in Python, it should do what yo...
[ 1 ]
[]
[]
[ "logging", "object", "python" ]
stackoverflow_0004488500_logging_object_python.txt
Q: How to start an application using Python I want to use a Python script to start an application, and then click File to Open a file. How should accomplish this? For example, I want to write a script which starts an automation tool/program that I have. Is there another scripting language that is better suited for th...
How to start an application using Python
I want to use a Python script to start an application, and then click File to Open a file. How should accomplish this? For example, I want to write a script which starts an automation tool/program that I have. Is there another scripting language that is better suited for this? You are appreciated!
[ "If I understand your question correctly you basically want to load a program using python, if so you should try something like this:\nimport os\nACRORD = r\"c:\\Program Files\\Adobe\\Acrobat 5.0\\Reader\\acrord32.exe\"\nos.system ('\"%s\" %s' % (ACRORD, r\"c:\\temp\\blah.pdf\"))\n\nas found here also: http://mail....
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004488847_python.txt
Q: python regular expression replacing part of a matched string i got an string that might look like this "myFunc('element','node','elementVersion','ext',12,0,0)" i'm currently checking for validity using, which works fine myFunc\((.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\) now i'd like to replace whatever st...
python regular expression replacing part of a matched string
i got an string that might look like this "myFunc('element','node','elementVersion','ext',12,0,0)" i'm currently checking for validity using, which works fine myFunc\((.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\) now i'd like to replace whatever string is at the 3rd parameter. unfortunately i cant just use a stri...
[ "In re.sub, you need to specify a substitution for the whole matching string. That means that you need to repeat the parts that you don't want to replace. This works:\nmyRe = re.compile(r\"(myFunc\\(.+?\\,.+?\\,)(.+?)(\\,.+?\\,.+?\\,.+?\\,.+?\\))\")\nprint myRe.sub(r'\\1\"noversion\"\\3', val)\n\n", "If your only...
[ 9, 4, 2, 1, 1 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0004489074_python_regex_string.txt
Q: User authentication on GAE I'm working on a project that will require user authentication. Currently I'm planning on running the project on GAE. For various reasons I'd rather have my own authentication system rather than use openid or google's built in authentication service. I've looked high and low for a librar...
User authentication on GAE
I'm working on a project that will require user authentication. Currently I'm planning on running the project on GAE. For various reasons I'd rather have my own authentication system rather than use openid or google's built in authentication service. I've looked high and low for a library but can't seem to find anythin...
[ "If you use Django in GAE you can write your own auth system.\n", "If you are OK with using a third-party framework, instead of webapp, tipfy has some good extensions. For authentication, check tipfy.ext.auth. The documentation looks good.\n", "If you are ready to use django as a framework, you may get the djan...
[ 1, 1, 1 ]
[]
[]
[ "authentication", "authkit", "google_app_engine", "python" ]
stackoverflow_0004487697_authentication_authkit_google_app_engine_python.txt
Q: Disable right click in GTK window I would disable right click (and so context menu) in a Python GTK window (pyGTK) where inside is located a "window" pyWebKitGtk. Someone can help me writing some lines of code? I think that would better delete event directly in pyGTK but if you know how don't show context menu in ...
Disable right click in GTK window
I would disable right click (and so context menu) in a Python GTK window (pyGTK) where inside is located a "window" pyWebKitGtk. Someone can help me writing some lines of code? I think that would better delete event directly in pyGTK but if you know how don't show context menu in pyWebKitGtk is good anyway. TNK TNK TNK...
[ "You can use the enable-default-context-menu setting:\nwebview.props.settings.props.enable_default_context_menu = False\n\n" ]
[ 6 ]
[]
[]
[ "contextmenu", "pygtk", "python", "right_click", "webkit" ]
stackoverflow_0004445065_contextmenu_pygtk_python_right_click_webkit.txt
Q: Django runfcgi mode timeout manage runfcgi host=127.0.0.1 port=8002 maxrequests=200 maxchildren=100 minchildren=4 I started django fcgi in this way. It seems all right in processes monitor. But when I open http://127.0.0.1:8002, it keep runing and no result come out. manage runserver 127.0.0.1:8002 This method w...
Django runfcgi mode timeout
manage runfcgi host=127.0.0.1 port=8002 maxrequests=200 maxchildren=100 minchildren=4 I started django fcgi in this way. It seems all right in processes monitor. But when I open http://127.0.0.1:8002, it keep runing and no result come out. manage runserver 127.0.0.1:8002 This method was fine. Does any one knows why?
[ "As explained in the Django docs on FastCGI:\n\nFastCGI is an efficient way of letting\n an external application serve pages to\n a Web server. The Web server delegates\n the incoming Web requests (via a\n socket) to FastCGI, which executes the\n code and passes the response back to\n the Web server, which, i...
[ 2 ]
[]
[]
[ "django", "fastcgi", "python" ]
stackoverflow_0004486857_django_fastcgi_python.txt
Q: HTTP Error 401: Unauthorized Again stucked with tweepy. I got an app that uses tweepy oauth authentication and follows step by step the instructions from the tutorial: http://joshthecoder.github.com/tweepy/docs/auth_tutorial.html#oauth-authentication This app was working correctly, but now, is only returning the s...
HTTP Error 401: Unauthorized
Again stucked with tweepy. I got an app that uses tweepy oauth authentication and follows step by step the instructions from the tutorial: http://joshthecoder.github.com/tweepy/docs/auth_tutorial.html#oauth-authentication This app was working correctly, but now, is only returning the same exception in any user attempt ...
[ "One guess may be the accounts are blocked try using cURL to figure out if you are blacklisted, in which case Twitter probably won't have notified you of this. Alternatively, try another module: http://dev.twitter.com/pages/oauth_libraries\nfor cURL do the following:\ncurl -i -u my_account:fuuu! http://api.twitte...
[ 0 ]
[]
[]
[ "python", "tweepy", "twitter" ]
stackoverflow_0004462849_python_tweepy_twitter.txt
Q: Python: split on two different expressions? Possible Duplicate: Python strings split with multiple separators Is there a way in Python to split a string on two different keys? Say I have a string like this: mystr = "wketjwlektjwltjkw<br/>wwwweltjwetlkwjww" + \ "wwetlwjtwlet<strong>wwwwketjwlektjwlk</str...
Python: split on two different expressions?
Possible Duplicate: Python strings split with multiple separators Is there a way in Python to split a string on two different keys? Say I have a string like this: mystr = "wketjwlektjwltjkw<br/>wwwweltjwetlkwjww" + \ "wwetlwjtwlet<strong>wwwwketjwlektjwlk</strong" I'd like to split on EITHER <br/>wwww or <...
[ "import re\nre.split(r'<(br\\/|strong)>wwww', mystr)[::2]\n\n" ]
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0004489774_python.txt
Q: Framework for user defined relationships I'm thinking about creating a Django-powered website where users would be able to relate entities to each other. Examples would for instance include: "John is married to Mary" or "John works at Google". Users should be able to define the entities and their relationships the...
Framework for user defined relationships
I'm thinking about creating a Django-powered website where users would be able to relate entities to each other. Examples would for instance include: "John is married to Mary" or "John works at Google". Users should be able to define the entities and their relationships themselves (and will typically define relations o...
[ "There's Protege, the Stanford ontology program. If you can run it for Java, perhaps you can run it for Jython.\nhttp://protege.stanford.edu/conference/2004/slides/3.3_dameron_7-7-04.pdf\n", "\nUsers are able to define the relationships themselves (and will typically define relations of other people, not of them...
[ 1, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004488965_django_python.txt
Q: TemplateDoesNotExist at django hosting in the localhost , my code is running good on http://127.0.0.1:8000/twitter/ , but in the django hosting : http://zjm1126.alwaysdata.net/twitter/, it is show error : TemplateDoesNotExist at /twitter/ home.html home.html is in mysite: twitter templates ...
TemplateDoesNotExist at django hosting
in the localhost , my code is running good on http://127.0.0.1:8000/twitter/ , but in the django hosting : http://zjm1126.alwaysdata.net/twitter/, it is show error : TemplateDoesNotExist at /twitter/ home.html home.html is in mysite: twitter templates home.html and i set this is settings.py...
[ "Check if there are missing templates included in your home.html.\nIf you have, say, {% include \"header.html\" %} in your home.html, and there's no header.html in the templates directory, Django still will throw TemplateDoesNotExist home.html, even though the actual missing template is not home.html, but the one i...
[ 2, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004486904_django_django_templates_python.txt
Q: Automatic class decoration (or validation) upon derivation I have a base class from which I derive multiple subclasses. Each subclass defines class constants, and I wish to enforce certain limitations on them. For example: class Base(object): # define these in your sub-class, and make sure (NOM % DENOM == 0) ...
Automatic class decoration (or validation) upon derivation
I have a base class from which I derive multiple subclasses. Each subclass defines class constants, and I wish to enforce certain limitations on them. For example: class Base(object): # define these in your sub-class, and make sure (NOM % DENOM == 0) NOMINATOR = None DENOMINATOR = None class Subclass_good...
[ "Ok, funny. I was thinking about it for a while, but only after posting the question - specifically when choosing tags, and adding \"metaclass\" there - did I realize I may have an answer myself.\nSo, submitted for review and future knowledge, here goes:\nclass Base_Metaclass(type):\n def __new__(meta, classname...
[ 8, 1 ]
[]
[]
[ "class", "decorator", "metaclass", "python" ]
stackoverflow_0004490053_class_decorator_metaclass_python.txt