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: Altering "Send To" on Windows with Python I need to redirect the "Send To Mail Recipient" menu in Microsoft Office (primarily Word and Excel) to send the document using a web client email. I need to do the same thing with the context menu that appears when right-clicking a file (i.e. Send To -> Mail Recipient). I'...
Altering "Send To" on Windows with Python
I need to redirect the "Send To Mail Recipient" menu in Microsoft Office (primarily Word and Excel) to send the document using a web client email. I need to do the same thing with the context menu that appears when right-clicking a file (i.e. Send To -> Mail Recipient). I'd like to catch these events using Python, prob...
[ "the only thing I can think of is to use Microsoft Active Accessibility bindings for Python. These give you the ability to monitor events, including window open/close events. I can't think of any other library that has this functionality.\nhttp://www.cs.unc.edu/Research/assist/doc/pyaa/public/pyAA.AA.AccessibleObje...
[ 0 ]
[]
[]
[ "com", "python", "pywin32", "registry" ]
stackoverflow_0005395853_com_python_pywin32_registry.txt
Q: What are the difference in these two 2d arrays? I was writing a program that needs a 2d array, and came upon a strange problem. At first, I wrote: board = [[]]*11 to make eleven arrays within an array. Then I wanted eleven blanks within each array so I wrote: for i in range(11): board[i].append(' ') I wanted...
What are the difference in these two 2d arrays?
I was writing a program that needs a 2d array, and came upon a strange problem. At first, I wrote: board = [[]]*11 to make eleven arrays within an array. Then I wanted eleven blanks within each array so I wrote: for i in range(11): board[i].append(' ') I wanted to fill the third array, from index 4 to 7 with star...
[ "The list [[]] * 11 contains 11 references to the same list.\nYour second example creates 11 different lists.\nboard = [[]]*11\n# ^^ this is called just once\n\nboard2 = []\nfor i in range(11):\n board2.append([])\n# ^^ this is called 11 times, creating 11 different lists\n\nAnother way to...
[ 7 ]
[]
[]
[ "arrays", "multidimensional_array", "python", "syntax" ]
stackoverflow_0005397519_arrays_multidimensional_array_python_syntax.txt
Q: Querying objects in a View in DJANGO I have a django model called destination. I have another model called tours. Tours consist of destinations and other elements. In my VIEW for destinations, I want to have available a Tour List containing all the Tours associated with a particular destination. I'm not sure ...
Querying objects in a View in DJANGO
I have a django model called destination. I have another model called tours. Tours consist of destinations and other elements. In my VIEW for destinations, I want to have available a Tour List containing all the Tours associated with a particular destination. I'm not sure how to write it out. this is what I have:...
[ "get_object_or_404() will get you only a single object. Filter instead.\ntours_in = Tour.objects.filter(destination=destination_id)\n\n" ]
[ 0 ]
[]
[]
[ "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0005396852_django_models_django_templates_django_views_python.txt
Q: How to use Mercurial to deploy Django applications? I'm creating a server with Apache2 + mod_python + Django for development and would like to know how to use Mercurial to manage application development. My idea is to make the folder where the Mercurial stores the project be the same folder to deploy Django. Thank...
How to use Mercurial to deploy Django applications?
I'm creating a server with Apache2 + mod_python + Django for development and would like to know how to use Mercurial to manage application development. My idea is to make the folder where the Mercurial stores the project be the same folder to deploy Django. Thank you for your attention!
[ "\nI thought about this, good idea for development.\nUse mercurial in common way. And of course you need deploy mercurial server before.\nIf you update your django project, it will be compiled on the fly.\n\n\nMy workflow:\n\nSet up mercurial server or use bitbucket\nInit repo locally\nPush repo to central repo\nOn...
[ 0 ]
[]
[]
[ "apache2", "django", "mercurial", "mod_python", "python" ]
stackoverflow_0005397528_apache2_django_mercurial_mod_python_python.txt
Q: How to JSON encode Entities? I'm getting started with Google App Engine. I want to make AJAX chat like Twitter. class ChatMessage(db.Model): message = db.StringProperty() created = db.DateTimeProperty(auto_now=True) Server JSON encodes the response, class RPCHandler(webapp.RequestHandler): def get(self): ...
How to JSON encode Entities?
I'm getting started with Google App Engine. I want to make AJAX chat like Twitter. class ChatMessage(db.Model): message = db.StringProperty() created = db.DateTimeProperty(auto_now=True) Server JSON encodes the response, class RPCHandler(webapp.RequestHandler): def get(self): chat_list = {'message':'Hello!'}...
[ "In App Engine Python you can use this script to encode db.Models to JSON. You may have to customize some parts, like the DateTime formatting.\nhttp://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55\n", "You can't use simplejson.dumps() on a list of db.Model items directly.\n...
[ 3, 1, 0, 0 ]
[]
[]
[ "ajax", "google_app_engine", "json", "python" ]
stackoverflow_0005397793_ajax_google_app_engine_json_python.txt
Q: check ldap access rights with python I am writing a web frontend (django) for an LDAP server. There are different kinds of people with different kinds of privileges, so I set up LDAP ACL to control who gets to see or edit a specific attribute. Now its easy to determine if a specific user has read access - try to r...
check ldap access rights with python
I am writing a web frontend (django) for an LDAP server. There are different kinds of people with different kinds of privileges, so I set up LDAP ACL to control who gets to see or edit a specific attribute. Now its easy to determine if a specific user has read access - try to read, and you will see what you get. But I ...
[ "ACL, on openldap are organized by OU and/or DN check with regexp\nex : \naccess to attrs=userPassword\n by anonymous auth\n by self write\n by dn.base=\"ou=users_with_userPassword_write_access,dc=myproduct,dc=org\" write\n by dn.exact=\"cn=manager,dc=myproduct,dc=org\" write\n by * none\n\naccess to...
[ 0, 0, 0 ]
[]
[]
[ "acl", "ldap", "python" ]
stackoverflow_0004224527_acl_ldap_python.txt
Q: Python - Best data structure for incredibly large matrix I need to create about 2 million vectors w/ 1000 slots in each (each slot merely contains an integer). What would be the best data structure for working with this amount of data? It could be that I'm over-estimating the amount of processing/memory involved. ...
Python - Best data structure for incredibly large matrix
I need to create about 2 million vectors w/ 1000 slots in each (each slot merely contains an integer). What would be the best data structure for working with this amount of data? It could be that I'm over-estimating the amount of processing/memory involved. I need to iterate over a collection of files (about 34.5GB in ...
[ "You might be memory bound on your machine. Without cleaning up running programs:\na = numpy.zeros((1000000,1000),dtype=int)\n\nwouldn't fit into memory. But in general if you could break the problem up such that you don't need the entire array in memory at once, or you can use a sparse representation, I would go w...
[ 5, 1, 1 ]
[]
[]
[ "data_structures", "large_data_volumes", "matrix", "python", "vector" ]
stackoverflow_0005397809_data_structures_large_data_volumes_matrix_python_vector.txt
Q: How can I have specific information passed along each time a view is rendered in Django? I'm building a web site in Django, and I want to have some basic information added to the dictionary that is passed to the template renderer. For now, I'm just wanting a list of the static pages in my site so that I can put li...
How can I have specific information passed along each time a view is rendered in Django?
I'm building a web site in Django, and I want to have some basic information added to the dictionary that is passed to the template renderer. For now, I'm just wanting a list of the static pages in my site so that I can put links in the header, but would like to be able to expand that information later.
[ "Context Processors\nhttp://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors\nIt's just a function that takes 1 argument, request, and returns a dictionary. Specify active processors in your settings file.\ndef MyProcessor(request):\n return {'im_available_in_every_template':...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005397985_django_python.txt
Q: Image Manipulation Library / API for Modifying Faces I'm looking for an image manipulation library, preferably in .NET, that makes it easy to recognize and manipulate faces in images. Is there a library out there that does this? A: There is OpenCV (Open Source Computer Vision), which is a is a library of program...
Image Manipulation Library / API for Modifying Faces
I'm looking for an image manipulation library, preferably in .NET, that makes it easy to recognize and manipulate faces in images. Is there a library out there that does this?
[ "There is OpenCV (Open Source Computer Vision), which is a is a library of programming functions for real time computer vision. \nI'm not familiar with it, so I don't know if it will make \"easy to recognize and manipulate faces in images\", but you can give it a look. It's not in .Net, but you tagged your question...
[ 1 ]
[]
[]
[ ".net", "c", "c++", "python" ]
stackoverflow_0005366774_.net_c_c++_python.txt
Q: Python: divide an array into section Update: I managed to fix the issue with the help of Jeremy's function that break my data set in to 50 chunks. I have posted the final answer. I have the following code the reason I want to break the array into chunks is that I am trying to use an api that only allows 50 request...
Python: divide an array into section
Update: I managed to fix the issue with the help of Jeremy's function that break my data set in to 50 chunks. I have posted the final answer. I have the following code the reason I want to break the array into chunks is that I am trying to use an api that only allows 50 requests at a time. Also I am java developer who ...
[ "There's probably a built-in function to do this but I can't think of it.\n#!/usr/bin/env python2.7\n\ndef divide_list(list_, n):\n \"\"\"Produces an iterator over subsections of maximum length n of the list.\"\"\"\n\n for i in range(0, len(list_), n):\n yield list_[i:i + n]\n\nExample usage:\nprint(li...
[ 3, 3, 3, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0005386844_json_python.txt
Q: Find inside a string in Python There is a string, it contains numbers and characters. I need to find an entire number(s) (in that string) that contains number 467033. e.g. 1.467033777777777 Thanks A: Try this: import re RE_NUM = re.compile('(\d*\.\d+)', re.M) text = 'eghwodugo83o135.13508yegn1.467033777777777...
Find inside a string in Python
There is a string, it contains numbers and characters. I need to find an entire number(s) (in that string) that contains number 467033. e.g. 1.467033777777777 Thanks
[ "Try this:\nimport re\n\nRE_NUM = re.compile('(\\d*\\.\\d+)', re.M)\n\ntext = 'eghwodugo83o135.13508yegn1.4670337777777773u87208t'\nfor num in RE_NUM.findall(text):\n if '467033' in num:\n print num\n\nPrints:\n1.4670337777777773\n\nGeneralized / optimized in response to comment:\ndef find(text, numbers):...
[ 2, 1, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005398252_python_string.txt
Q: Python 3.2 idle : range function - print or list? I know this is wrong thing to do, but I am using python 3 but studying it with python 2 book. it says, >>>range(2,7) will show [2,3,4,5,6] but I know it won't show the output above, THAT I figured. so I tried: >>>>print(range(2,7)) and ta-da- it shows follow: r...
Python 3.2 idle : range function - print or list?
I know this is wrong thing to do, but I am using python 3 but studying it with python 2 book. it says, >>>range(2,7) will show [2,3,4,5,6] but I know it won't show the output above, THAT I figured. so I tried: >>>>print(range(2,7)) and ta-da- it shows follow: range(2,7) looks like this is the one of changes from P...
[ "In your IDLE case, you are running the code in IDLE's PyShell window. This is running the interactive interpreter. In interactive mode, Python interprets immediately each line you type in and it displays the value returned by evaluating the statement you typed plus anything written to standard output or standard ...
[ 6, 4 ]
[]
[]
[ "list", "printing", "python", "range" ]
stackoverflow_0005398260_list_printing_python_range.txt
Q: Python, Django and pyodbc: invalid characters I am connecting to a MS SQL server database using pyodbc. The error im getting is the following invalid byte sequence for encoding "UTF8": 0x93 HINT: This error can also happen if the byte sequence does not match the encoding expected by the server, which is control...
Python, Django and pyodbc: invalid characters
I am connecting to a MS SQL server database using pyodbc. The error im getting is the following invalid byte sequence for encoding "UTF8": 0x93 HINT: This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding". The SQL database is enco...
[ "You have given next to no clues but a reasonable guess is:\nYou need to decode your MS SQL Server data to unicode using the correct encoding, and (not necessarily immediately) encode it as 'UTF-8' for transmission to postgres.\nWhat makes you think that the encoding used on the SQL Server db is latin1 and not cp12...
[ 3 ]
[]
[]
[ "decode", "django", "pyodbc", "python", "utf_8" ]
stackoverflow_0005387319_decode_django_pyodbc_python_utf_8.txt
Q: Finding All Possible Combinations of Letters using an API and Python I'm trying to put together a small web app where users enter in the last 4 digits of their phone number, hit submit, and then are shown all the words (if any) that can be made on the keypad using their 4 numbers. So if a user enters "2287" they a...
Finding All Possible Combinations of Letters using an API and Python
I'm trying to put together a small web app where users enter in the last 4 digits of their phone number, hit submit, and then are shown all the words (if any) that can be made on the keypad using their 4 numbers. So if a user enters "2287" they are shown "acts" "bats" "cats" and any other words that can be made from th...
[ "Read dictionary and keep only 4 letter words, append them to defaultdict(list) by the number code of the four letters, when user inputs for numbers give them the ready list for that number or say 'No words for that number'.\nimport itertools\nletters = ('',' ', 'abc','def','ghi','jkl','mno','pqrs','tuv','wxyz')\nr...
[ 3, 2 ]
[]
[]
[ "api", "html", "javascript", "python", "scripting" ]
stackoverflow_0005398827_api_html_javascript_python_scripting.txt
Q: disable glow effect of gtkbutton I would like to know that how to disable the glow effect of gtkButton on mouseover. Please help me. Thank you in advance. A: This may be what you are looking for. It is c++, but hopefully you can translate it to the python equivalent. The code changes the background color of a wi...
disable glow effect of gtkbutton
I would like to know that how to disable the glow effect of gtkButton on mouseover. Please help me. Thank you in advance.
[ "This may be what you are looking for. It is c++, but hopefully you can translate it to the python equivalent. The code changes the background color of a widget in different states.\nvoid changeColor(Gtk::Widget* widget, double r, double g, double b) {\n Glib::RefPtr<Gdk::Colormap> colormap = widget->get_colorma...
[ 2, 1, 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0005237080_gtk_pygtk_python.txt
Q: In GTK on Windows, how do I change the background color of the whole app? According to http://www.pygtk.org/docs/pygtk/gtk-constants.html, there are five state types: STATE_NORMAL, STATE_INSENSITIVE, etc. I want to set the background color of a Table, HBox, VBox, whatever, and I've tried setting every possible col...
In GTK on Windows, how do I change the background color of the whole app?
According to http://www.pygtk.org/docs/pygtk/gtk-constants.html, there are five state types: STATE_NORMAL, STATE_INSENSITIVE, etc. I want to set the background color of a Table, HBox, VBox, whatever, and I've tried setting every possible color of every kind of state: style = self.get_style() for a in (style.bas...
[ "Mostly google-fu (no windows here), posting as an \"answer\" mostly for a slightly better formatting. See if experimenting with the full-blown gtkrc like the one from here brings the fruits. The location, based on this and this appears to vary - so unless someone has the deterministic approach of finding it, filem...
[ 2, 1, 0 ]
[]
[]
[ "colors", "gtk", "pygtk", "python", "windows" ]
stackoverflow_0001241846_colors_gtk_pygtk_python_windows.txt
Q: Generate headers in Twisted client i'm using the Twisted web "HTTPClient" protocol to dialogue with a http server (using twisted app as a client), the problem is that most of my request do not accept my header. Is there some sort of way (maybe using certain libraries) to generate header?? I'll post some code so yo...
Generate headers in Twisted client
i'm using the Twisted web "HTTPClient" protocol to dialogue with a http server (using twisted app as a client), the problem is that most of my request do not accept my header. Is there some sort of way (maybe using certain libraries) to generate header?? I'll post some code so you can have a look class Local(HTTPClient...
[ "I would definitely recommend you to use Twisted's Agent class along with the Header class in the twisted.web.http_headers module.\nThere is a nice guide available here.\nIf you need a real life example of a Twisted HTTP client which adds some headers to the request and can read the ones of the answer, here it is:\...
[ 3 ]
[]
[]
[ "client", "http", "python", "twisted" ]
stackoverflow_0003301260_client_http_python_twisted.txt
Q: How do I url encode in Python? I tried this: but it doesn't work. print urllib.urlencode("http://"+SITE_DOMAIN+"/go/") I want to turn it into a string with url encodings A: Were you looking for the quote() or quote_plus() function instead? >>> urllib.quote("http://spam.com/go/") 'http%3A%2F%2Fspam.com%2Fgo%2F' ...
How do I url encode in Python?
I tried this: but it doesn't work. print urllib.urlencode("http://"+SITE_DOMAIN+"/go/") I want to turn it into a string with url encodings
[ "Were you looking for the quote() or quote_plus() function instead?\n>>> urllib.quote(\"http://spam.com/go/\")\n'http%3A%2F%2Fspam.com%2Fgo%2F'\n\n", "You are looking for urllib.quote().\n" ]
[ 13, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005399112_python.txt
Q: Managing multiple Twisted client connections I'm trying to use Twisted in a sort of spidering program that manages multiple client connections. I'd like to maintain of a pool of about 5 clients working at one time. The functionality of each client is to connect to a specified IRC server that it gets from a list,...
Managing multiple Twisted client connections
I'm trying to use Twisted in a sort of spidering program that manages multiple client connections. I'd like to maintain of a pool of about 5 clients working at one time. The functionality of each client is to connect to a specified IRC server that it gets from a list, enter a specific channel, and then save the list ...
[ "The best option is really just to do the obvious thing here. Don't have a loop, or a repeating timed call; just have handlers that do the right thing.\nKeep a central connection-management object around, and make event-handling methods feed it the information it needs to keep going. When it starts, make 5 outgoi...
[ 4, 3 ]
[ "I don't know if you are forced to use Twisted, otherwise you might want to give Gevent a try.\n" ]
[ -1 ]
[ "python", "twisted" ]
stackoverflow_0001365737_python_twisted.txt
Q: Python odeint usage Can someone tell me how to put in the parameters for the odeint function for the python to get the integral. I am trying to get the integral of e^x from 0 to 2 but I am not sure how to put in the parameters. The documentation isnt all that clear to me. Thanks A: Here's an example that assumes...
Python odeint usage
Can someone tell me how to put in the parameters for the odeint function for the python to get the integral. I am trying to get the integral of e^x from 0 to 2 but I am not sure how to put in the parameters. The documentation isnt all that clear to me. Thanks
[ "Here's an example that assumes y(0) = 1.\nimport scipy\nimport scipy.integrate\n\n\ndef integrateExp(y0, a, b):\n limits = [a, b]\n integral = scipy.integrate.odeint(lambda y, t : scipy.exp(t), y0, limits)\n return integral[1]\n\nprint integrateExp(1, 0, 2)\n\nThe first argument should take (y,t) and return the...
[ 3, 1 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0005371555_python_scipy.txt
Q: mysql inserting variable from jython I am trying to insert a variable into mysql from jython and am getting weird errors var1='abc' cursor.execute (""" INSERT INTO Master (Name) VALUES (%s) """, (var1)) I get an error zxJDBC.ProgrammingError: optional second argument must be a list or tuple I am just trying to ...
mysql inserting variable from jython
I am trying to insert a variable into mysql from jython and am getting weird errors var1='abc' cursor.execute (""" INSERT INTO Master (Name) VALUES (%s) """, (var1)) I get an error zxJDBC.ProgrammingError: optional second argument must be a list or tuple I am just trying to add one variable into a table called Maste...
[ "Change (var1) to (var1,). Parenthesis group unless you add a comma, which then indicates a tuple.\nAlso, check the parameter style, as it may not be recognizing the %s format. Per PEP 249:\nparamstyle\n\nString constant stating the type of parameter marker\nformatting expected by the interface. Possible values a...
[ 3 ]
[]
[]
[ "jython", "mysql", "python" ]
stackoverflow_0005399316_jython_mysql_python.txt
Q: Uninstall Easy_Install So I installed Python 2.7.1 from source on a server using stow. I have been careless in the past, and I am trying to keep organized when dealing with source installs. So, enter stow. Now I installed easy_install with wget and running the ez_setup.py script. Lo and behold, in my infinite ...
Uninstall Easy_Install
So I installed Python 2.7.1 from source on a server using stow. I have been careless in the past, and I am trying to keep organized when dealing with source installs. So, enter stow. Now I installed easy_install with wget and running the ez_setup.py script. Lo and behold, in my infinite wisdom/carelessness, I forgo...
[ "Go to your \"site-packages\" directory (look at your sys.path) and then run:\nrm -rf setuptools-*.egg pkg_resources.py easy_install.py setuptools/ setuptools-*.egg-info/\n\nAnd delete the easy_install binary as well. I came up with these instructions when writing FAQ for PyPM.\n" ]
[ 6 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0005399056_easy_install_python.txt
Q: problem with seek() in file handling I am using seek in a file- the file has a bunch of filenames and some logs of a process done on the file- some of these logs have errors. I am going line by line, if i get an error, I want to log everything in between two filenames. When I use seek, I think that instead of mov...
problem with seek() in file handling
I am using seek in a file- the file has a bunch of filenames and some logs of a process done on the file- some of these logs have errors. I am going line by line, if i get an error, I want to log everything in between two filenames. When I use seek, I think that instead of moving it to the line i want it to, it moves ...
[ "Use .tell() to store your start-of-line position, then you can .seek() back to it.\nEdit: I think this is what you want:\ndef errorsInLog(fname, newfileStr='D:', iserrorStr='error'):\n with open(fname) as inf:\n prev = pos = inf.tell()\n line = inf.readline()\n error = False\n\n whil...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005399534_python.txt
Q: Determine function to execute from option used How can options/arguments determine which function is chosen during program execution? For the example I have two options depending on the option I would like them to use their respective functions. What am I missing? import os, sys, glob from optparse import OptionPa...
Determine function to execute from option used
How can options/arguments determine which function is chosen during program execution? For the example I have two options depending on the option I would like them to use their respective functions. What am I missing? import os, sys, glob from optparse import OptionParser def fname(arguments): files = [] for a...
[ "\nYou are missing a lot.\n\nWhere is filename given a value?\nWhere is keyString given a value?\nWhere is bucket given a value?\nYou shouldn't name your function list since that it is a primitive type\n\nYou probably want to look at the optparse tutorial. I'm assuming that you expecting bucket to receive the valu...
[ 1 ]
[]
[]
[ "function", "python", "scripting" ]
stackoverflow_0005399617_function_python_scripting.txt
Q: Python: first instance of subprocess.Popen() is very slow I'm sure I'm missing something simple, but when using the subprocess module, there is a very significant wait (> 10 seconds) to starting the first subprocess. The second one starts shortly after the first. Is there any way to fix this? Code below: EDIT: To ...
Python: first instance of subprocess.Popen() is very slow
I'm sure I'm missing something simple, but when using the subprocess module, there is a very significant wait (> 10 seconds) to starting the first subprocess. The second one starts shortly after the first. Is there any way to fix this? Code below: EDIT: To add, HWAccess (in proc.py) links a dll. Could this have anythin...
[ "I am not sure if this is the right track, but I remember seeing such delays when starting a process wayyy back (and not at all Python related), and it turned out they were related to some badly configured network settings on my computer. Upon subprocess start-up, it has to set up interprocess communication, and th...
[ 4 ]
[]
[]
[ "popen", "python", "subprocess" ]
stackoverflow_0005399166_popen_python_subprocess.txt
Q: python file without extension works, but with .py extension fails to import my module My python file has "from .. import" statement to package under C:\Python27\Lib\site-packages. If my file name does not have any extension (e.g. foo ) then "python foo" works. If I rename file from foo to foo.py then the "from ....
python file without extension works, but with .py extension fails to import my module
My python file has "from .. import" statement to package under C:\Python27\Lib\site-packages. If my file name does not have any extension (e.g. foo ) then "python foo" works. If I rename file from foo to foo.py then the "from .. import" statement to that package fails in foo.py: try: from my_package.System.prefi...
[ "I'm going to make a wild guess here: is your filename the same as the package that you're trying to import (my_package in your example)?\nI was able to reproduce behavior similar to what you describe by creating a file, django.py, that contained the import statement from django.db import models. When I ran python...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005399827_python.txt
Q: Why is this def function not being executed in Python? Python is simply bringing up another prompt when I enter the following piece of code from Zed Shaw exercise 18. # this one is like our scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # ok, that *args...
Why is this def function not being executed in Python?
Python is simply bringing up another prompt when I enter the following piece of code from Zed Shaw exercise 18. # this one is like our scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2: %r" % (arg1, arg2) # ok, that *args is actually pointless, we can just do this def print_two_ag...
[ "The indentation of the last four lines is wrong. Because they're indented, the python interpreter thinks they're part of print_none(). Unindent them, and the interpreter will call them as expected. It should look like this:\n>>> print_two(\"Zed\",\"Shaw\")\n[... etc ...]\n\n", "def defines a function. Functions...
[ 4, 2, 1, 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0005400473_function_python.txt
Q: Function call in Google App Engine - Python In main.py I have a display code that repeats several times. So I created a f1.py and placed the code in f1.py as a function display(query) and I am calling it from main.py as f1.display(query). But display(query) has the line self.response.out.write( # some code ) an...
Function call in Google App Engine - Python
In main.py I have a display code that repeats several times. So I created a f1.py and placed the code in f1.py as a function display(query) and I am calling it from main.py as f1.display(query). But display(query) has the line self.response.out.write( # some code ) and I get the error message: self.response.out.writ...
[ "self is a conventional name for the first argument passed to a class instance's methods. A class instance will pass a reference to itself as the first argument to all of it's methods when they are called. It's common practice to name the first parameter for instance methods self.\nSo, when you factored out part ...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005400417_google_app_engine_python.txt
Q: Python/Google app engine data storage performance In a python/google app engine app, I've got a choice between storing some static data (couple KB in size) in a local json/xml file or putting it into the datastore and querying it from there. The data is created by me, so there's no issues with badly formed data. ...
Python/Google app engine data storage performance
In a python/google app engine app, I've got a choice between storing some static data (couple KB in size) in a local json/xml file or putting it into the datastore and querying it from there. The data is created by me, so there's no issues with badly formed data. In specific terms such as saving quota, less resource ...
[ "If your data is small, static and infrequently changed, you'll get the best performance by just writing your data as a dict in it's own module and just import it where you need it. This would take advantage of the fact that Python will cache your modules on import.\n", "For superior app performance, as Chris and...
[ 5, 1, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "json", "performance", "python" ]
stackoverflow_0005395782_google_app_engine_google_cloud_datastore_json_performance_python.txt
Q: Changing the Django data type in models without dropping the table I have created a Django application. Now i wanted to change the field type for 1 of my db field in models. Since there are some records already in the database with the present type, i guess its not possible to change the type by simply changing it...
Changing the Django data type in models without dropping the table
I have created a Django application. Now i wanted to change the field type for 1 of my db field in models. Since there are some records already in the database with the present type, i guess its not possible to change the type by simply changing it in models.py. By googling i came to know that it can be changed without...
[ "The app you need is South\nHere are the steps (refer to the doc for more details) : \n./manage.py convert_to_south yourapp \n\nthis will create a migration folder and fake a first migration \nThen add a new_dateOfJoin DateField in your models.py :\n./manage.py migrate yourapp \n\nthis will create and apply immed...
[ 19, 2, 0 ]
[]
[]
[ "django", "django_models", "mysql", "postgresql", "python" ]
stackoverflow_0005373906_django_django_models_mysql_postgresql_python.txt
Q: How to move python project from Netbeans in windows to Ubuntu Ok, so I spent about 20 hours trying to install pypoker and wxPython in windows and finally gave up. So I installed Ubuntu and got that working. Now, how do i get my Netbeans project to Ubuntu? i straight up copied my src folder in netbeans and put it i...
How to move python project from Netbeans in windows to Ubuntu
Ok, so I spent about 20 hours trying to install pypoker and wxPython in windows and finally gave up. So I installed Ubuntu and got that working. Now, how do i get my Netbeans project to Ubuntu? i straight up copied my src folder in netbeans and put it in ubuntu, but when i typed python "name", all i get is segmentation...
[ "Start by installing netbeans Install netbeans http://bit.ly/software-large and go from there. \nNot sure of the exact dependencies, but try installing python-wxgtk2.8 (or 2.6) and wx-common (and possibly python-wxtools) if you haven't. \n" ]
[ 1 ]
[]
[]
[ "netbeans", "python", "ubuntu", "wxpython" ]
stackoverflow_0005400833_netbeans_python_ubuntu_wxpython.txt
Q: Parse This Custom Twitter Capture Data With Python and Create Statistics I'm trying to gather Twitter statistics from a specific dataset that was provided to me. I have no control over how the data is formatted before it is given to me so I'm locked into this messy for. I would like some suggestions on how I can b...
Parse This Custom Twitter Capture Data With Python and Create Statistics
I'm trying to gather Twitter statistics from a specific dataset that was provided to me. I have no control over how the data is formatted before it is given to me so I'm locked into this messy for. I would like some suggestions on how I can build a python program to parse this sort of input and outputting something mor...
[ "The input here is JSON. Python has a JSON module. Happily it has a CSV module too. So that's your input and output taken care of!\nUpdate\nYou are getting there!\nYour call to writerow() needs to look more like (not in a for-loop):\nf.writerow( \n (\n jsonindata['contributors'],\n json...
[ 4, 4 ]
[]
[]
[ "csv", "json", "python", "twitter" ]
stackoverflow_0005400977_csv_json_python_twitter.txt
Q: Type Error in nested for loops Homework problem for class that involves invoking several for loops, here's the hw problem: Average Temperature Write a program that uses nested loops to collect data and calculate the average temperature over a period of months. The program should first ask for the number of months....
Type Error in nested for loops
Homework problem for class that involves invoking several for loops, here's the hw problem: Average Temperature Write a program that uses nested loops to collect data and calculate the average temperature over a period of months. The program should first ask for the number of months. The outer loop will iterate once fo...
[ "Read the error: you are giving input 5 arguments.\nConcat strings with + operator, not commas\n", "num1 = input('Please enter the average temperature for week %s in month %s: '%(y,i))\n", "As was suggested in the comments, look at other ways of joining strings.\nhttp://skymind.com/~ocrow/python_string/\n" ]
[ 1, 1, 0 ]
[]
[]
[ "debugging", "for_loop", "loops", "python" ]
stackoverflow_0005401129_debugging_for_loop_loops_python.txt
Q: Problem understanding Importer Protocol in Python I'm having some trouble understanding the Importer Protocol as per http://www.python.org/dev/peps/pep-0302/. Should the fullname argument of finder.find_module(fullname, path=None) never include a . (dot)? That is, if you want to find module abc.efg.hij, you must c...
Problem understanding Importer Protocol in Python
I'm having some trouble understanding the Importer Protocol as per http://www.python.org/dev/peps/pep-0302/. Should the fullname argument of finder.find_module(fullname, path=None) never include a . (dot)? That is, if you want to find module abc.efg.hij, you must call finder.find_module('hij', path='abc.efg'). Calling ...
[ "No, it is just saying that import abc.efg.hij will eventually result in 3 different find_module calls at various stages of the import process:\nfind_module(\"abc\", None)\nfind_module(\"abc.efg\", abc.__path__)\nfind_module(\"abc.efg.hij\", abc.efg.__path__)\n\nExploring the importlib documentation may also be of ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005401186_python.txt
Q: Adding values to a list I'm an R newbie and am trying to create a basic "database" for my comic books. However, I have a problem. The idea is to place each new entry as a list. I assumed that I could set up the lists to look like the following. [Thor, 50, Marvel] [Thor, 51, Marvel] [Thor, 52, Marvel] ... eventual...
Adding values to a list
I'm an R newbie and am trying to create a basic "database" for my comic books. However, I have a problem. The idea is to place each new entry as a list. I assumed that I could set up the lists to look like the following. [Thor, 50, Marvel] [Thor, 51, Marvel] [Thor, 52, Marvel] ... eventually, I 'd like to include entr...
[ "You should use a nested structure.\ncomicdb.append((title, issue, publisher))\n\n", "The answer is simple. you insert 3 words to the list instead of appending a list which contains the 3 words.\nIt should be like this:\noption = 0\ncomicdb = []\n\nwhile option != 3:\n print \"--------------------------\"\n ...
[ 4, 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005400351_python.txt
Q: Filter whitespace and newlines with Pygments I've been trying to add syntax highlighting to my django site. The problem is I'm getting the &nbsp; and <br /> characters formatted as well. Is there a way to preserve these characterss? Here is the code I'm using: from BeautifulSoup import BeautifulSoup from django i...
Filter whitespace and newlines with Pygments
I've been trying to add syntax highlighting to my django site. The problem is I'm getting the &nbsp; and <br /> characters formatted as well. Is there a way to preserve these characterss? Here is the code I'm using: from BeautifulSoup import BeautifulSoup from django import template from django.template.defaultfilters...
[ "Well, Petri is right, pre is for code blocks. Before he pointed that out I just wrote a function to clean the first output, it's messy but maybe someone who just needs to remove certain things from the final output might find it ok:\nfrom BeautifulSoup import BeautifulSoup\nfrom django import template\nfrom djang...
[ 1 ]
[]
[]
[ "pygments", "python" ]
stackoverflow_0005385779_pygments_python.txt
Q: Javascript validation error on using with Django I have created a django application. Using this app users can be created or deleted. But while creating a user, when we leave 1 of the field (Employee ID Field) null its not getting submitted and its throwing this error - invalid literal for int() with base 10: '' ....
Javascript validation error on using with Django
I have created a django application. Using this app users can be created or deleted. But while creating a user, when we leave 1 of the field (Employee ID Field) null its not getting submitted and its throwing this error - invalid literal for int() with base 10: '' . So i guess validating that field alone and submitting...
[ "mistake: \"if ((\" two brackets opened\n--- UPDATE ---\nFirst of all, if you get an error about converting empty or null to a number, that means you have your code wrong. Fixing it by having additional verification at the javascript means you're making very nasty workaround without fixing error itself - if javascr...
[ 2 ]
[]
[]
[ "django", "django_forms", "javascript", "python", "validation" ]
stackoverflow_0005401890_django_django_forms_javascript_python_validation.txt
Q: Regular expression help for a date (python+ im trying to create an expression that matches 11.11.11 but not 111.11.111 i'm using python keyword = re.compile(r"[0-9]*[0-9]\.[0-9]*[0-9]\.[0-9]*[0-9]") the date could be at the start/end of a sentence and not have a white space but a next line before/after. how woul...
Regular expression help for a date (python+
im trying to create an expression that matches 11.11.11 but not 111.11.111 i'm using python keyword = re.compile(r"[0-9]*[0-9]\.[0-9]*[0-9]\.[0-9]*[0-9]") the date could be at the start/end of a sentence and not have a white space but a next line before/after. how would i account for both ? as it is this will pick up...
[ "* means \"zero or more of the preceding token\". Therefore your regex will match anything from 1.1.1 to 999999.999999.99999 etc.\nYou can be more specific like this:\nkeyword = re.compile(r\"\\b[0-9]{2}\\.[0-9]{2}\\.[0-9]{2}\\b\")\n\nThe \\b word boundary anchors make sure that the numbers start/end at that positi...
[ 3, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005402332_python_regex.txt
Q: problem Deleting list items in a for loop (python) Possible Duplicate: Remove items from a list while iterating in Python Hi im having a problem i cant seem to delete items whilst iterating through a list in python, Here is what i've got: a title should be removed if a user Inputs n or N when asked the question ...
problem Deleting list items in a for loop (python)
Possible Duplicate: Remove items from a list while iterating in Python Hi im having a problem i cant seem to delete items whilst iterating through a list in python, Here is what i've got: a title should be removed if a user Inputs n or N when asked the question to delete in the for loop, the problem is that when its...
[ "The below code will fix your issue. You have to iterate over a copy of the list. You can't remove items from the list you are iterating over.\nimport copy\n\ndef main():\n titles_list = [\"English\", \"Math\", \"History\", \"IT\", \"Biology\", \"Spanish\"]\n titles_list_orig = copy.deepcopy(titles_list)\n\n ...
[ 16, 8, 1, 1 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0005401601_list_loops_python.txt
Q: Since Django discourages passing arguments to functions in templates, what is encouraged instead? I understand that in Django, the template language is purposely neutered to prevent too much computation in display code. It means that, ideally, for every situation where users might feel compelled to do computation,...
Since Django discourages passing arguments to functions in templates, what is encouraged instead?
I understand that in Django, the template language is purposely neutered to prevent too much computation in display code. It means that, ideally, for every situation where users might feel compelled to do computation, there's a more proper alternative. Either a tag or filter that does the trick, or something hopefully ...
[ "I don't see why creating a custom tag or filter is an 'abuse'. As far as I'm concerned, that's exactly what they're for, and I use them for that all the time.\n", "Maybe Jinja templates would be a good alternative to using Django's templating system in this instance. Apart from the important fact that Jinja allo...
[ 4, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005400632_django_python.txt
Q: django - regex for optional url parameters I have a view in django that can accept a number of different filter parameters, but they are all optional. If I have 6 optional filters, do I really have to write urls for every combination of the 6 or is there a way to define what parts of the url are optional? To give...
django - regex for optional url parameters
I have a view in django that can accept a number of different filter parameters, but they are all optional. If I have 6 optional filters, do I really have to write urls for every combination of the 6 or is there a way to define what parts of the url are optional? To give you an example with just 2 filters, I could hav...
[ "One method would be to make the regular expression read all the given filters as a single string, and then split them up into individual values in the view.\nI came up with the following URL:\n(r'^(?P<city>[^/]+)/(?P<state>[^/]+)(?P<filters>(?:/[^/]+/[^/]+)*)/?$',\n 'views.my_view'),\n\nMatching the required city ...
[ 9, 8, 2 ]
[ "Try use something like that in your urls.py:\nurl(r'^(?P<city>[^/]+)/(?P<state>[^/]+)/(radius/(?P<miles>[^/]+)/|company/(?P<company_name>[^/]+)/)*$', 'view')\n\n" ]
[ -1 ]
[ "django", "python", "url_pattern", "urlconf" ]
stackoverflow_0005399035_django_python_url_pattern_urlconf.txt
Q: generating a grid in a function We made a little script in computer science class for finding the shortest path through a grid of nodes, some interlinked, some not. The griddata is stored in a way that doesn't require to define any new classes, namely in a nested list. For n nodes, the list should have n elements,...
generating a grid in a function
We made a little script in computer science class for finding the shortest path through a grid of nodes, some interlinked, some not. The griddata is stored in a way that doesn't require to define any new classes, namely in a nested list. For n nodes, the list should have n elements, each being a list with n elements. g...
[ " res=[[0]*nodes]*nodes\n\nprobably doesn't do what you think it does:\n>>> nodes = 3\n>>> res=[[0]*nodes]*nodes\n>>> res\n[[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n>>> res[0][0] = 'echo'\n>>> res\n[['echo', 0, 0], ['echo', 0, 0], ['echo', 0, 0]]\n\nInstead of making three separate lists [0,0,0], it gives you three refere...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005402357_python.txt
Q: How to JSON encode? Possible Duplicate: How to JSON encode Entities? I'm getting started with Google App Engine. I want to make AJAX chat like Twitter. class ChatMessage(db.Model): message = db.StringProperty() created = db.DateTimeProperty(auto_now=True) Server JSON encodes the response, class RPCHandler(w...
How to JSON encode?
Possible Duplicate: How to JSON encode Entities? I'm getting started with Google App Engine. I want to make AJAX chat like Twitter. class ChatMessage(db.Model): message = db.StringProperty() created = db.DateTimeProperty(auto_now=True) Server JSON encodes the response, class RPCHandler(webapp.RequestHandler): ...
[ "See the Python documentation:\nhttp://docs.python.org/library/json.html\n(Specifically, look at the API method 'json.dump')\n", "Python has a module called json which can automatically serialize and deserialize dictionaries, lists, and other native Python objects (or complex types if you provide the interface). ...
[ 0, 0, 0 ]
[]
[]
[ "google_app_engine", "json", "python" ]
stackoverflow_0005401309_google_app_engine_json_python.txt
Q: Is there a way to programmatically stop web.py? I'm trying to run web.application in a Windows Service and I cannot find a way to programmatically stop it after application.run(). I tried sys.exit and it didn't work well with Windows Service. A: I solved the question I originally raised by looking into web.py so...
Is there a way to programmatically stop web.py?
I'm trying to run web.application in a Windows Service and I cannot find a way to programmatically stop it after application.run(). I tried sys.exit and it didn't work well with Windows Service.
[ "I solved the question I originally raised by looking into web.py source code, and exposed the WSGIServer in web/httpserver.py to web/application.py, so that i can call WSGIServer.stop() in application.stop(), which is added by myself.\nIt's a quick hack and not that neat, but it removed the blocker quickly.\n" ]
[ 5 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0005389111_python_web.py.txt
Q: copy contents of one table to another table in django How do I copy all the rows in a django table to a new table while retaining the old table contents? A: Execute raw SQL directly: from django.db import connection, transaction cursor = connection.cursor() # commit required cursor.execute("SELECT * INTO %s FROM...
copy contents of one table to another table in django
How do I copy all the rows in a django table to a new table while retaining the old table contents?
[ "Execute raw SQL directly:\nfrom django.db import connection, transaction\ncursor = connection.cursor()\n# commit required\ncursor.execute(\"SELECT * INTO %s FROM %s\" % (newtable, oldtable))\ntransaction.commit_unless_managed()\n\nWorking from model objects, the table name will be stored in _meta.db_table\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005401561_django_python.txt
Q: wxpython global variables im trying to create global variables of wx.Panel, wx.Button, and wx.TextCtrl, so that i can "Edit" them in different functions coming from a java background i thought maybe "panel = wx.Panel()" outside all functions might work but i get an error saying i need to send arguments to it, and ...
wxpython global variables
im trying to create global variables of wx.Panel, wx.Button, and wx.TextCtrl, so that i can "Edit" them in different functions coming from a java background i thought maybe "panel = wx.Panel()" outside all functions might work but i get an error saying i need to send arguments to it, and i dont know what those argument...
[ "It takes the arguments defined by the wxPanel constructor.\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0005402358_python_wxpython.txt
Q: how can i use sharepoint (via soap?) from python? I want to use Sharepoint with python (C-Python) Has anyone tried this before ? A: I suspect that since this question was answered the SUDS library has been updated to take care of the required authentication itself. After jumping through various hoops, I found th...
how can i use sharepoint (via soap?) from python?
I want to use Sharepoint with python (C-Python) Has anyone tried this before ?
[ "I suspect that since this question was answered the SUDS library has been updated to take care of the required authentication itself. After jumping through various hoops, I found this to do the trick:\n\nfrom suds import WebFault\nfrom suds.client import *\nfrom suds.transport.https import WindowsHttpAuthenticated...
[ 10, 9, 4, 3 ]
[]
[]
[ "ntlm", "python", "sharepoint", "soap", "suds" ]
stackoverflow_0000218987_ntlm_python_sharepoint_soap_suds.txt
Q: cPickle file using protocol option I have silly question. Is possible to re-pickle(cPickle) an already cPickled file using another protocol option, and also which protocol would be best for a very large file. Would appreciate any help/suggestions. A: I don't really understand what you mean by pickling a file. Do...
cPickle file using protocol option
I have silly question. Is possible to re-pickle(cPickle) an already cPickled file using another protocol option, and also which protocol would be best for a very large file. Would appreciate any help/suggestions.
[ "I don't really understand what you mean by pickling a file. Do you want to read a pickled file as binary without unpickling and then pickle it again? This should not be a problem but I do not see what good it would do...\nThe default protocol version in pickle is 0, ASCII (pickle docs). The latest binary protocol ...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005386582_python.txt
Q: Where to put generic Database Tables on Django? I'm trying to start with Django. I'm developing an App. This App is called "Directory" and will store info about websites. I must to create a database table called "Genders", but this is a generic database table and could be used in other App. My question... how to d...
Where to put generic Database Tables on Django?
I'm trying to start with Django. I'm developing an App. This App is called "Directory" and will store info about websites. I must to create a database table called "Genders", but this is a generic database table and could be used in other App. My question... how to deal with this kind of situation in Django? And in wic...
[ "In django, you don't (generally) create database tables. You create models, and let the django ORM create tables for you.\nTo prevent having two tables in your database called gender, django will prefix the model name with the name of the app. Thus, if your app was called foo, your model class was Gender, you woul...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005402847_django_python.txt
Q: Numpy manipulating array of True values dependent on x/y index So I have an array (it's large - 2048x2048), and I would like to do some element wise operations dependent on where they are. I'm very confused how to do this (I was told not to use for loops, and when I tried that my IDE froze and it was going really ...
Numpy manipulating array of True values dependent on x/y index
So I have an array (it's large - 2048x2048), and I would like to do some element wise operations dependent on where they are. I'm very confused how to do this (I was told not to use for loops, and when I tried that my IDE froze and it was going really slow). Onto the question: h = aperatureimage h[:,:] = 0 indices = n...
[ "Could you perhaps post a minimal, yet complete, example? One that we can copy/paste and run ourselves?\nIn the meantime, in the first two lines of your current example:\nh = aperatureimage\nh[:,:] = 0\n\nyou set both 'aperatureimage' and 'h' to 0. That's probably not what you intended. You might want to consider:\...
[ 2 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0005400915_numpy_python_scipy.txt
Q: regular expression question (python) I want to read a word html file and grab any words which contain letters of a name but not print them if the words are longer than the name # compiling the regular expression: keyword = re.compile(r"^[(rR)|(yY)|(aA)|(nN)]{5}$/") if keyword.search (line): print line, i a...
regular expression question (python)
I want to read a word html file and grab any words which contain letters of a name but not print them if the words are longer than the name # compiling the regular expression: keyword = re.compile(r"^[(rR)|(yY)|(aA)|(nN)]{5}$/") if keyword.search (line): print line, i am grabbing the words with this but don't s...
[ "it seems you are looking for keyword.match() instead of keyword.search(). you should read this part of the python documentation which discusses the difference between match and search.\nalso, your regular expression seems completely off... [ and ] delimits a set of characters, so you can't put groups and have a lo...
[ 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005402900_python_regex.txt
Q: Is there a way to close a workbook using xlrd I am using the function open_workbook() to open an excel file. But I cannot find any function to close the file later in the xlrd module. Is there a way to close the xls file using xlrd? Or is not required at all? A: Digging into the mailing list archive, it seems th...
Is there a way to close a workbook using xlrd
I am using the function open_workbook() to open an excel file. But I cannot find any function to close the file later in the xlrd module. Is there a way to close the xls file using xlrd? Or is not required at all?
[ "Digging into the mailing list archive, it seems that the file object is closed directly by the constructor, so you don't need to close it explicitly.\n", "The open_workbook calls the release_resources ( which closes the mmaped file ) before returning.\n" ]
[ 22, 6 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0005403781_python_xlrd.txt
Q: string, regular expressions in python From the following question How to automatically remove certain preprocessors directives and comments from a C header-file? header = "" #some string p_macro = re.compile("#if.*?#endif", re.MULTILINE + re.DOTALL) p_comment = re.compile("/\*.*?\*/", re.MULTILINE + re.DOTALL) ...
string, regular expressions in python
From the following question How to automatically remove certain preprocessors directives and comments from a C header-file? header = "" #some string p_macro = re.compile("#if.*?#endif", re.MULTILINE + re.DOTALL) p_comment = re.compile("/\*.*?\*/", re.MULTILINE + re.DOTALL) # Example ... # print re.sub(p_macro, ...
[ "p_macro = re.compile(\"#(end)?if.*?#(?(1)|end)if\",re.DOTALL)\n\nre.MULTILINE is useless because there is no character '^' and no '$' in the RE\nPossibly, you will have to add such correction endlessly.....\n" ]
[ 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005403050_python_string.txt
Q: xcopy python deployment I'm new to python and I'm writing my first program. I would like after I finish to be able to run the program from the source code on a windows or mac machine. My program has dependencies on 3rd party modules. I read about virtualenv but I don't think it helps me because it says it's not re...
xcopy python deployment
I'm new to python and I'm writing my first program. I would like after I finish to be able to run the program from the source code on a windows or mac machine. My program has dependencies on 3rd party modules. I read about virtualenv but I don't think it helps me because it says it's not relocatable and it's not cross-...
[ "You can do what you want, you just have to make sure that the directory containing your third-party modules is on the python path.\nThere's no requirement to install modules system-wide.\n", "Note, while packaging your whole app with py2exe may not be an option, you can use it to make a simple launcher environme...
[ 1, 1, 0, 0 ]
[]
[]
[ "installation", "module", "python", "virtualenv" ]
stackoverflow_0005093349_installation_module_python_virtualenv.txt
Q: Datetime field on Django to store the date of insertion of row? I'm new to Django. I'm starting a new App and I'm currently on the Models. I need to store the date of the insertion of the line and when the line suffer from an UPDATE I need to store that date too. My models.py from django.db import models class Di...
Datetime field on Django to store the date of insertion of row?
I'm new to Django. I'm starting a new App and I'm currently on the Models. I need to store the date of the insertion of the line and when the line suffer from an UPDATE I need to store that date too. My models.py from django.db import models class Directorio(models.Model): n_site = models.CharField(max_l...
[ "Documented in django here.\ndate_inserted = models.DateTimeField(auto_now_add=True)\ndate_last_update = models.DateTimeField(auto_now=True)\n\n" ]
[ 4 ]
[]
[]
[ "django", "postgresql", "python" ]
stackoverflow_0005404458_django_postgresql_python.txt
Q: How to take a user sentence and create a list of words out of it? I'm unsure what the user will enter but I want to break their input sentence up into words in a list User_input = raw_input("Please enter a search criterion: ") User_Input_list[""] # input example: steve at the office # compiling the regular expre...
How to take a user sentence and create a list of words out of it?
I'm unsure what the user will enter but I want to break their input sentence up into words in a list User_input = raw_input("Please enter a search criterion: ") User_Input_list[""] # input example: steve at the office # compiling the regular expression: keyword = re.compile(r"\b[aA-zZ]\b") for word in User_input...
[ "User_Input_list = User_input.split()\n\n", "The easiest solution is probably to use split:\n>>> \"steve at the office\".split()\n['steve', 'at', 'the', 'office']\n\nBut this won't remove punctuation, which may or may not be a problem for you:\n>>> \"steve at the office.\".split()\n['steve', 'at', 'the', 'office....
[ 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005403349_list_python.txt
Q: What's the package name in django for urlfetch Which package is used to import for same work in django, what we do with from google.appengine.api import urlfetch in google app engine... A: urllib2 A: urllib(Open arbitrary resources by URL), urllib2(extensible library for opening URLs) These are python librarie...
What's the package name in django for urlfetch
Which package is used to import for same work in django, what we do with from google.appengine.api import urlfetch in google app engine...
[ "urllib2\n", "urllib(Open arbitrary resources by URL), urllib2(extensible library for opening URLs)\nThese are python libraries and not django packages.\n" ]
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005402034_django_python.txt
Q: Are there any cpython libraries that work with jsr168 and/or jsr286? On a Java portal you can have portlets that include data provided by other applications. We want to replace our existing Java portal with a Django application, which means duplicating the Java portal's ability to display portlets. The two Sun spe...
Are there any cpython libraries that work with jsr168 and/or jsr286?
On a Java portal you can have portlets that include data provided by other applications. We want to replace our existing Java portal with a Django application, which means duplicating the Java portal's ability to display portlets. The two Sun specifications in question that we want to duplicate are JSR168 and JSR286. I...
[ "I'm not sure you can do this. From JSR 168:\n\nIf I understand correctly, you want the Django application to take the place of the existing \"Java Portal/Portlet Container\" in the diagram. Unfortunately, the interface between the portlet container and the individual portlets is using in-memory API calls, not as a...
[ 3, 0 ]
[]
[]
[ "django", "jsr168", "jsr286", "python" ]
stackoverflow_0001379607_django_jsr168_jsr286_python.txt
Q: Zero-value colour in matplotlib hexbin I have some spatially-distributed data. I'm plotting this with matplotlib.pyplot.hexbin and would like to change the "background" (i.e. zero-value) colour. An example is shown below - my colour-map of choice is matplotlib.cm.jet: How can I change the base colour from blue to...
Zero-value colour in matplotlib hexbin
I have some spatially-distributed data. I'm plotting this with matplotlib.pyplot.hexbin and would like to change the "background" (i.e. zero-value) colour. An example is shown below - my colour-map of choice is matplotlib.cm.jet: How can I change the base colour from blue to white? I have done something similar with m...
[ "hexbin(x,y,mincnt=1) should do the trick. Essentially, you only want to display the hexagons with more than 1 count in them.\nfrom numpy import linspace\nfrom numpy.random import normal\nfrom pylab import hexbin,show\n\nn = 2**6\n\nx = linspace(-1,1,n)\ny = normal(0,1,n)\n\nh = hexbin(x,y,gridsize=10,mincnt=0)\n\n...
[ 21 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0005402898_matplotlib_plot_python.txt
Q: problem with python list Hi im trying to create a list adding to it via a for loop reading line by line from a txt file. Im getting a syntax error on the list but am unsure about how to fix the problem ??? import re file = open("text.txt","r") text = file.readlines() file.close() line_count=0 for line in text: ...
problem with python list
Hi im trying to create a list adding to it via a for loop reading line by line from a txt file. Im getting a syntax error on the list but am unsure about how to fix the problem ??? import re file = open("text.txt","r") text = file.readlines() file.close() line_count=0 for line in text: User_Input_list[] += [] + ...
[ "Do it like this:\ninput = []\nline_count = 0\nwith open(\"text.txt\",\"r\") as file:\n for line in file:\n input.extend(line.split())\n line_count += 1\n\n", "Why not\nUserInputList += line.split()?\n", "If you want each line in the file to be a separate element in the list, here's a simpler w...
[ 7, 0, 0 ]
[]
[]
[ "list", "python", "text_files" ]
stackoverflow_0005405887_list_python_text_files.txt
Q: Detect Areas of Text in Screenshot I'm working on a project to increase the ability for wine to automatically test software packages. What I'm looking to do now is detect text in the screen capture of the current window. I can then parse all of the text and use autohotkey to give a mouse click on the coordinates o...
Detect Areas of Text in Screenshot
I'm working on a project to increase the ability for wine to automatically test software packages. What I'm looking to do now is detect text in the screen capture of the current window. I can then parse all of the text and use autohotkey to give a mouse click on the coordinates of the text I want. For example, in firef...
[ "A possible starting point is Project SIKULI. It is a tool to automate GUI testing. It is written in Java, nonetheless it includes a scripting environment based on Jython, hence modifying it to support python script may be not too difficult.\n" ]
[ 1 ]
[]
[]
[ "image_processing", "linux", "ocr", "python" ]
stackoverflow_0005405902_image_processing_linux_ocr_python.txt
Q: Prevent SFTP/SSH session timeout with paramiko I'm using paramiko to connect to an SFTP server on which I have to download and process some files. The server has a timeout set to 5 minutes, but some days it happens that the processing of the files can take longer than the timeout. So, when I want to change the wor...
Prevent SFTP/SSH session timeout with paramiko
I'm using paramiko to connect to an SFTP server on which I have to download and process some files. The server has a timeout set to 5 minutes, but some days it happens that the processing of the files can take longer than the timeout. So, when I want to change the working directory on the server to process some other f...
[ "If the server is timing you out for inactivity, there's not much you can do from the client-side (other than perhaps send a simple command every now and again to keep your session from timing out).\nHave you considered breaking apart your download and processing steps, so that you can download everything you need ...
[ 6 ]
[]
[]
[ "paramiko", "python", "sftp", "ssh", "timeout" ]
stackoverflow_0005402919_paramiko_python_sftp_ssh_timeout.txt
Q: What is the equivalent of Matlab 'fscanf' in Python? The Matlab function fscanf() seems to be very powerful. Is there any equivalent of the same in python (or numpy)? Specifically I want to read a matrix from file but I don't want to iterate through each line to read the matrix. Something of this sort (from matlab...
What is the equivalent of Matlab 'fscanf' in Python?
The Matlab function fscanf() seems to be very powerful. Is there any equivalent of the same in python (or numpy)? Specifically I want to read a matrix from file but I don't want to iterate through each line to read the matrix. Something of this sort (from matlab for reading a 2D 1000x1000 matrix): matrix = fscanf(fope...
[ "Python has no built-in fscanf function. The closest way to do it is to read the file line by line and use regular expressions.\nNumpy (the Matlab-like Python library), however, has a function that allows to read a file and construct an array from is content : numpy.fromfile (or, as suggested in the other answers, ...
[ 5, 3, 1, 0, 0 ]
[]
[]
[ "matlab", "python", "scanf" ]
stackoverflow_0005402468_matlab_python_scanf.txt
Q: SQLAlchemy Self Referencing Relationship - NoReferencedTableError I'm using SA 0.6.6, Declarative style, against Postgres 8.3, to map Python objects to a database. I have a table that is self referencing and I'm trying to make a relationship property for it's children. No matter what I try, I end up with a NoRef...
SQLAlchemy Self Referencing Relationship - NoReferencedTableError
I'm using SA 0.6.6, Declarative style, against Postgres 8.3, to map Python objects to a database. I have a table that is self referencing and I'm trying to make a relationship property for it's children. No matter what I try, I end up with a NoReferencedTableError. My code looks exactly like the sample code from the...
[ "This was a foolish mistake on my part. I typically specify my FK's by specifying the Entity type, not the string. I am using different schemas, so when defining the FK entity as a string I also need the schema.\nBroken:\nparentFolderId = Column(Integer,ForeignKey('FilterFolder.id'))\n\nFixed:\nparentFolderId = C...
[ 2, 1 ]
[]
[]
[ "python", "self_reference", "sqlalchemy" ]
stackoverflow_0005397382_python_self_reference_sqlalchemy.txt
Q: Counting frequency of words in documents using python regex Created a python module which reads in a file, removes the stop words and outputs a python dictionary with the word and its frequency (How many times it occurred in the document). def run(): filelist = os.listdir(path) regex = re.compile(r'.*<div class="b...
Counting frequency of words in documents using python regex
Created a python module which reads in a file, removes the stop words and outputs a python dictionary with the word and its frequency (How many times it occurred in the document). def run(): filelist = os.listdir(path) regex = re.compile(r'.*<div class="body">(.*?)</div>.*', re.DOTALL | re.IGNORECASE) reg1 = re.compile...
[ "The fileinput module lets you easily handle multiple files. \n", "The backslash in '<\\/?[ap][^>]*>' is useless because '/' isn't a special character\n'[^\\w]' is '\\W' By the way '[^\\w]+' will be more efficient than just one '[^\\w]'\nre.DOTALL is useless with r'<\\/?[ap][^>]*>' since there is no dot in th...
[ 2, 2, 0, 0 ]
[]
[]
[ "count", "dictionary", "frequency", "python", "regex" ]
stackoverflow_0005405551_count_dictionary_frequency_python_regex.txt
Q: Avoid passing RequestContext in every render in django I am developing a site right now that, once you are logged in, a search bar will always be present on the top of the page. I am wondering what the best way design this paradigm in Django. Currently, I have a separate file called forms.py that sits at settings....
Avoid passing RequestContext in every render in django
I am developing a site right now that, once you are logged in, a search bar will always be present on the top of the page. I am wondering what the best way design this paradigm in Django. Currently, I have a separate file called forms.py that sits at settings.py level in my folder hierarchy. In almost every view, I hav...
[ "Use a context processor\nAdd your search form to the context of all views using RequestContext, which the new render you're using does automatically.\ndef FormContextProcessor(request):\n if request.user.is_authenticated():\n return {'form': SearchForm() }\n return {}\n\nYou said it's used in nearly a...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005406393_django_python.txt
Q: How to wrap an init/cleanup function in Boost python I recently discovered the existence of boost-python and was astonished by it's apparent simplicity. I wanted to give it a try and started to wrap an existing C++ library. While wrapping the basic library API calls is quite simple (nothing special, just regular f...
How to wrap an init/cleanup function in Boost python
I recently discovered the existence of boost-python and was astonished by it's apparent simplicity. I wanted to give it a try and started to wrap an existing C++ library. While wrapping the basic library API calls is quite simple (nothing special, just regular function calls and very common parameters), I don't know ho...
[ "You could try to do a guard object and assign it to a hidden attribute of your module.\nstruct MyLibGuard\n{\n MyLibGuard() { myLib::initialize();}\n ~MyLibGuard() { myLib::cleanup();}\n};\n\nusing namespace boost::python;\n\nBOOST_PYTHON_MODULE(arch_lib)\n{\n boost::shared_ptr<MyLibGuard> libGuard = new ...
[ 9 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0005406334_boost_python_c++_python.txt
Q: Characters turning up in POST data I'm running a high traffic ssl website with apache/mod_wsgi/python. Very occasionally (around 10x in 3 months) I've seen some extra garbage characters in post data. Usually it's been in the form of a extra char at the end. ('access.uid', 'allow\xba') ('checksum', 'b219d6a006ebd95...
Characters turning up in POST data
I'm running a high traffic ssl website with apache/mod_wsgi/python. Very occasionally (around 10x in 3 months) I've seen some extra garbage characters in post data. Usually it's been in the form of a extra char at the end. ('access.uid', 'allow\xba') ('checksum', 'b219d6a006ebd95691d0d7b468a94510496c5dd8\xff') Once th...
[ "What version of Apache are you using? From memory, somewhere around Apache 2.2.12-2.2.15 there were various SSL fixes. You might want to ensure you are using Apache 2.2.15 or later.\n", "what happens if you print eval(\"u'%s'\"%garbled_text)? does the output look likely (I understand that you may not be able to ...
[ 2, 0, 0, 0 ]
[]
[]
[ "apache", "mod_wsgi", "python" ]
stackoverflow_0005315737_apache_mod_wsgi_python.txt
Q: Screenchange Event Is there a way to know whether the screen has been changed or not ? A: I think that it should possible by setting a GetMsgProc hook in order to detect every WM_PAINT event. The hook should just change a flag in a shared memory read by the main RDP process.
Screenchange Event
Is there a way to know whether the screen has been changed or not ?
[ "I think that it should possible by setting a GetMsgProc hook in order to detect every WM_PAINT event.\nThe hook should just change a flag in a shared memory read by the main RDP process.\n" ]
[ 0 ]
[]
[]
[ "c", "python", "windows" ]
stackoverflow_0005405232_c_python_windows.txt
Q: Pyplot colors not as expected Does anyone know why this code doesn't plot the boxes colors correctly. I want each component to be a different color but they all come out black with a blue legend. from numpy import array, zeros import matplotlib.pyplot as plt # Components: Useage times (start, stop), wattage, deta...
Pyplot colors not as expected
Does anyone know why this code doesn't plot the boxes colors correctly. I want each component to be a different color but they all come out black with a blue legend. from numpy import array, zeros import matplotlib.pyplot as plt # Components: Useage times (start, stop), wattage, detail COMPONENTS = {"fridge": ( [(0.0...
[ "Your code, as far as the graph is concerned, is fine. The problem is that there are too many bars, so you only see the black borders. This is what looks when zooming in:\n\nTo get the legend right, pass the label argument while plotting, then just call plt.legend() without arguments when you're done.\n" ]
[ 2 ]
[]
[]
[ "colors", "matplotlib", "python" ]
stackoverflow_0005407207_colors_matplotlib_python.txt
Q: How to get a list of key names in Python/Google app engine? In Python/Google app engine, I'd like to store a property as a key name in order to save resources and speed things up. But I don't know how to get the list of key names. As an example, consider the data model: class Book(db.Model): isbn = db.StringP...
How to get a list of key names in Python/Google app engine?
In Python/Google app engine, I'd like to store a property as a key name in order to save resources and speed things up. But I don't know how to get the list of key names. As an example, consider the data model: class Book(db.Model): isbn = db.StringProperty() # Make this a key name instead. category = db.Strin...
[ "For the first approach, ISBN as key:\nclass Book(db.Model):\n #isbn is key, so it shouldn't be a property\n category = db.StringProperty()\n author = db.StringProperty()\n title = db.StringProperty()\n\nnew_book = Book(category=\"fantasy,comedy\", title=\"The Light Fantastic\", author=\"TerryPratchett\...
[ 3, 1, 1 ]
[]
[]
[ "google_app_engine", "key", "python" ]
stackoverflow_0005407647_google_app_engine_key_python.txt
Q: Python and sharepoint integration I am working on integrating python and sharepoint. I am facing major problems with the GetItems and CopyIntoItems web service calls present in the Copy web service. The library i am using to consume the service is Python-suds . I want to know if 1. Are these are the right methods...
Python and sharepoint integration
I am working on integrating python and sharepoint. I am facing major problems with the GetItems and CopyIntoItems web service calls present in the Copy web service. The library i am using to consume the service is Python-suds . I want to know if 1. Are these are the right methods to be used for downloading/uploading f...
[ "Look at \nhttp://pypi.python.org/pypi/haufe.sharepoint\nIt provides a solid base for adding file operations.\n", "As for downloading files, you can just use a standard HTTP GET for the file. If you look at the metadata that is returned, one of them will be an absolute url to the document. That will work fine o...
[ 2, 1 ]
[]
[]
[ "python", "sharepoint", "web_services" ]
stackoverflow_0005380560_python_sharepoint_web_services.txt
Q: Is RabbitMQ capable of passing messages to specific clients? Or must I perform those checks client-side? I have my software running on a bunch of clients around my network. I've been playing around with RabbitMQ as a solution for passing messages between each client. My test code is this: #!/usr/bin/python2 impor...
Is RabbitMQ capable of passing messages to specific clients? Or must I perform those checks client-side?
I have my software running on a bunch of clients around my network. I've been playing around with RabbitMQ as a solution for passing messages between each client. My test code is this: #!/usr/bin/python2 import pika import time connection = pika.AsyncoreConnection(pika.ConnectionParameters( 'localhos...
[ "You can have as many queue in RabbitMQ. Why not have a queue for messages to the server as well as a queue for each client?\n" ]
[ 1 ]
[]
[]
[ "networking", "python", "rabbitmq" ]
stackoverflow_0005401434_networking_python_rabbitmq.txt
Q: IP address and hostname of remote peer in Twisted TCP client Writing a Jabber client that uses Twisted Words. I would like to know an IP address and hostname of remote peer. xmlstream.transport.getPeer().host return hostname, while it should return IP address (xmlstream is an instance of twisted.words.protocols.ja...
IP address and hostname of remote peer in Twisted TCP client
Writing a Jabber client that uses Twisted Words. I would like to know an IP address and hostname of remote peer. xmlstream.transport.getPeer().host return hostname, while it should return IP address (xmlstream is an instance of twisted.words.protocols.jabber.xmlstream.XmlStream). Update: Yes, my Twisted is rather outda...
[ "You've run into a bug fixed 3 years ago, in Twisted 8.2.0. You should upgrade to a more recent version of Twisted. (I would suggest the recently-announced prerelease of Twisted 11.0; now's a good time to test!) If you've found this bug in a more recent version of Twisted, you should reopen that bug, and explain...
[ 6, 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0005406617_python_twisted.txt
Q: Need Quick & Dirty DOCX Viewing - PyGTK Need: A module containing methods for rendering docx files with formatting. Requirements: PyGTK compatibility is not the python-docx module A: https://github.com/mikemaccana/python-docx Is about as good as it gets.
Need Quick & Dirty DOCX Viewing - PyGTK
Need: A module containing methods for rendering docx files with formatting. Requirements: PyGTK compatibility is not the python-docx module
[ "https://github.com/mikemaccana/python-docx\nIs about as good as it gets.\n" ]
[ 2 ]
[]
[]
[ "gtk", "ms_word", "pygtk", "python" ]
stackoverflow_0005407776_gtk_ms_word_pygtk_python.txt
Q: Google app engine static file handlers example The static_dir examples are pretty clear So for example, I want requests to http://mysite.appengine.com/main.htm to go to the C:\<appenginesiteroot>\html\main.htm file (on the hard disk), and this can be achieved with # app.yaml - url: / static_dir: html But when i...
Google app engine static file handlers example
The static_dir examples are pretty clear So for example, I want requests to http://mysite.appengine.com/main.htm to go to the C:\<appenginesiteroot>\html\main.htm file (on the hard disk), and this can be achieved with # app.yaml - url: / static_dir: html But when it comes to using static file handlers its not clear....
[ "script is for scripts, you are trying to map to a static file. Have you looked at the Static File Pattern Handlers section of the doc?\nHave you tried:\n- url: /\n static_files: main.html\n upload: main.html\n\n" ]
[ 12 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005408255_google_app_engine_python.txt
Q: How to download/upload all entities in appengine? Need to download my all entities from appengine(appid.appspot.com) and upload to devserver(localhost:8080) for testing. Referred lot of threads in stackoverflow and google community. But not able to load/download all entities.Give me some link or idea,any one succe...
How to download/upload all entities in appengine?
Need to download my all entities from appengine(appid.appspot.com) and upload to devserver(localhost:8080) for testing. Referred lot of threads in stackoverflow and google community. But not able to load/download all entities.Give me some link or idea,any one successfully loaded all entity to devserver in version 1.4.2...
[ "This is a script that I used to use for this purpose (I switched to using an Ant script). I haven't maintained it for a while, but it appears to still work:\nhttps://gist.github.com/882011\nIf you have experience with Ant, this is what I switched to:\nhttps://bitbucket.org/darktable/gae-python-ant-farm/src/fb0512f...
[ 3, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005396611_google_app_engine_python.txt
Q: Retrieving YAML parameters during runtime in App Engine (Python) Is it possible to programmatically retrieve any of the YAML parameters during run-time? Are they stored in the environment somewhere? Good example would be to automatically find the application version and to add it as a comment in the landing HTML p...
Retrieving YAML parameters during runtime in App Engine (Python)
Is it possible to programmatically retrieve any of the YAML parameters during run-time? Are they stored in the environment somewhere? Good example would be to automatically find the application version and to add it as a comment in the landing HTML page.
[ "No, but some of the data is available from os.environ - for example, os.environ['APPLICATION_ID'], and os.environ['CURRENT_VERSION_ID'].\n", "No (except for what environment settings CGI and WSGI standards mandate). If you need the full contents of app.yaml to use in your code, then I'd recommend keeping a copy...
[ 5, 4, 2 ]
[]
[]
[ "google_app_engine", "python", "runtime", "yaml" ]
stackoverflow_0003848671_google_app_engine_python_runtime_yaml.txt
Q: dictionary key error python I get the error "Key Error: 'tempMax'". Can anyone tell what the problem is with the following code: def catagorise(self, day, cat, f): self.features.setdefault(cat, {f:{'high':0,'mid':0,'low':0}}) if f == 'tempMean': if day.tempMean > 15.0: self.features[ca...
dictionary key error python
I get the error "Key Error: 'tempMax'". Can anyone tell what the problem is with the following code: def catagorise(self, day, cat, f): self.features.setdefault(cat, {f:{'high':0,'mid':0,'low':0}}) if f == 'tempMean': if day.tempMean > 15.0: self.features[cat][f]['high'] += 1 elif d...
[ "The issue is in the setdefault call.\nf is set to tempMax but tempMax was never initialized.\nIn this case it needs to be initialized as a dictionary because you have 'high' as a key\nself.features[cat][f]['high']\n\n\nself.features[cat]['tempMax'] = {}\n\nIf you come from a php background then this is a common mi...
[ 4, 1, 0 ]
[]
[]
[ "dictionary", "key", "python" ]
stackoverflow_0005408726_dictionary_key_python.txt
Q: Python Raytracing I'm building a simple Python raytracer with pure Python (just for the heck of it), but I've hit a roadblock. The setup of my scene is currently this: Camera located at 0, -10, 0 pointing along the y-axis. Sphere with radius 1 located at 0, 0, 0. Imaging plane-thing is a distance of 1 away from t...
Python Raytracing
I'm building a simple Python raytracer with pure Python (just for the heck of it), but I've hit a roadblock. The setup of my scene is currently this: Camera located at 0, -10, 0 pointing along the y-axis. Sphere with radius 1 located at 0, 0, 0. Imaging plane-thing is a distance of 1 away from the camera and has a wid...
[ "Are you normalising the ray's direction vector?\n" ]
[ 8 ]
[]
[]
[ "python", "raytracing", "vector" ]
stackoverflow_0005408669_python_raytracing_vector.txt
Q: How can I listen for a button press in Tkinter How can I listen for a button press in Tkinter? I need to listen for a button and not run a function but, I want to run a function that listens for a button. Update Here is the code: #!/usr/bin/env python import time import thread from Tkinter import * class at(Fram...
How can I listen for a button press in Tkinter
How can I listen for a button press in Tkinter? I need to listen for a button and not run a function but, I want to run a function that listens for a button. Update Here is the code: #!/usr/bin/env python import time import thread from Tkinter import * class at(Frame): def __init__(self, *args, **params): ## ...
[ "What you are trying to accomplish is unclear, but it sounds like you misunderstand how GUI programming works in general and are just asking the wrong question. Generally speaking, If you think you need to poll for button presses rather than take advantage of the event loop you are doing it wrong.\nSo, the best ans...
[ 1, 0 ]
[]
[]
[ "button", "listener", "python", "tkinter" ]
stackoverflow_0005392871_button_listener_python_tkinter.txt
Q: Matplotlib Unicode axis labels using the Cairo renderer I'm trying to generate a plot using Matplotlib with a non-Latin character (a "μ") in an axis label, like this: matplotlib.pyplot.xlabel(u'Sarcomere Length (μm)') I'm using the Cairo renderer on Linux and I'm getting a "box" instead of "μ": It works with acc...
Matplotlib Unicode axis labels using the Cairo renderer
I'm trying to generate a plot using Matplotlib with a non-Latin character (a "μ") in an axis label, like this: matplotlib.pyplot.xlabel(u'Sarcomere Length (μm)') I'm using the Cairo renderer on Linux and I'm getting a "box" instead of "μ": It works with accented Latin characters (like "é"). Any ideas?
[ "It's a font problem. Whatever font you have set as matplotlib's default doesn't have that particular character. There are a number of ways to potentially fix this, but it's going to be fairly system dependent. (It may be as simple as ensuring that you have the appropriate font package installed.) \nYou can set t...
[ 7 ]
[]
[]
[ "label", "matplotlib", "python", "unicode" ]
stackoverflow_0005408862_label_matplotlib_python_unicode.txt
Q: How to fix pdb in Aquamacs on Mac OS X? I'm developing a django app using aquamacs as my ide. Pdb isn't working since upgrading to emacs 23.2.1 using python 2.6.1. When I invoke pdb like this: M-x pdb Run pdb (like this): pdb ./manage.py runserver The gud-manage.py frame appears with this message (and nothing mor...
How to fix pdb in Aquamacs on Mac OS X?
I'm developing a django app using aquamacs as my ide. Pdb isn't working since upgrading to emacs 23.2.1 using python 2.6.1. When I invoke pdb like this: M-x pdb Run pdb (like this): pdb ./manage.py runserver The gud-manage.py frame appears with this message (and nothing more) - Current directory is /path/to/my/source/...
[ "Not sure if that is the case for you, but just to mention it: PDB hangs for me in Emacs when the source code path contains a space - when I move the python file to a directory without a space in the name, it works (on Emacs 23.1.1).\n", "Same issue (Current directory is ...) to me with emacs 23.2 (9). As you men...
[ 2, 2, 0 ]
[]
[]
[ "debugging", "emacs", "python" ]
stackoverflow_0003358124_debugging_emacs_python.txt
Q: Django: Faking a field in the admin interface? I have a model, Foo. It has several database properties, and several properties that are calculated based on a combination of factors. I would like to present these calculated properties to the user as if they were database properties. (The backing factors would be ch...
Django: Faking a field in the admin interface?
I have a model, Foo. It has several database properties, and several properties that are calculated based on a combination of factors. I would like to present these calculated properties to the user as if they were database properties. (The backing factors would be changed to reflect user input.) Is there a way to do t...
[ "I would suggest you subclass a modelform for Foo (FooAdminForm) to add your own fields not backed by the database. Your custom validation can reside in the clean_* methods of ModelForm.\nInside the save_model method of FooAdmin you get the request, an instance of Foo and the form data, so you could do all processi...
[ 33, 6, 1, 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0004891506_django_django_admin_python.txt
Q: Python : Recursively flatten a list I have a list l = [2, 9, [1, 13], 8, 6]. How can I flatten it recursively to get l = [2, 9, 1, 13, 8, 6]? A: If you want to flatten arbitrarily nested iterables, you could try this function: def flatten(x): try: it = iter(x) except TypeError: yield x ...
Python : Recursively flatten a list
I have a list l = [2, 9, [1, 13], 8, 6]. How can I flatten it recursively to get l = [2, 9, 1, 13, 8, 6]?
[ "If you want to flatten arbitrarily nested iterables, you could try this function:\ndef flatten(x):\n try:\n it = iter(x)\n except TypeError:\n yield x\n else:\n for i in it:\n for j in flatten(i):\n yield j\n\nExample:\na = [2, 9, [1, 13], 8, 6]\nlist(flatten...
[ 6 ]
[]
[]
[ "list", "python", "recursion" ]
stackoverflow_0005409224_list_python_recursion.txt
Q: Counting number of iterations before match is found not working right I have the below code: def numbers(): '''returns 2 random numbers between 1 and 10 that are not the same ''' b = random.randrange(1, 11, 1) res = [] count = 0 while len(res) < 2: if b not in res: res.a...
Counting number of iterations before match is found not working right
I have the below code: def numbers(): '''returns 2 random numbers between 1 and 10 that are not the same ''' b = random.randrange(1, 11, 1) res = [] count = 0 while len(res) < 2: if b not in res: res.append(b) b = random.randrange(1, 11, 1) return res def ma...
[ "Here's one possible problem: the first time through your while len(res) < 2: loop, your new value of b could be the same as the old value of b. Then this code will loop forever:\nwhile len(res) < 2:\n if b not in res:\n res.append(b)\n b = random.randrange(1, 11, 1)\n\nbecause len(res) will always...
[ 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005409357_list_python.txt
Q: web.py url handling: multiple subapplication redirection When using web.py framework. you can redirect an url to a subapplication. e.g (code.py): import web import subapp1 urls = ( "/sub1", subapp1.app, "/(.*)", "index" ) .... this is really straight forward. However, when writing subapp1.py which has it...
web.py url handling: multiple subapplication redirection
When using web.py framework. you can redirect an url to a subapplication. e.g (code.py): import web import subapp1 urls = ( "/sub1", subapp1.app, "/(.*)", "index" ) .... this is really straight forward. However, when writing subapp1.py which has its own url handlers, if i want to re-route some url, say '/sub2...
[ "After some trial-error, found that there is nothing wrong with web.py and rerouting from subapp to another subapp. It is all working perfectly.\nWhat is wrong is my method. Do not try to create a subapp in package's init.py file. At least when i moved subapp to its own module, it all worked well.\n" ]
[ 1 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0005406865_python_web.py.txt
Q: Installing the newest scipy (0.9) in Ubuntu? I tried following the tutorial but after hours of building the ATLAS + LAPACK I got an error in the make install. I tried to download the following 4 libraries and install it still but no dice. Currently I have installed numpy 1.3 and scipy 0.7.2 from the ubuntu reposit...
Installing the newest scipy (0.9) in Ubuntu?
I tried following the tutorial but after hours of building the ATLAS + LAPACK I got an error in the make install. I tried to download the following 4 libraries and install it still but no dice. Currently I have installed numpy 1.3 and scipy 0.7.2 from the ubuntu repositories. I need a feature from scipy 0.9 though. Any...
[ "ActivePython includes a package manager that allows you to install scipy 0.9 (among numpy, matplotlib, etc.) from PyPM.\npypm install numpy\n\nThese packages are built with ATLAS + LAPACK (Linux), veclib (OSX) or Intel MKL / ifortran (Windows).\n", "To install Scipy 0.9, you need to have a newer Numpy installed ...
[ 3, 1, 0, 0 ]
[]
[]
[ "numpy", "python", "scipy", "ubuntu" ]
stackoverflow_0005061340_numpy_python_scipy_ubuntu.txt
Q: Python smtplib module leaks memory I have written a daemon of sorts to monitor files in a directory and send out an email whenever there is a change in any of the files. I used bb-freeze to compile it to a Windows .exe. I noticed after letting it run for a couple of days that it was taking more and more space in m...
Python smtplib module leaks memory
I have written a daemon of sorts to monitor files in a directory and send out an email whenever there is a change in any of the files. I used bb-freeze to compile it to a Windows .exe. I noticed after letting it run for a couple of days that it was taking more and more space in memory. I used Heapy to monitor the memor...
[ "I would bet that you have a reference cycle.\nEdit: I altered your code slightly to:\nimport time\nimport gc\nimport smtplib\nimport mimetypes\nfrom email.MIMEText import MIMEText\n\ndef sendMail(subject, text):\n gmailUser = 'myemail@gmail.com'\n gmailPass = 'mypassword'\n recipient = gmailUser\n\n msg = ...
[ 1, 0, 0 ]
[]
[]
[ "python", "smtplib" ]
stackoverflow_0005409308_python_smtplib.txt
Q: Tick method in a PoliceOfficer class My question deals with creating a tick procedure the original tick procedure where it makes a class called PoliceOfficer arrest everyone who is naked around him. def tick(self): # next time step for all objects that tick for t in self.__things: obj...
Tick method in a PoliceOfficer class
My question deals with creating a tick procedure the original tick procedure where it makes a class called PoliceOfficer arrest everyone who is naked around him. def tick(self): # next time step for all objects that tick for t in self.__things: obj = self.get_thing(t) if has_...
[ "Uhm,... you want to test is an object is of a certain class? Python has a built-in function for that: isinstance(). Quick example:\n>>> isinstance(1, int)\nTrue\n>>> isinstance(\"Hello World!\", int)\nFalse\n>>> isinstance(\"Hello World!\", str)\nTrue\n\nCheck the documentation for more information.\nhttp://docs.p...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005409879_python.txt
Q: How can I display the date/time in multiple languages? I would like to display the date and time (or either date or time, separately) in multiple languages. Specifically English and Spanish, but perhaps in other languages in the future. I've considered pythons time.strftime function in combination with locale.set...
How can I display the date/time in multiple languages?
I would like to display the date and time (or either date or time, separately) in multiple languages. Specifically English and Spanish, but perhaps in other languages in the future. I've considered pythons time.strftime function in combination with locale.setlocal. I ruled this out after reading in the docs (http://do...
[ "I would maintain the translations as standard PO file using the gettext mechanism.\nFor each language you keep the translations in a dedicated file. You use the month and day names as msgid and keep the specific translations as msgstr.\nhttp://docs.python.org/library/gettext.html\n" ]
[ 1 ]
[]
[]
[ "datetime", "locale", "python", "python_babel" ]
stackoverflow_0005410397_datetime_locale_python_python_babel.txt
Q: How to read complete IP frames from TCP socket in Python? I need to read a complete (raw) IP frame from a TCP stream socket using Python. Essentially I want an unmodified frame just as if it came off the physical line, including all the header information. I have been looking into raw sockets in Python but I have ...
How to read complete IP frames from TCP socket in Python?
I need to read a complete (raw) IP frame from a TCP stream socket using Python. Essentially I want an unmodified frame just as if it came off the physical line, including all the header information. I have been looking into raw sockets in Python but I have ran into some issues. I don't need to form my own packets, I si...
[ "If you don't mind using Scapy, which is not part of the standard library, and super speed isn't a requirement, you can use its sniff function. It takes a callback. Something like:\npkts_rxd = []\ndef process_and_send(pkt):\n pkts_rxd.append(pkt)\n sendp(pkt, 'eth1')\nsniff(prn=process_and_send, iface='eth0',...
[ 3, 0, 0 ]
[]
[]
[ "linux", "python", "raw_sockets", "sockets" ]
stackoverflow_0005410470_linux_python_raw_sockets_sockets.txt
Q: simple python list problem According to the docs: list.append(x): Add an item to the end of the list So, if I do: list = [] list.append("banana") print list[0] --> which is suppose to print the FIRST item of the list > banana So far so good, however if now I append another item: list.append("apple") print list[0...
simple python list problem
According to the docs: list.append(x): Add an item to the end of the list So, if I do: list = [] list.append("banana") print list[0] --> which is suppose to print the FIRST item of the list > banana So far so good, however if now I append another item: list.append("apple") print list[0] apple Wasn't it suppose to ...
[ ">>> l = []\n>>> l.append('banana')\n>>> print l[0]\nbanana\n>>> l.append('apple')\n>>> print l[0]\nbanana\n>>> print l\n['banana', 'apple']\n\nWorks fine for me, are you sure you aren't clearing the list anytime?\n", "Works for me. You probably ought to pick a name other than list, since there's a built-in funct...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005410725_python.txt
Q: accessing specific elements from python dictionary Not sure if people refer to slightly older questions but Accessing elements of python dictionary Consider a dict like dict = { 'Apple': {'American':'16', 'Mexican':10, 'Chinese':5}, 'Grapes':{'Arabian':'25','Indian':'20'} } How do I access...
accessing specific elements from python dictionary
Not sure if people refer to slightly older questions but Accessing elements of python dictionary Consider a dict like dict = { 'Apple': {'American':'16', 'Mexican':10, 'Chinese':5}, 'Grapes':{'Arabian':'25','Indian':'20'} } How do I access for instance a particular element of this dictionary ? ...
[ "for i in dict.keys():\n print \"Group\", i\n for j in dict[i].keys():\n print \"Item\", j, \"Value\", dict[i][j]\n\n" ]
[ 3 ]
[]
[]
[ "dictionary", "python", "string" ]
stackoverflow_0005410741_dictionary_python_string.txt
Q: Faster bitwise modulus for Lucas-Lehmer primality test The Lucas-Lehmer primality test tests prime numbers to determine whether they are also Mersenne primes. One of the bottlenecks is the modulus operation in the calculation of (s**2 − 2) % (2**p - 1). Using bitwise operations can speed things up considerably (se...
Faster bitwise modulus for Lucas-Lehmer primality test
The Lucas-Lehmer primality test tests prime numbers to determine whether they are also Mersenne primes. One of the bottlenecks is the modulus operation in the calculation of (s**2 − 2) % (2**p - 1). Using bitwise operations can speed things up considerably (see the L-L link), the best I have so far being: def mod(n,p):...
[ "The best improvement I could find was removing Mp = (1<<p) - 1 from the modulus function altogether, and pre-calculating it in the L-L function before starting the iterations of the L-L test. Using while n > Mp: instead of while n.bit_length() > p: also saved some time.\n", "In the case where n is much longer th...
[ 1, 0 ]
[]
[]
[ "bit_manipulation", "modulo", "optimization", "primes", "python" ]
stackoverflow_0005393420_bit_manipulation_modulo_optimization_primes_python.txt
Q: How to build a IMS open source corpus workbench and NLTK readable corpus? Currently i've a bunch of .txtfiles. within each .txt files, each sentence is separated by newline. how do i change it to the IMS CWB format so that it's readable by CWB? and also to nltk format. Can someone lead me to a howto page to do tha...
How to build a IMS open source corpus workbench and NLTK readable corpus?
Currently i've a bunch of .txtfiles. within each .txt files, each sentence is separated by newline. how do i change it to the IMS CWB format so that it's readable by CWB? and also to nltk format. Can someone lead me to a howto page to do that? or is there a guide page to do that, i've tried reading through the manual b...
[ "It's easy to produce cwb's \"verticalized\" format from an NLTK-readable corpus:\nfrom nltk.corpus import brown\n\nout = open('corpus.vrt','w')\nfor sentence in nltk.brown.sents():\n print >>out,'<s>'\n for word in sentence:\n print >>out,word\n print >>out,'</s>'\nout.close()\n\nFrom there, y...
[ 2 ]
[]
[]
[ "corpus", "nltk", "python" ]
stackoverflow_0005038283_corpus_nltk_python.txt
Q: Sheet music library I'm a python hacker looking to build a sheet music app. I'm comfortable with reading/understanding sheet music (played piano for many years). Here are my complete newbie questions.. Is there a standard for representing notes digitally? I don't want to reinvent any wheels. Given a sequence of...
Sheet music library
I'm a python hacker looking to build a sheet music app. I'm comfortable with reading/understanding sheet music (played piano for many years). Here are my complete newbie questions.. Is there a standard for representing notes digitally? I don't want to reinvent any wheels. Given a sequence of notes and durations, is ...
[ "Take a look at lilypond. It uses LaTeX to typeset sheet music. Its input format is simple text, and can be generated pretty easily with Python or whatever.\nAbjad is a \"Python API for Formalized Score Control\" and a wrapper around lilypond, but I haven't used it and so can't vouch for it.\n", "As far as I know...
[ 30, 6, 2, 1 ]
[]
[]
[ "music_notation", "python" ]
stackoverflow_0005411185_music_notation_python.txt
Q: How to prevent xml.ElementTree fromstring from dropping commentnode I have tho following code fragment: from xml.etree.ElementTree import fromstring,tostring mathml = fromstring(input) for elem in mathml.getiterator(): elem.tag = 'm:' + elem.tag return tostring(mathml) When i input the fol...
How to prevent xml.ElementTree fromstring from dropping commentnode
I have tho following code fragment: from xml.etree.ElementTree import fromstring,tostring mathml = fromstring(input) for elem in mathml.getiterator(): elem.tag = 'm:' + elem.tag return tostring(mathml) When i input the following input: <math> <a> 1 2 3 </a> <b /> <foo>Uitleg</foo> <!-- <bar>...
[ "You cannot with xml.etree, because its parser ignores comments (which is acceptable behaviour for an xml parser by the way). But you can if you use the (compatible) lxml library, which allows you to configure parser options.\nfrom lxml import etree\n\nparser = etree.XMLParser(remove_comments=False)\ntree = etree.p...
[ 17 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0005409161_elementtree_python_xml.txt
Q: Extract class from python I'm writing a game in c++ using boost.python library as script system. I have an abstract class Object. Now I create new class, inherit it from Objects and write somewhere Object *obj = new SomeCoolObject(); I also have a map of objects: map<string, Object*> objects. So after making objec...
Extract class from python
I'm writing a game in c++ using boost.python library as script system. I have an abstract class Object. Now I create new class, inherit it from Objects and write somewhere Object *obj = new SomeCoolObject(); I also have a map of objects: map<string, Object*> objects. So after making object I do: objects.insert("name", ...
[ "If you've already loaded the module (e.g., using boost::python::import(\"module_name\")), you should be able to reference any classes in it via the attr() member function. Generally I write a wrapper function around it, since it can raise an exception if the class (or any other attribute, for that matter) doesn't ...
[ 1 ]
[]
[]
[ "boost", "c++", "class", "extract", "python" ]
stackoverflow_0005395086_boost_c++_class_extract_python.txt
Q: Cannot convert 'vector' to Python object I am trying to wrap a c++ function with signature vector < unsigned long > Optimized_Eratosthenes_sieve(unsigned long max) using Cython. I have a file sieve.h containing the function, a static library sieve.a and my setup.py is as follows: from distutils.core import setu...
Cannot convert 'vector' to Python object
I am trying to wrap a c++ function with signature vector < unsigned long > Optimized_Eratosthenes_sieve(unsigned long max) using Cython. I have a file sieve.h containing the function, a static library sieve.a and my setup.py is as follows: from distutils.core import setup from distutils.extension import Extension fr...
[ "If you only need to call you function for C++, declare it with cdef instead of def.\nOn the other hand, if you need to call it from Python, your function has to return a Python object.\nIn this case, you'll probably make it return a Python list of integers.\n" ]
[ 2 ]
[]
[]
[ "c++", "cython", "python" ]
stackoverflow_0005327894_c++_cython_python.txt