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: Unable to access file as a database in django In my django application structure is as follows: __init__.py __init__.pyc models.py tests.py usage.rrd views.py views.pyc I am trying to access the usage.rrd file in views.py as follows: from django.http import HttpResponse import rrdtool def hello(request...
Unable to access file as a database in django
In my django application structure is as follows: __init__.py __init__.pyc models.py tests.py usage.rrd views.py views.pyc I am trying to access the usage.rrd file in views.py as follows: from django.http import HttpResponse import rrdtool def hello(request): info = rrdtool.info('usage.rrd') ...
[ "The application starts from the root directory of your project. So you you need to fix your path, ('app-name/usage.rrd') .\n", "As mentioned in thebwt's answer it's a path issue. The working directory for your django environment will not be that of you app, hence the failure to locate your file.\nYou will have t...
[ 1, 0 ]
[]
[]
[ "django", "python", "rrd", "rrdtool" ]
stackoverflow_0005169260_django_python_rrd_rrdtool.txt
Q: GWT or Python or Ruby for Web Development I want to embark on learning a totally new language for web back-end development and I've narrowed down my choice between these three: GWT Ruby Python Do you know or recommend of any sites that walks you through building a simple site using these technologies that could...
GWT or Python or Ruby for Web Development
I want to embark on learning a totally new language for web back-end development and I've narrowed down my choice between these three: GWT Ruby Python Do you know or recommend of any sites that walks you through building a simple site using these technologies that could be easily deployed and tested? By the way, I a...
[ "if you want to have fun and learn rails http://railsforzombies.org/. \nif you dont appreciate the humor, http://ruby.railstutorial.org/\n", "GWT is really a frontend development technology. It includes components that make it play nice with the backend, but it is primarily a UI framework.\n", "If you want to b...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "gwt", "python", "ruby" ]
stackoverflow_0005156496_gwt_python_ruby.txt
Q: Python: The opposite of `datetime.date.isocalendar()` The datetime module provides a method date.isocalendar that, given a date, returns it in the format ([year], [week], [weekday]). How do I go backwards? Given a ([year], [week], [weekday]) tuple, how can I get a date object? A: EDIT Found question with solutio...
Python: The opposite of `datetime.date.isocalendar()`
The datetime module provides a method date.isocalendar that, given a date, returns it in the format ([year], [week], [weekday]). How do I go backwards? Given a ([year], [week], [weekday]) tuple, how can I get a date object?
[ "EDIT Found question with solution:\nWhat's the best way to find the inverse of datetime.isocalendar()?\nMy solution had mistakes. On googling saw previous question which upon testing below worked. (See top answered question in above link for definition of iso_to_gregorian ). (Basically find iso year start date ...
[ 4 ]
[]
[]
[ "date", "iso", "python" ]
stackoverflow_0005168984_date_iso_python.txt
Q: After saving memcache data, is it immediately available on GAE? On Google App Engine (python), I need to save data with memcache and quickly read it on another page. But before I start coding to have memcache saved, then on the next page I open up that data with the known key, I'm starting to wonder if the data w...
After saving memcache data, is it immediately available on GAE?
On Google App Engine (python), I need to save data with memcache and quickly read it on another page. But before I start coding to have memcache saved, then on the next page I open up that data with the known key, I'm starting to wonder if the data will always be there on the next page? How long does it take to cache ...
[ "I don't believe there is anything special with the GAE implementation of memcached so cached values will be available immediately after they are set, so yes, it will be available on the next page unless it is expired because the memcached server hit it's memory limit. Google don't appear to limit how much data you...
[ 3, 3, 2 ]
[]
[]
[ "caching", "google_app_engine", "memcached", "python" ]
stackoverflow_0005169001_caching_google_app_engine_memcached_python.txt
Q: how to look-up rdf object knowing subject or other way around? I'm using RDFLIB to build graphs among 3 data-sets (A, B, C) with ntriples. Goal: graphs contain links among those data-set A->B, B->C and C->A, I want to check consistency of those links by making sure that links outgoing from A refer back to the same...
how to look-up rdf object knowing subject or other way around?
I'm using RDFLIB to build graphs among 3 data-sets (A, B, C) with ntriples. Goal: graphs contain links among those data-set A->B, B->C and C->A, I want to check consistency of those links by making sure that links outgoing from A refer back to the same entries in A. Problem: once I iterate over links in the A->B, I wan...
[ "\nis there a way to look up objects by knowing the subject without iterating over all entries?\n\nThe answer is Yes. And you can use to different mechanisms: (a) iterate with a restriction; or (b) issue an SPARQL query.\n\n(a) constrain the graph and iterate \n\nThis solution uses a RDFLib triples function over th...
[ 5 ]
[]
[]
[ "python", "rdf", "rdflib" ]
stackoverflow_0005168729_python_rdf_rdflib.txt
Q: Using tornado.auth.TwitterMixin with a callback URL? I am trying to use tornado.auth.TwitterMixin with a callback url, but I am having problems with it. I am not sure how do i set the callback url from within the Tornado Application. Here's my class for tornado.auth.TwitterMixin : class TAuthBindingHandler(Ba...
Using tornado.auth.TwitterMixin with a callback URL?
I am trying to use tornado.auth.TwitterMixin with a callback url, but I am having problems with it. I am not sure how do i set the callback url from within the Tornado Application. Here's my class for tornado.auth.TwitterMixin : class TAuthBindingHandler(BaseHandler,tornado.auth.TwitterMixin): @tornado.web.as...
[ "Hey, I'm not sure if you still need the answer, but self.authorize_redirect takes a callback_uri. So in your case, I would write self.authorize_redirect('http://localhost:8888/authentication-complete'). It took me a while to figure it out. Good luck!\n" ]
[ 2 ]
[]
[]
[ "python", "tornado", "twitter" ]
stackoverflow_0005063242_python_tornado_twitter.txt
Q: how to pass value into templatetag from template in django I have very basic question,gone through many blogs and django documentation but its bit confusing .could any help with below scenario. Scenario : i have x table in that four columns columns : **id name date data ** 1 ab 20...
how to pass value into templatetag from template in django
I have very basic question,gone through many blogs and django documentation but its bit confusing .could any help with below scenario. Scenario : i have x table in that four columns columns : **id name date data ** 1 ab 2011-02-03 p 2 bc 2011-02-03 A ...
[ "You should create class that will correspond to the table you are trying to output.\nI.e. something along the lines:\nClass MyTable:\n def __init__(self):\n self.dates = [] // where dates[i] might be something like {date: [P, A, ...]}\n // you will have to figure out how and what do you...
[ 0 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0005170448_django_django_models_django_templates_django_views_python.txt
Q: what are the rules for imports in python I have a directory structure : ../POC/mud/ client/ common/ server/ and i am trying to use the following imports : from mud.server import config from mud.common.lib import util but when i try to import config , i get an error: Python ...
what are the rules for imports in python
I have a directory structure : ../POC/mud/ client/ common/ server/ and i am trying to use the following imports : from mud.server import config from mud.common.lib import util but when i try to import config , i get an error: Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GC...
[ "First you have to have __init__.py file in the mud and sub-folders, the file can be empty though. Take a look at the Python tutorial in the packages section: http://docs.python.org/tutorial/modules.html#packages\nIn addtion you need to be in the POC folder for the import statements to work or you set the PYTHONPAT...
[ 5 ]
[]
[]
[ "python", "python_import", "python_module" ]
stackoverflow_0005170792_python_python_import_python_module.txt
Q: Image processing 1 bit images I am trying to understand the basics for image processing an image of a corridor. I have have used PIL to convert find the edges in an image, then I have converted it to a 1 bit image. I know what I want to be able to extract - the longest horizontal and diagonal lines that can be fou...
Image processing 1 bit images
I am trying to understand the basics for image processing an image of a corridor. I have have used PIL to convert find the edges in an image, then I have converted it to a 1 bit image. I know what I want to be able to extract - the longest horizontal and diagonal lines that can be found in the image. Any ideas? from PI...
[ "First don't call them 1 bit images - that normally refers to images (like icons) where each pixel is 1bit and so 8pixels can be packed into a single byte.\nImages with only two levels are normally called 'binary' in image processing.\nNow you only have to learn the science of image processing !\nA good place to st...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005170775_python.txt
Q: AES encryption problem: Python pycrypt OFB = C++ Gladman CFB While trying to get a python application to talk to a C++ application using an encrypt link, we could not get them to talk. Trying various combinations of parameters we accidentally found that if we told python to encrypt in OFB mode it would successful...
AES encryption problem: Python pycrypt OFB = C++ Gladman CFB
While trying to get a python application to talk to a C++ application using an encrypt link, we could not get them to talk. Trying various combinations of parameters we accidentally found that if we told python to encrypt in OFB mode it would successfully decrypt in the C++ in CFB mode. Both the python pycrypt library...
[ "PyCrypto uses 8-bit CFB mode by default. I guess the other end uses block-size CFB mode. The segment size in bits is set by the segment_size keyword argument to AES.new, for block-size CFB mode it should be AES.block_size*8.\nFor the first block OFB mode is identical to block-size CFB mode.\n" ]
[ 3 ]
[]
[]
[ "aes", "c++", "encryption", "python" ]
stackoverflow_0005170442_aes_c++_encryption_python.txt
Q: Removing/Copying multiple files with Python I use os.remove() for deleting a file, and shutil.copyfile() for copying a file. Sometimes I need to remove/copy all the files in a directory, and I use the following code. files = glob.glob(os.path.join(profilerPath + "/*.*")) for f in files: os.remove(f) It works...
Removing/Copying multiple files with Python
I use os.remove() for deleting a file, and shutil.copyfile() for copying a file. Sometimes I need to remove/copy all the files in a directory, and I use the following code. files = glob.glob(os.path.join(profilerPath + "/*.*")) for f in files: os.remove(f) It works fine, but I'd like to ask if you have better cod...
[ "What about shutil.copytree() and shutil.rmtree()? They copy/delete recursivly, i.e. everything below a given path.\nIf you want to copy/delete files only, without traversing into subdirectories, your current solution is fine (though you should check if each file indeed is a file and not a directory -- directory na...
[ 5 ]
[]
[]
[ "file", "python" ]
stackoverflow_0005171048_file_python.txt
Q: Create save filenames from userinput in Python I'm programming an IRC and XMPP bot that needs to convert user provided input to a filename. I have already written a function to do this. Is it sane enough? Here is the code: allowednamechars = string.ascii_letters + string.digits + '_+/$.-' def stripname(name, allo...
Create save filenames from userinput in Python
I'm programming an IRC and XMPP bot that needs to convert user provided input to a filename. I have already written a function to do this. Is it sane enough? Here is the code: allowednamechars = string.ascii_letters + string.digits + '_+/$.-' def stripname(name, allowed=""): """ strip all not allowed chars from na...
[ "You might consider just doing base64.urlsafe_b64encode(name), which will always produce a safe name, unless you really want a human-readable file name. Otherwise, the number of edge cases is pretty long, and if you forget one of them, you've got a security problem.\n", "urllib.quote(name.encode(\"utf8\")) will ...
[ 0, 0 ]
[]
[]
[ "filenames", "irc", "python", "user_input", "xmpp" ]
stackoverflow_0005133194_filenames_irc_python_user_input_xmpp.txt
Q: IIS6 kills python cgi script after printing 401 header? Win2k3 sp2 w/ ii6, python7 configured as a script mapping (detailed later). New to python, using the following code works as expected: import logging as log import time import win32api LOG_FILENAME="C:\\logs\\iistest.log" TIME_STEP=.0001 log.basicConfig(fi...
IIS6 kills python cgi script after printing 401 header?
Win2k3 sp2 w/ ii6, python7 configured as a script mapping (detailed later). New to python, using the following code works as expected: import logging as log import time import win32api LOG_FILENAME="C:\\logs\\iistest.log" TIME_STEP=.0001 log.basicConfig(filename=LOG_FILENAME,filemode="w",level=log.DEBUG) try: ...
[ "Hmmm. I've done some perl CGI work on IIS, but not python, so I won't really be able to help you directly. I yellow-flag, though, about the \"Custom\" tag in your metabase excerpt. The UNCPassword property should not be registered as a Custom tag. I've had entire virtual directories import as Customs before, and t...
[ 0 ]
[]
[]
[ "cgi", "http_status_code_401", "iis", "python" ]
stackoverflow_0004101574_cgi_http_status_code_401_iis_python.txt
Q: Using a Simulation (MyHDL) and wxPython together I am using the package MyHDL to do hardware simulation, but I want to put a GUI around it so that users can interactively change signals and see the other signals update. The problem is, MyHDL uses a simulator as follows Simulator has several generators Each genera...
Using a Simulation (MyHDL) and wxPython together
I am using the package MyHDL to do hardware simulation, but I want to put a GUI around it so that users can interactively change signals and see the other signals update. The problem is, MyHDL uses a simulator as follows Simulator has several generators Each generator can either be listening for signal changes, or cal...
[ "Nevermind, I \"solved\" it using app.ExitLoop()\nI realized I could wrap my own loop around app.MainLoop() and whenever I get an event that the Simulator cares about, the handler calls app.ExitLoop(), giving control back to the simulator and then it starts the main loop for wx again.\nIt's not perfect, it's defini...
[ 3 ]
[]
[]
[ "generator", "multithreading", "python", "simulation", "wxpython" ]
stackoverflow_0005164594_generator_multithreading_python_simulation_wxpython.txt
Q: Is PyObjC pre-installed on OSX SL? I'm going to sell a program that uses that framework in Mac App Store. I want to make sure it will be approved by Apple. A: Yes. $ /usr/bin/python2.6 Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credi...
Is PyObjC pre-installed on OSX SL?
I'm going to sell a program that uses that framework in Mac App Store. I want to make sure it will be approved by Apple.
[ "Yes.\n$ /usr/bin/python2.6\nPython 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) \n[GCC 4.2.1 (Apple Inc. build 5646)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import objc\n>>> objc.__file__\n'/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/pyth...
[ 4 ]
[]
[]
[ "cocoa", "objective_c", "pyobjc", "python" ]
stackoverflow_0005171346_cocoa_objective_c_pyobjc_python.txt
Q: Dump memcache keys from GAE SDK Console? In the "Memcache Viewer", is there any way to dump a list of existing keys? Just for debugging, of course, not for use in any scripts! I ask because it doesn't seem like the GAE SDK is using a "real" memcache server, so I'm guessing it's emulated in Python (for simplicity, ...
Dump memcache keys from GAE SDK Console?
In the "Memcache Viewer", is there any way to dump a list of existing keys? Just for debugging, of course, not for use in any scripts! I ask because it doesn't seem like the GAE SDK is using a "real" memcache server, so I'm guessing it's emulated in Python (for simplicity, as it's just a development server).. This woul...
[ "People ask for this on the memcached list a lot, sometimes with the same type of \"just in case I want to look around to debug something\" sentiment.\nThe best way to handle this is to know how you generate your keys, and just go look stuff up when you want to know what's stored for a given value.\nIf you have too...
[ 8, 4, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "memcached", "python" ]
stackoverflow_0000625314_google_app_engine_memcached_python.txt
Q: method call problem with Python So I'm learning python, and I seem to be having a consistent problem with calling setText() methods on Text objects. The process works fine when I'm in the interactive IDLE GUI, but when I save modules and then try to run them, I get: nonetype object has no attribute setText Do I ...
method call problem with Python
So I'm learning python, and I seem to be having a consistent problem with calling setText() methods on Text objects. The process works fine when I'm in the interactive IDLE GUI, but when I save modules and then try to run them, I get: nonetype object has no attribute setText Do I need to assign some sort of return ty...
[ "Perhaps the draw method is not returning anything. Try changing your code to this:\nmessage1 = Text(Point(50,50), \"Click\")\nmessage1.draw(win)\nmessage1.setText(\"\")\n\n", "I'm not sure how to answer your second question properly..so I'll just do it as an answer here.\nThe reason the first does not work is be...
[ 2, 1 ]
[]
[]
[ "attributes", "methods", "object", "python", "python_idle" ]
stackoverflow_0005171234_attributes_methods_object_python_python_idle.txt
Q: Create Python Web Service I have a module I created to generate Javascript for inputs on the server side. I'd like to expose this as a SOAP web service so other languages can use it as well. I searched the internet but everything I find relates to creating a SOAP consumption client and doesn't cover building the a...
Create Python Web Service
I have a module I created to generate Javascript for inputs on the server side. I'd like to expose this as a SOAP web service so other languages can use it as well. I searched the internet but everything I find relates to creating a SOAP consumption client and doesn't cover building the actual web services. Please advi...
[ "You can try soaplib:\n\nThis is a simple, easily extendible soap library that provides several useful tools for creating, publishing and consuming soap web services in python.\n\nAlso see the documentation.\n" ]
[ 1 ]
[]
[]
[ "python", "soap", "web_services" ]
stackoverflow_0005171513_python_soap_web_services.txt
Q: Tools / best practices for managing application dependencies? What tools or best practices are available for tracking and managing dependencies of the software I'm developing? I'm using Python / Django, and to date all my software requirements are open source. I'm developing a web application that, while modest, ...
Tools / best practices for managing application dependencies?
What tools or best practices are available for tracking and managing dependencies of the software I'm developing? I'm using Python / Django, and to date all my software requirements are open source. I'm developing a web application that, while modest, has a number of dependencies. At a minimum, I'd like to track the ...
[ "Use pip and virtualenv. With virtualenv, you can create a \"virtual environment\" which has all your Python packages installed into a local directory. With pip install -r, you can install all packages listed in a specific requirements file.\nRough example:\nvirtualenv /path/to/env --no-site-packages --unzip-setupt...
[ 18 ]
[]
[]
[ "dependency_management", "python" ]
stackoverflow_0005172029_dependency_management_python.txt
Q: Python Authentication I'm new to python and after struggling with myself a little bit I almost got the code to working. import urllib, urllib2, cookielib username = 'myuser' password = 'mypass' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login = urllib.urlencode({'us...
Python Authentication
I'm new to python and after struggling with myself a little bit I almost got the code to working. import urllib, urllib2, cookielib username = 'myuser' password = 'mypass' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login = urllib.urlencode({'user' : username, 'pass' : pa...
[ "If a browser got that response, it would interpret it as a request to redirect to the URL specified. \nYou will need to do something similar with your script. You need to parse the <META> tag and locate the URL and then do a GET on that URL.\n" ]
[ 3 ]
[]
[]
[ "authentication", "python" ]
stackoverflow_0005172233_authentication_python.txt
Q: django: passing custom tag a parameter I'm trying to pass a variable from the URL (not the query string) to a custom tag, but it looks like I'm getting a ValueError when converting it to an int. It appears at first glance that it's coming in as a string like "project.id" instead of the actual integer value of tha...
django: passing custom tag a parameter
I'm trying to pass a variable from the URL (not the query string) to a custom tag, but it looks like I'm getting a ValueError when converting it to an int. It appears at first glance that it's coming in as a string like "project.id" instead of the actual integer value of that. From what I understand, the tag paramete...
[ "The issue is simply that you haven't resolved the variables to the values they contain. If you put some logging into your method, you'll see that at that point projectId is actually the string \"projectId\", because that's how you referenced it in the template. You need to define this is an instance of template.Va...
[ 1 ]
[]
[]
[ "django", "python", "templatetag" ]
stackoverflow_0005170663_django_python_templatetag.txt
Q: List Manipulation in Python with pop() In short, I need to remove multiple items from a list according to their indexes. However, I can't use pop because it shifts the indexes (without some clumsy compensating system). Is there a way to remove multiple items simultaneously? I have an algorithm that goes through a ...
List Manipulation in Python with pop()
In short, I need to remove multiple items from a list according to their indexes. However, I can't use pop because it shifts the indexes (without some clumsy compensating system). Is there a way to remove multiple items simultaneously? I have an algorithm that goes through a list, and if the conditions are right remove...
[ "Are your lists large? If so, use ifilter from itertools to filter out elements that you don't want lazily (with no up front cost). \nLists not so large? Just use a list comprehension:\n newlist = [x for x in oldlist if x not in ['a', 'c'] ]\n\nThis will create a new copy of the list. This is not generally an issue...
[ 17, 15, 7 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005162991_list_python.txt
Q: Learning the directory's physical disk on Linux with Python First, sorry for my bad English. I'm writing a python script, which compares the files in two different directories. But for performance, I want to know that: "Are the directories on the same physical disk or not?", so I can read them simultaneously for p...
Learning the directory's physical disk on Linux with Python
First, sorry for my bad English. I'm writing a python script, which compares the files in two different directories. But for performance, I want to know that: "Are the directories on the same physical disk or not?", so I can read them simultaneously for performance gain. My current idea is getting "mount" commands outp...
[ "You are looking for the stat function from linux, which is also provided to you by python (see http://docs.python.org/library/os.html#os.stat).\nYou will have to compare the st_dev from the resulting structure and both files will be on the same filesystem if they match.\nUsing this function is as portable as you c...
[ 5, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005171511_linux_python.txt
Q: python equivalent of java Matcher.quoteReplacement() Python has re.escape() if you want to match an arbitrary string literal. In my case, however, I want to use an arbitrary string literal as a replacement string in re.sub(). The re.escape() method produces excessive escaping for that, but an unescaped literal st...
python equivalent of java Matcher.quoteReplacement()
Python has re.escape() if you want to match an arbitrary string literal. In my case, however, I want to use an arbitrary string literal as a replacement string in re.sub(). The re.escape() method produces excessive escaping for that, but an unescaped literal string is not safe to use, because there are still special c...
[ "Wouldn't repl = repl.replace('\\\\','\\\\\\\\') suffice?\n", "Backslash is the only \"special\" character in a replacement, according to the re.sub documentation.\nThere's only one obvious way to do it, plus a non-obvious but documented way:\n>>> repl = r\"foo\\1bar\\2zot\"\n>>> re.sub(r\".*\", repl, \"frobozz\"...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005171629_python_regex.txt
Q: python + sqlite3: using IS NOT in a join query This works the way I expect (c is a cursor) c.execute('''SELECT e1.file, e1.sourceUrl, e1.rev FROM externals1 AS e1 LEFT JOIN externals as e0 ON (e1.file = e0.file) AND (e1.rev <> e0.rev) ''') but I get an error here: c.ex...
python + sqlite3: using IS NOT in a join query
This works the way I expect (c is a cursor) c.execute('''SELECT e1.file, e1.sourceUrl, e1.rev FROM externals1 AS e1 LEFT JOIN externals as e0 ON (e1.file = e0.file) AND (e1.rev <> e0.rev) ''') but I get an error here: c.execute('''SELECT e1.file, e1.sourceUrl, e1.rev ...
[ "!= is ANSI for not equals, what you posted in the second example is invalid SQL for any database I know of. You could try:\n SELECT e1.file, e1.sourceUrl, e1.rev \n FROM externals1 AS e1\nLEFT JOIN externals as e0 ON e0.file = e1.file\n AND e1.rev NOT IN (e0.rev)\n\n", "SELECT e1.f...
[ 2, 2, 0 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0005172356_python_sql_sqlite.txt
Q: Recursion problem in trees + python I would like to mention that this is a homework but am not asking for help related to code. I am having this strange problem . I am trying to implement a btree deletion and am having some recursive return problem def delete ( tree , node , value ) : if node.leaf == True: ...
Recursion problem in trees + python
I would like to mention that this is a homework but am not asking for help related to code. I am having this strange problem . I am trying to implement a btree deletion and am having some recursive return problem def delete ( tree , node , value ) : if node.leaf == True: # delete value from node ...
[ "A quick guess, fix to to:\n ...\n else:\n return delete(tree,node.Child,value) # you missed the return here\n ...\n\nAnd I guess you should recurse into all children of the node, not only one (there might be more than one, right?).\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005172501_python.txt
Q: How come PIL + ndarrays are only working for black and white mode? Let me use a piece of code and a more succinct description instead. import numpy as np from PIL import Image as im real_img = im.open('test.jpg').convert('L') #comment the .convert('L') and it no longer works old_img = np.array(real_img) new_img =...
How come PIL + ndarrays are only working for black and white mode?
Let me use a piece of code and a more succinct description instead. import numpy as np from PIL import Image as im real_img = im.open('test.jpg').convert('L') #comment the .convert('L') and it no longer works old_img = np.array(real_img) new_img = np.zeros(old_img.shape) for i_row in xrange(old_img.shape[0]): for ...
[]
[]
[ "Found this.\n\"Image.fromarray() expects one bit per pixel but actually gets one byte.\"\nSo despite everything apparently being equal, it seems the convert methods are transforming the values onto their binary representations under the hood? I'm not sure tbh. But this fixes the problem:\nimport numpy as np\nfrom ...
[ -1 ]
[ "arrays", "image_processing", "numpy", "python", "python_imaging_library" ]
stackoverflow_0005172412_arrays_image_processing_numpy_python_python_imaging_library.txt
Q: How to directly query a relational/SQL database from a ZOPE product? How do I connect to and query a relational database that was configured with a DA e.g. ZPsycopgDA in a Zope product? I want to send my own SQL queries using bound parameters and receive the results preferrable as a set of Result objects. I don't ...
How to directly query a relational/SQL database from a ZOPE product?
How do I connect to and query a relational database that was configured with a DA e.g. ZPsycopgDA in a Zope product? I want to send my own SQL queries using bound parameters and receive the results preferrable as a set of Result objects. I don't want to use ZSQLMethods as I can't create one for every query beforehand, ...
[ "The Zope Database Adapters (DA) code base is some of the oldest code still in use in Zope, and is thus somewhat archaic. When you call a Zope DA, you get a database connection object (a DB instance) that in turn has a query method:\nconnection = context.idOfZPsycoPGDA()\nconnection.query('SELECT * FROM your_table'...
[ 4, 1 ]
[]
[]
[ "python", "sql", "zope" ]
stackoverflow_0005170593_python_sql_zope.txt
Q: Map with no arguments and class method? It seems pretty simple: # builtins work fine: >>> map (str, [(), (), ()]) ['()', '()', '()'] # but no luck for class methods: >>> class C (object): ... def m(self): ... return 42 ... >>> c = C() >>> map(c.m, [(), (), ()]) Traceback (most recent call last): File "<s...
Map with no arguments and class method?
It seems pretty simple: # builtins work fine: >>> map (str, [(), (), ()]) ['()', '()', '()'] # but no luck for class methods: >>> class C (object): ... def m(self): ... return 42 ... >>> c = C() >>> map(c.m, [(), (), ()]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: m() ta...
[ "You need to add a parameter to your m method, where the argument of the map will be passed.\nclass C (object):\n def m(self, x):\n return 42\n\n>>> c = C()\n>>> map(c.m, [(), (), ()])\n[42, 42, 42]\n\nSee, c.m is a bound method, already like calling m(c), you need a placeholder for the additional paramet...
[ 4, 4, 2, 1, 1, 0 ]
[]
[]
[ "functional_programming", "map", "python" ]
stackoverflow_0005172668_functional_programming_map_python.txt
Q: Why is an instance of webapp.WSGIApplication always defined as a global variable in google app engine code? I'm starting to learn to use google app engine and, in much of the code I've come across, they declare the instance of the webapp.WSGIApplication as a global variable. This doesn't seem to be necessary, as ...
Why is an instance of webapp.WSGIApplication always defined as a global variable in google app engine code?
I'm starting to learn to use google app engine and, in much of the code I've come across, they declare the instance of the webapp.WSGIApplication as a global variable. This doesn't seem to be necessary, as the code works fine when it is locally declared in the main function. I was always advised that global variables ...
[ "Google App Engine offers a neat feature called App caching.\nThe first time the main handler is invoked, the full script is evaluated importing the modules and creating the global elements.\nIf the handler is called after the script has already been evaluated, the app instance simply calls its main() function dire...
[ 7, 1 ]
[]
[]
[ "global_variables", "google_app_engine", "python" ]
stackoverflow_0005172694_global_variables_google_app_engine_python.txt
Q: Formatting CSV Results of Scrapy I am trying to scrape a website and save and format the results to a CSV file. I am able to save the file, however have three questions regarding the output and formatting: All of the results reside in one cell rather than on multiple lines. Is there a command I am forgetting to...
Formatting CSV Results of Scrapy
I am trying to scrape a website and save and format the results to a CSV file. I am able to save the file, however have three questions regarding the output and formatting: All of the results reside in one cell rather than on multiple lines. Is there a command I am forgetting to use when listing items so they appear...
[ "Edit: now that I understand the problem better. Should your parse() function look more like the following? That is, yield-ing one item at a time, instead of returning a list. I suspect the list you are returning is what is being stuffed ill-formatted into the one cell.\ndef parse(self, response):\n hxs = HtmlXP...
[ 2, 0 ]
[]
[]
[ "csv", "formatting", "python", "scrapy" ]
stackoverflow_0005172282_csv_formatting_python_scrapy.txt
Q: WIth PyCharm, why is the PYTHONPATH when running a Django project different from when running the manage.py syncdb task? Shouldn't it be the same by default? If not, is there some way to fix this so that the same PYTHONPATH is used? A: This may not be the ideal solution, but it works, and comes courtesy of my b...
WIth PyCharm, why is the PYTHONPATH when running a Django project different from when running the manage.py syncdb task?
Shouldn't it be the same by default? If not, is there some way to fix this so that the same PYTHONPATH is used?
[ "This may not be the ideal solution, but it works, and comes courtesy of my boss. \nModify pycharm's django_manage.py, inserting the following code at the top, before all existing code. django_manage.py can be found at [PyCharm install directory]/helpers/pycharm/django_manage.py. \nimport site\nimport sys\n\n# A...
[ 1, 0 ]
[]
[]
[ "django", "pycharm", "python", "pythonpath", "syncdb" ]
stackoverflow_0005172214_django_pycharm_python_pythonpath_syncdb.txt
Q: where can i find VARIANT type codes? (vboxapi problem) I'm using vboxapi through the COM, and I noticed a bug... calling IMedium.CreateBaseStorage as they have defined it yields an error, "Invalid VARIANT type: 20". I changed the value of 20 to 19, which was the VARIANT of the other (integer) parameter: de...
where can i find VARIANT type codes? (vboxapi problem)
I'm using vboxapi through the COM, and I noticed a bug... calling IMedium.CreateBaseStorage as they have defined it yields an error, "Invalid VARIANT type: 20". I changed the value of 20 to 19, which was the VARIANT of the other (integer) parameter: def _patch_createBaseStorage(self, aLogicalSize, aVariant): ...
[ "Here is one source (table at the bottom).\n" ]
[ 1 ]
[]
[]
[ "com", "python", "variant", "virtualbox", "windows" ]
stackoverflow_0005172339_com_python_variant_virtualbox_windows.txt
Q: How can I pass the bash variable literally without any interpretation? I have a bash code as follows python "$TM" The problem is that $TM can be whatever character, including ` characters. When $TM has `abc`, the bash tries to run abc as a command before giving it a parameter to python. How can I prevent this? Ho...
How can I pass the bash variable literally without any interpretation?
I have a bash code as follows python "$TM" The problem is that $TM can be whatever character, including ` characters. When $TM has `abc`, the bash tries to run abc as a command before giving it a parameter to python. How can I prevent this? How can I pass the $TM literally without any interpretation? ADDED I need more...
[ "I think you are getting it wrong. Bash didn't \"expand\" TM because it contained backticks (that would be a terrible security breach), the variable already contains the output of the command. You should quote the backticks to prevent the process substitution to occur:\n$ TM=\"`ls`\"\n$ echo $TM\nfile1 file2\n\nvs:...
[ 3, 0 ]
[ "Your question is a bit vague but have you tried to see if quoting $TM to prevent word splitting solves your problem:\npython \"$TM\"\n\n", "python \"$TM\"\n\n        \n" ]
[ -2, -2 ]
[ "bash", "parameters", "python" ]
stackoverflow_0005172644_bash_parameters_python.txt
Q: How can I generate a note or chord in python? Can anybody point me to a good library for generating notes and chords in python 2.7? I have looked at the PythonInfoWiki without a lot of luck, PyAudio just crashes and nothing else seems to generate tones. A: I don't know if it will help, but here's some code that ...
How can I generate a note or chord in python?
Can anybody point me to a good library for generating notes and chords in python 2.7? I have looked at the PythonInfoWiki without a lot of luck, PyAudio just crashes and nothing else seems to generate tones.
[ "I don't know if it will help, but here's some code that synthetizes a complex sound based on gives frequencies and amplitudes:\nimport math\nimport wave\nimport struct\n\ndef synthComplex(freq=[440],coef=[1], datasize=10000, fname=\"test.wav\"):\n frate = 44100.00 \n amp=8000.0 \n sine_list=[]\n for x...
[ 8 ]
[]
[]
[ "audio", "python" ]
stackoverflow_0005173795_audio_python.txt
Q: Python monitoring stderr and stdout of a subprocess I trying to start a program (HandBreakCLI) as a subprocess or thread from within python 2.7. I have gotten as far as starting it, but I can't figure out how to monitor it's stderr and stdout. The program outputs it's status (% done) and info about the encode t...
Python monitoring stderr and stdout of a subprocess
I trying to start a program (HandBreakCLI) as a subprocess or thread from within python 2.7. I have gotten as far as starting it, but I can't figure out how to monitor it's stderr and stdout. The program outputs it's status (% done) and info about the encode to stderr and stdout, respectively. I'd like to be able t...
[ "I have accomplished the same with ffmpeg. This is a stripped down version of the relevant portions. bufsize=1 means line buffering and may not be needed.\ndef Run(command):\n proc = subprocess.Popen(command, bufsize=1,\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT,\n universal_newlines=True)\...
[ 14 ]
[]
[]
[ "multithreading", "python", "stderr", "stdout", "subprocess" ]
stackoverflow_0005173945_multithreading_python_stderr_stdout_subprocess.txt
Q: Running Python Code on Xampp on windows platform XAMPP-PYTHON-WINDOWS I have installed Xampp. I'm running the apache web server and mySql service. I want to host my python code on my web server. However, I am having a hard time setting up python with Xampp. I read about modwsgi, downloaded it and pasted it in the ...
Running Python Code on Xampp on windows platform
XAMPP-PYTHON-WINDOWS I have installed Xampp. I'm running the apache web server and mySql service. I want to host my python code on my web server. However, I am having a hard time setting up python with Xampp. I read about modwsgi, downloaded it and pasted it in the modules folder. I have python 3.2 installed on my C dr...
[ "The official releases of mod_wsgi don't support Python 3.2 so you cant use it. To use Python 3.2 you would need to compile mod_wsgi from source code in subversion repository which I would suggest is probably going to be a bit beyond what you are able to do based on problems you are having above. So, use Python 2.6...
[ 4, 0 ]
[]
[]
[ "python", "windows", "xampp" ]
stackoverflow_0005164921_python_windows_xampp.txt
Q: django eggs template Loader error I'm trying to install dajax/dajaxice according to their documentation, which suggests that I uncomment the eggs template loader (third in tuple below below) in my settings.py. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_di...
django eggs template Loader error
I'm trying to install dajax/dajaxice according to their documentation, which suggests that I uncomment the eggs template loader (third in tuple below below) in my settings.py. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template...
[ "Upgrade to mod_wsgi 3.3. Don't use mod_wsgi 2.X. Read:\nhttp://blog.dscpl.com.au/2009/04/wsgi-and-printing-to-standard-output.html\nIn short, Python code somewhere is trying to use sys.stdin which technically means that code cannot be used portably on all WSGI implementations. Older mod_wsgi versions tried to high...
[ 2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0005173726_django_django_templates_python.txt
Q: What is 3 % 4 in Python? What is 3 % 4 in Python? I.e. I don't know what the outcome is if: the remainder is a fraction (whereas the operands are non-fractions) the first operand < the second operand A: The % sign is the modulus operator. A quick example: C:\Users\jon>python Python 2.6.5 (r265:79096, Mar 19 201...
What is 3 % 4 in Python?
What is 3 % 4 in Python? I.e. I don't know what the outcome is if: the remainder is a fraction (whereas the operands are non-fractions) the first operand < the second operand
[ "The % sign is the modulus operator. A quick example:\nC:\\Users\\jon>python\nPython 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> 3%4\n3\n>>> 4%3\n1\n>>> 4.5%3\n1.5\n>>> 4%3.5\n0.5\n\n", "1) the re...
[ 6, 2, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005174257_python.txt
Q: Bulkloader import list of integers How should I configure import_transform and export_transform im my configuration yaml file to be able to export and import multiple integer property? A: I wrote this collection of helpers for bulk loading data: http://code.google.com/p/bulkloader-gdata-connector/source/browse/b...
Bulkloader import list of integers
How should I configure import_transform and export_transform im my configuration yaml file to be able to export and import multiple integer property?
[ "I wrote this collection of helpers for bulk loading data:\nhttp://code.google.com/p/bulkloader-gdata-connector/source/browse/bulk_helper.py\nI think that list_to_json(int) and json_to_list(int) are what you need.\nBe aware that this will choke on entities that have don't have the list defined yet.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "java", "python" ]
stackoverflow_0005171845_google_app_engine_java_python.txt
Q: Python index out of range error, not sure what I'm doing wrong I'm relatively new to python, have done it a bit for my physics university course. At the moment I'm trying to write a program to calculate some stuff to do with vector functions, that's not really important though as I have it all working up until the...
Python index out of range error, not sure what I'm doing wrong
I'm relatively new to python, have done it a bit for my physics university course. At the moment I'm trying to write a program to calculate some stuff to do with vector functions, that's not really important though as I have it all working up until the last section. The program up to this point produces a load of local...
[ "xmin, ymin = xmin_list[0], ymin_list[1] # < error comes in this line \n\nThe error here is the [1]. If the preceding if statement conditions are False, then ymin_list is still the empty list you set it to, and index 1 is past the end.\nAlso, in the second part you don't need to be using range(len()) like that. Tr...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005174343_python.txt
Q: django-sphinx BuildExcerpts I'm trying to use BuildExcerpts in django sphinx. My view looks something like this: q = request.GET.get('q', '') my_model_list = MyModel.search.query(q).set_options(passages=True, passages_opts={ 'before_match':"<font color='red'>", 'af...
django-sphinx BuildExcerpts
I'm trying to use BuildExcerpts in django sphinx. My view looks something like this: q = request.GET.get('q', '') my_model_list = MyModel.search.query(q).set_options(passages=True, passages_opts={ 'before_match':"<font color='red'>", 'after_match':'</font>', ...
[ "For others who are having similar problems, here is what I had to do to fix it.\nGo to your django-sphinx install folder and open up models.py. On line 650, you need to replace these two lines:\ndocs = [getattr(instance, f) for f in fields]\nif isinstance(self._passages_opts, dict):\n\nwith \n docs = [getattr(ins...
[ 1 ]
[]
[]
[ "django", "django_sphinx", "python" ]
stackoverflow_0004329549_django_django_sphinx_python.txt
Q: override Django get_or_create I have a model that I overrode the save method for, so that the save method can be passed in some data and auto-fill-in a field before saving. Here is my model: class AccountModel(models.Model): account = models.ForeignKey(Account) def save(self, request=None, *args, **kwarg...
override Django get_or_create
I have a model that I overrode the save method for, so that the save method can be passed in some data and auto-fill-in a field before saving. Here is my model: class AccountModel(models.Model): account = models.ForeignKey(Account) def save(self, request=None, *args, **kwargs): if request: ...
[ "You could subclass django.db.models.query.QuerySet and override the get_or_create method there to accept your request keyword argument and pass it onto save I guess, but it isn't very pretty.\nclass AccountQuerySet(models.query.QuerySet):\n def get_or_create(...):\n ...\n\nYou could then add a custom man...
[ 19 ]
[]
[]
[ "django", "django_managers", "django_models", "python", "subclass" ]
stackoverflow_0005173343_django_django_managers_django_models_python_subclass.txt
Q: Ajax POST request failing in Django I am making an Ajax POST Request and it does not get recognized in my view. Code in views.py: @csrf_exempt def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): #handle_uploaded_file(r...
Ajax POST request failing in Django
I am making an Ajax POST Request and it does not get recognized in my view. Code in views.py: @csrf_exempt def upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): #handle_uploaded_file(request.FILES['file']) f = request...
[ "Use request.raw_post_data in your view. Somehow like this:\nif request.is_ajax():\n source = request.raw_post_data\n #Save or/and modify your file\nelse:\n #As usual\n\nBy the way, i do not know how to get file by chunks. Maybe someone knows.\n" ]
[ 2 ]
[]
[]
[ "ajax", "django", "file_upload", "python" ]
stackoverflow_0005114313_ajax_django_file_upload_python.txt
Q: Nested Dictionary/Array in C++ Everybody, I am a Python/C# guy and I am trying to learn C++. In Python I used to do things like: myRoutes = {0:[1,2,3], 1:[[1,2],[3,4]], 2:[[1,2,3],[[1,2,3],[1,2,3]],[4]]} Basically when you have arrays of variable length and you don't want to wast a 2D matrix for them, nesting arra...
Nested Dictionary/Array in C++
Everybody, I am a Python/C# guy and I am trying to learn C++. In Python I used to do things like: myRoutes = {0:[1,2,3], 1:[[1,2],[3,4]], 2:[[1,2,3],[[1,2,3],[1,2,3]],[4]]} Basically when you have arrays of variable length and you don't want to wast a 2D matrix for them, nesting arrays into a dictionary to keep track o...
[ "It looks like part of the question is: 'How do I store heterogeneous data in a container?' There are several different approaches:\n1) Use a ready-made class of array types that abstracts away the exact details (i.e., dimensionality). Example: Boost Basic Linear Algebra\n2) Make an explicit list of element types, ...
[ 5, 2 ]
[]
[]
[ "arrays", "c++", "dictionary", "nested", "python" ]
stackoverflow_0005175344_arrays_c++_dictionary_nested_python.txt
Q: Having to evaluate a string to access a class from a module I've loaded one of my modules <module my_modules.mymodule from .../my_modules/mymodule.pyc> with __import__. Now I'm having the module saved in a variable, but I'd like to create an instance of the class mymodule. Thing is - I've gotten the module name pa...
Having to evaluate a string to access a class from a module
I've loaded one of my modules <module my_modules.mymodule from .../my_modules/mymodule.pyc> with __import__. Now I'm having the module saved in a variable, but I'd like to create an instance of the class mymodule. Thing is - I've gotten the module name passed as string into my script. So I've got a variable containing...
[ "Your problem is that __import__ is designed for use by the import internals, not really for direct usage. One symptom of this is that when importing a module from inside a package, the top-level package is returned rather than the module itself.\nThere are two ways to deal with this. The preferred way is to use im...
[ 1 ]
[]
[]
[ "eval", "import", "module", "python" ]
stackoverflow_0005157371_eval_import_module_python.txt
Q: Voice call with physical phones using Python I am wondering whether there exists a solution for placing voice calls (calling actual numbers) in Python. A: How about this? It seems to allow you to make calls using Session Initiation Protocol (SIP). Obviously, you need to have an SIP server running somewhere.
Voice call with physical phones using Python
I am wondering whether there exists a solution for placing voice calls (calling actual numbers) in Python.
[ "How about this? It seems to allow you to make calls using Session Initiation Protocol (SIP). Obviously, you need to have an SIP server running somewhere.\n" ]
[ 0 ]
[]
[]
[ "python", "voip" ]
stackoverflow_0005175749_python_voip.txt
Q: To check installed software using a program We need to create a program ..actually we were asked to create a software licensing compliance tool....How do we check the installed software inside the machine.. Is it through the registry...while searching i saw a post which said we need to look into the "uninstall" su...
To check installed software using a program
We need to create a program ..actually we were asked to create a software licensing compliance tool....How do we check the installed software inside the machine.. Is it through the registry...while searching i saw a post which said we need to look into the "uninstall" subkey of HKLM . Also do we also get information ...
[ "As you already mentioned the list of (properly) installed programs can be found in the registry under the key\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\n\nSee here for example or use google for further information. Have a look at this key using regedit, the structure id quite obv...
[ 1, 0 ]
[]
[]
[ "python", "registry" ]
stackoverflow_0005175683_python_registry.txt
Q: Problem using easy_install on Windows 7, 64 bit. (cannot find python.exe) I have just now installed Python 2.6 on my Windows 7 (64 bit) Lenovo t61p laptop. I have downloaded Sphinx and nose and apparently installed them correctly using python setup.py install (at least no errors were reported during the install...
Problem using easy_install on Windows 7, 64 bit. (cannot find python.exe)
I have just now installed Python 2.6 on my Windows 7 (64 bit) Lenovo t61p laptop. I have downloaded Sphinx and nose and apparently installed them correctly using python setup.py install (at least no errors were reported during the installation). Now I am trying to install pymongo using easy_install but I am not havi...
[ "I don't know anything about these specific packages so I may not be much help. But for what it's worth I have run into the \"can't find python executable\" errors before with 64 bit python. It happened when the package I was trying to install didn't have a 64 bit version and it was looking for 32 bit python. I ...
[ 6, 0, 0 ]
[]
[]
[ "easy_install", "mongodb", "python", "windows_7" ]
stackoverflow_0002321872_easy_install_mongodb_python_windows_7.txt
Q: Using python win32com can't make two separate tables in MS Word 2007 I am trying to create multiple tables in a new Microsoft Word document using Python. I can create the first table okay. But I think I have the COM Range object configured wrong. It is not pointing to the end. The first table is put before "Hel...
Using python win32com can't make two separate tables in MS Word 2007
I am trying to create multiple tables in a new Microsoft Word document using Python. I can create the first table okay. But I think I have the COM Range object configured wrong. It is not pointing to the end. The first table is put before "Hello I am a text!", the second table is put inside the first table's first c...
[ "The problem seems to be in the Range object that represents a part of the document. In my original code the Range object contains the first cell and starts at the first cell, where it will insert. Instead I want to insert at the end of the range. So I got the following code replacement to work. I moved the Col...
[ 2 ]
[]
[]
[ "ms_word", "python", "win32com" ]
stackoverflow_0004882240_ms_word_python_win32com.txt
Q: Rendering JSON objects using a Django template after an Ajax call I've been trying to understand what's the optimal way to do Ajax in Django. By reading stuff here and there I gathered that the common process is: formulate your Ajax call using some JavaScript library (e.g., jQuery), set up a URL pattern in Djang...
Rendering JSON objects using a Django template after an Ajax call
I've been trying to understand what's the optimal way to do Ajax in Django. By reading stuff here and there I gathered that the common process is: formulate your Ajax call using some JavaScript library (e.g., jQuery), set up a URL pattern in Django that catches the call and passes it to a view function in the Python ...
[ "Hey thanks vikingosegundo! \nI like using decorators too :-).\nBut in the meanwhile I've been following the approach suggested by the snippet I was mentioning above. Only thing, use instead the snippet n. 942 cause it's an improved version of the original one. Here's how it works:\nImagine you have a template (e.g...
[ 25, 13, 7, 6, 3, 3, 1, 0 ]
[]
[]
[ "ajax", "django", "json", "python", "templates" ]
stackoverflow_0000882215_ajax_django_json_python_templates.txt
Q: Problem with concurrent reading and writing (distinct processes) using MySQL and Python I have two concurrent processes: 1.) Writer - inserts new rows into a MySQL database on a regular basis (10-20 rows/sec) 2.) Reader - reads from the same table being inserted into I notice that the Reader process only seems to...
Problem with concurrent reading and writing (distinct processes) using MySQL and Python
I have two concurrent processes: 1.) Writer - inserts new rows into a MySQL database on a regular basis (10-20 rows/sec) 2.) Reader - reads from the same table being inserted into I notice that the Reader process only seems to see a snapshot of the database at about the time of its startup. Inserts occuring before thi...
[ "What's the read side look like? \nI bet this is a problem with the isolation level on the read side. Most likely your read connection is getting an implicit transaction and the default InnoDB isolation level is:\nRepeatable Read\nTry issuing:\ncursor.execute(\"SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITT...
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0005175655_mysql_python.txt
Q: Need to send email with attached CSV file in App Engine (Python/Django) I have a requirement to export some data from a table (not all fields + some properties) and send it as an attachment in an email. I was thinking to create a StringIO object with the CSV contents and upload it to the blobstore and attach the f...
Need to send email with attached CSV file in App Engine (Python/Django)
I have a requirement to export some data from a table (not all fields + some properties) and send it as an attachment in an email. I was thinking to create a StringIO object with the CSV contents and upload it to the blobstore and attach the file to the email. But I don't know how to go from StringIO to uploaded file. ...
[ "As documented, the mail.send_mail function takes an argument 'attachments', which should be a list of 2-tuples, being the filename and the contents of the file to attach. You can get the contents from a StringIO by calling .get_value() on it.\nAs to size, outgoing emails are limited to 10MB. If your CSV file is bi...
[ 2 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0005167127_django_google_app_engine_python.txt
Q: Creating a new array having logarithmic values of elements in another array in Python Hey.. I have run into a bit of a problem with my python code.. I have a set of values each for frequency and power-spectrum. I need to plot frequency v/s power-spectrum on Log scale. I was trying to store the logarithmic values o...
Creating a new array having logarithmic values of elements in another array in Python
Hey.. I have run into a bit of a problem with my python code.. I have a set of values each for frequency and power-spectrum. I need to plot frequency v/s power-spectrum on Log scale. I was trying to store the logarithmic values of frequency and power-spectrum in 2 other variables and then plot them.. Any idea how that ...
[ "Assuming you've got a list of values you might use a simple list comprehension:\nfrequencies = [1, 2, 3, 4, 5]\nimport math\nlogOfFrequencies = [ math.log(x) for x in frequencies ]\n\nOr\nlogOfFrequencies = map(math.log, frequencies)\n\nIf you have a numpy array of frequencies because you're using Matplotlib / Pyl...
[ 5, 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005175421_numpy_python.txt
Q: Searching the facebook graph api with google app engine This is my first question here.. :) Well.. I'm wondering if anyone has achieved this in an effecient way. I want to search through friends friends and possibly their friends to see if some of them are present in my datastore. I've thought up several ways to ...
Searching the facebook graph api with google app engine
This is my first question here.. :) Well.. I'm wondering if anyone has achieved this in an effecient way. I want to search through friends friends and possibly their friends to see if some of them are present in my datastore. I've thought up several ways to do this, but they all have weaknesses.. :/ My first plan was ...
[ "I agree with Nick's comment, but I do feel this is particularly hard on GAE. Graph databases are more suited for this problem. \nThe being said, you might be able to get something working on GAE using bloom filters.\nThe bloom filter would narrow down the number of records you have to search. This, along with so...
[ 1 ]
[]
[]
[ "facebook", "google_app_engine", "python" ]
stackoverflow_0005174534_facebook_google_app_engine_python.txt
Q: unittest and metaclass: automatic test_* method generation As I create tests for a framework, I start noticing the following pattern: class SomeTestCase(unittest.TestCase): def test_feat_true(self): _test_feat(self, True) def test_feat_false(self): _test_feat(self, False) def _test_f...
unittest and metaclass: automatic test_* method generation
As I create tests for a framework, I start noticing the following pattern: class SomeTestCase(unittest.TestCase): def test_feat_true(self): _test_feat(self, True) def test_feat_false(self): _test_feat(self, False) def _test_feat(self, arg): pass # test logic goes here So I wan...
[ "Indeed, it is a closure issue:\nChange\nattrs[testable_name] = lambda self: meth(self, arg)\n\nto\nattrs[testable_name] = lambda self,meth=meth,arg=arg: meth(self, arg)\n\nBy using a default value, arg inside the lambda is bound to the default value arg set during each iteration of the loop. Without the default va...
[ 5, 1 ]
[]
[]
[ "metaclass", "python", "unit_testing" ]
stackoverflow_0005175942_metaclass_python_unit_testing.txt
Q: How to set the color of a single cell in a pygtk treeview? I have a PyGtk treeview with a couple of columns. During runtime i add constantly new rows. Each cell contains a string. Normaly, i would use a gtk.CellRenderer for each row, but I want to set the background color of each cell, according to the value insid...
How to set the color of a single cell in a pygtk treeview?
I have a PyGtk treeview with a couple of columns. During runtime i add constantly new rows. Each cell contains a string. Normaly, i would use a gtk.CellRenderer for each row, but I want to set the background color of each cell, according to the value inside the cell. I tried a couple of solutions, but it seems that I h...
[ "You can define background and foreground for your treeview cells in extra fields of the treeview data source. Then setup foreground and background attributes for the treeview columns to get their values from the corresponding data source fields. \nBelow is a small example:\nimport gtk\n\ntest_data = [\n { 'colu...
[ 12 ]
[]
[]
[ "cellrenderer", "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0005171300_cellrenderer_gtk_gtktreeview_pygtk_python.txt
Q: Mathematical Integration of a function in Python I'm trying to integrate this function: However I'm running into an error of: Traceback (most recent call last): File "<ipython console>", line 1, in <module> File "siestats.py", line 349, in NormalDistro P_inner = scipy.integrate(NDfx,-dev,dev) TypeErr...
Mathematical Integration of a function in Python
I'm trying to integrate this function: However I'm running into an error of: Traceback (most recent call last): File "<ipython console>", line 1, in <module> File "siestats.py", line 349, in NormalDistro P_inner = scipy.integrate(NDfx,-dev,dev) TypeError: 'module' object is not callable My code runs this...
[ "The module you are attempting to call is scipy.integrate, you need to call one of the functions within the module. Based on previous comments on chat you are probably wanting to use scipy.integrate.quad().\nAlso, it returns a tuple of (Result,MaximumError), so you shouldn't use P_inner directly in the sum for P, ...
[ 7, 2, 1 ]
[]
[]
[ "function", "python", "scipy" ]
stackoverflow_0005046845_function_python_scipy.txt
Q: PyQt4 - Cannot use QObject's functions in class inherited from QGraphicsItem (which inherits QObject) I wrote python code looking something like this: class Regularblock(QGraphicsItem): def __init__(self): super(QGraphicsItem).__init__() self.startTimer(100) def timerEvent(self, QTimerEvent...
PyQt4 - Cannot use QObject's functions in class inherited from QGraphicsItem (which inherits QObject)
I wrote python code looking something like this: class Regularblock(QGraphicsItem): def __init__(self): super(QGraphicsItem).__init__() self.startTimer(100) def timerEvent(self, QTimerEvent): do_something But when I try to initialize an instance of Regularblock, I get "AttributeError: '...
[ "Short answer: I think QGraphicsItem is not actually a subclass of QObject. Have a look here; it is not listed as one of the QOject's direct subclasses. I'm not 100% sure, but perhaps you should be using QGraphicsObject ?\n" ]
[ 2 ]
[]
[]
[ "inheritance", "pyqt", "pyqt4", "python" ]
stackoverflow_0005176282_inheritance_pyqt_pyqt4_python.txt
Q: Check absolute paths in Python How can I check whether two file paths point to the same file in Python? A: $ touch foo $ ln -s foo bar $ python Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>...
Check absolute paths in Python
How can I check whether two file paths point to the same file in Python?
[ "$ touch foo\n$ ln -s foo bar\n$ python\nPython 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) \n[GCC 4.0.1 (Apple Inc. build 5465)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import os\n>>> help(os.path.samefile)\nHelp on function samefile in module posixpath:\n\nsame...
[ 26, 6, 3, 0, 0 ]
[]
[]
[ "path", "python" ]
stackoverflow_0001207954_path_python.txt
Q: MySQL insert single variable with python Im having problem with single value inserts. Using pyodbc LL= [] .... sqla = 'INSERT INTO d.table VALUES (?,?,?,?,?,?,?)' csr.executemany(sqla, LL) Works, if LL is single column of data as a list...does not work. LL= [] .... sqla = 'INSERT INTO d.table VALUES (?)' csr.ex...
MySQL insert single variable with python
Im having problem with single value inserts. Using pyodbc LL= [] .... sqla = 'INSERT INTO d.table VALUES (?,?,?,?,?,?,?)' csr.executemany(sqla, LL) Works, if LL is single column of data as a list...does not work. LL= [] .... sqla = 'INSERT INTO d.table VALUES (?)' csr.execute(sqla, LL) How do I fix? Then LL= [] ...
[ "sqla = 'INSERT INTO d.table (column_name) VALUES (?)'\n\nThis is right syntax of INSERT QUERY.\n" ]
[ 1 ]
[]
[]
[ "pyodbc", "python", "sql" ]
stackoverflow_0005176633_pyodbc_python_sql.txt
Q: Is there python code to parse a geoPDF file to get the projection and image data? a geoPDF2KML tool? I want to organize lots of geoPDF files so they can easily viewed overlayed onto Google Maps and Google Earth. My 1st step, I think, is to convert the geoPDF to a jpg type image which then needs matching lat,long i...
Is there python code to parse a geoPDF file to get the projection and image data? a geoPDF2KML tool?
I want to organize lots of geoPDF files so they can easily viewed overlayed onto Google Maps and Google Earth. My 1st step, I think, is to convert the geoPDF to a jpg type image which then needs matching lat,long information. Is there python code to parse a geoPDF file to get the projection and image data? A geoPDF2KML...
[ "Steps I used on ubuntu system that has python (python already part of Unbuntu)\n1. download and install poppler\n2. download and install proj4\n3. download and install gdal\npoppler$./configure --enable-xpdf-headers --prefix=/usr/local/include/poppler\" then the usual \"$make\" and \"$make install\"\n\npoppler$mak...
[ 3, 2, 2 ]
[]
[]
[ "geospatial", "gis", "pdf", "python" ]
stackoverflow_0003884795_geospatial_gis_pdf_python.txt
Q: Why does argparse give me a list-in-a-list? I just noticed a behavior in argparse that puzzled me (guess I'd never used it for a dumb list of files before): import argparse parser = argparse.ArgumentParser() parser.add_argument('multi', action='append', nargs='+') print(parser.parse_args()) This gives me the outp...
Why does argparse give me a list-in-a-list?
I just noticed a behavior in argparse that puzzled me (guess I'd never used it for a dumb list of files before): import argparse parser = argparse.ArgumentParser() parser.add_argument('multi', action='append', nargs='+') print(parser.parse_args()) This gives me the output: ~$ ./testargs.py foo bar baz Namespace(multi=...
[ "You are calling\nparser.add_argument('multi', action='append', nargs='+')\n\nAnd it is taking all the arguments and appending as a single item in the multi list.\nIf you want it as individual items, just don't use append\nparser.add_argument('multi', nargs='+')\n\nFrom the docs\n'append' - This stores a list, and ...
[ 36 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0005176846_argparse_python.txt
Q: Python ElementTree XML Parsing I am trying to parse an xml file that I got by exporting a pdf to xml 1.0 using adobe pro. I am using Python and ElementTree to parse with. The pdf contains a table which spans multiple pages and has several different table headers. I want to parse and extract the row and column data...
Python ElementTree XML Parsing
I am trying to parse an xml file that I got by exporting a pdf to xml 1.0 using adobe pro. I am using Python and ElementTree to parse with. The pdf contains a table which spans multiple pages and has several different table headers. I want to parse and extract the row and column data from the table which begins with th...
[ "In cases where I need to keep state, I fall back to a SAX-style XML-parser, here's a sample script that simply pulls the rows between your MECHANICAL and COMPLETED figures.\n#!python\nimport xml.sax\nimport xml.sax.handler\n\nclass Handler(xml.sax.handler.ContentHandler):\n def __init__(self):\n self.l_c...
[ 4, 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0005174328_elementtree_python_xml.txt
Q: Python tell() behaving differently regarding position in the current file In the book - Core Python Programming, there is following example - >>> f = open('/tmp/x', 'w+') >>> f.tell() 0 >>> f.write('test line 1\n') # add 12-char string [0-11] >>> f.tell() 12 >>> f.write('test line 2\n') # add 12-char string [1...
Python tell() behaving differently regarding position in the current file
In the book - Core Python Programming, there is following example - >>> f = open('/tmp/x', 'w+') >>> f.tell() 0 >>> f.write('test line 1\n') # add 12-char string [0-11] >>> f.tell() 12 >>> f.write('test line 2\n') # add 12-char string [12-23] >>> f.tell() # tell us current file location (end)) 24 ...
[ "Your file is opened in text mode. In that mode Python on Windows makes a translation between Windows line-endings and Unix line endings. On Windows a line ending is two characters while on Unix it is one ('\\n'), hence your result is expected.\nIf you open the file in binary mode, you don't get these translations....
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005176959_python.txt
Q: Replace PHP with Python with Apache Basically I'm looking for a way to get rid of my PHP dependence, and I would like to switch to Python. I'm having trouble finding a way to basically make python a drop in replacement. I'm familiar with Django but its just not quick and dirty enough for most small things I have...
Replace PHP with Python with Apache
Basically I'm looking for a way to get rid of my PHP dependence, and I would like to switch to Python. I'm having trouble finding a way to basically make python a drop in replacement. I'm familiar with Django but its just not quick and dirty enough for most small things I have to do. So I'm wondering if there is an ...
[ "The files that mod_wsgi calls are Python files. Additionally, if you set them up in daemon mode, updating the python file will restart the daemon. It's pretty slick.\nAnother thing you could look at if Django is overkill is Werkzeug, which is pretty much just the server interface. Then later you can add databas...
[ 3, 0, 0 ]
[]
[]
[ "apache", "mod_wsgi", "php", "python" ]
stackoverflow_0005176524_apache_mod_wsgi_php_python.txt
Q: How does python extend work? If I have a list: a = [1,2,3,4] and then add 4 elements using extend a.extend(range(5,10)) I get a = [1, 2, 3, 4, 5, 6, 7, 8, 9] How does python do this? does it create a new list and copy the elements across or does it make 'a' bigger? just concerned that using extend will gobble up...
How does python extend work?
If I have a list: a = [1,2,3,4] and then add 4 elements using extend a.extend(range(5,10)) I get a = [1, 2, 3, 4, 5, 6, 7, 8, 9] How does python do this? does it create a new list and copy the elements across or does it make 'a' bigger? just concerned that using extend will gobble up memory. I'am also asking as ther...
[ "Python's documentation on it says:\n\nExtend the list by appending all the\n items in the given list; equivalent to\n a[len(a):] = L.\n\nAs to \"how\" it does it behind the scene, you really needn't concern yourself about it.\n", "L.extend(M) is amortized O(n) where n=len(m), so excessive copying is not usuall...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "memory_management", "python" ]
stackoverflow_0005176668_memory_management_python.txt
Q: Python Pygame Basic Program I have been trying to learn pygame the last day or so, and tried to write a basic program that just has a small image of a leaf falling from the top of the screen. Nothing appears when I run it, and I imagine I'm missing something obvious with how I'm doing this. (I can tell this is a ...
Python Pygame Basic Program
I have been trying to learn pygame the last day or so, and tried to write a basic program that just has a small image of a leaf falling from the top of the screen. Nothing appears when I run it, and I imagine I'm missing something obvious with how I'm doing this. (I can tell this is a very inefficient way of doing thi...
[ "You probably don't want this sequence:\nfor i in leaves:\n i.move()\n screen.blit(i.leafimage, i.leafrect)\n\n\nscreen.fill((255, 255, 255))\n\n\npygame.display.flip()\n\nYou draw the leaves, and then fill the entire screen with white, and then show the screen.\nfill the screen, then draw the leaves, then fl...
[ 7 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0005177011_pygame_python.txt
Q: accumulate numpy array for just one column I have a NumPy array, i want to accumulate the values of one column, say the 2nd column. a = np.array([[1,2],[2,4]]) # some kind of accumulate function that accumulates just one column: np.add.accumulate(a, 2) a should now be [[1,2],[2,6]] Is there a way to do this in Nu...
accumulate numpy array for just one column
I have a NumPy array, i want to accumulate the values of one column, say the 2nd column. a = np.array([[1,2],[2,4]]) # some kind of accumulate function that accumulates just one column: np.add.accumulate(a, 2) a should now be [[1,2],[2,6]] Is there a way to do this in NumPy?
[ "a = np.array([[1,2],[2,4]])\nnp.add.accumulate(a[:,1], out=a[:,1])\n\na is now:\narray([[1, 2],\n [2, 6]])\n\n" ]
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0005176968_numpy_python.txt
Q: Setting up a dict in the constructor (python) Hey I am a python rookie and I am trying to setup a dict in the constructor of a class how ever, whenever I try to access an element, it returns None. Here is my code class GoogleApp: def __init__(self, path): self.name = "Google App" self.description = "Cre...
Setting up a dict in the constructor (python)
Hey I am a python rookie and I am trying to setup a dict in the constructor of a class how ever, whenever I try to access an element, it returns None. Here is my code class GoogleApp: def __init__(self, path): self.name = "Google App" self.description = "Creates an new google app project." self.title = N...
[ "Can you post sample code?\nI ask this because I'm not sure what you are trying to do. <instance>.pre_defined_macros['_TITLE'] worked fine when I tested it.\n>>> class GoogleApp:\n\n def __init__(self, path):\n self.name = \"Google App\"\n self.description = \"Creates an new google app project.\"\n self.t...
[ 1, 0 ]
[]
[]
[ "class", "constructor", "dictionary", "python" ]
stackoverflow_0005177249_class_constructor_dictionary_python.txt
Q: Django model fields validation Where should the validation of model fields go in django? I could name at least two possible choices: in the overloaded .save() method of the model or in the .to_python() method of the models.Field subclass (obviously for that to work you must write custom fields). Possible use cases...
Django model fields validation
Where should the validation of model fields go in django? I could name at least two possible choices: in the overloaded .save() method of the model or in the .to_python() method of the models.Field subclass (obviously for that to work you must write custom fields). Possible use cases: when it is absolutely neccessary ...
[ "Django has a model validation system in place since version 1.2.\nIn comments sebpiq says \"Ok, now there is a place to put model validation ... except that it is run only when using a ModelForm! So the question remains, when it is necessary to ensure that validation is respected at the db-level, what should you d...
[ 75, 7, 3, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001624782_django_django_models_python.txt
Q: python urllib error so I have this code: def crawl(self, url): data = urllib.request.urlopen(url) print(data) but then when I call the function, it returns data = urllib.request.urlopen(url) AttributeError: 'module' object has no attribute 'request' what did I do wrong? I already imported urllib.. u...
python urllib error
so I have this code: def crawl(self, url): data = urllib.request.urlopen(url) print(data) but then when I call the function, it returns data = urllib.request.urlopen(url) AttributeError: 'module' object has no attribute 'request' what did I do wrong? I already imported urllib.. using python 3.1.3
[ "In python3, urllib is a package with three modules request, response, and error for its respective purposes.\nWhenever you had import urllib or import urllib2 in Python2.\nReplace them with\nimport urllib.request\nimport urllib.response\nimport urllib.error\n\nThe classs and methods are same.\nBTW, use 2to3 tool ...
[ 9, 2 ]
[]
[]
[ "python", "python_3.x", "request", "urllib" ]
stackoverflow_0005177219_python_python_3.x_request_urllib.txt
Q: how to merge multiple lists in python I have multiple lists like below [u'a', 11, u'P'] [u'a', 11, u'A'] [u'b', 2, u'P'] [u'c', 1, u'P'] [u'c', 2, u'P'] [u'd', 1, u'P'] [u'e', 3, u'P'] [u'f', 2, u'P'] [u'a', 1, u'P'] [u'a', 2, u'P'] [u'b', 1, u'P'] [u'b', 11, u'P'] how to merge above lists,to loop the list to ad...
how to merge multiple lists in python
I have multiple lists like below [u'a', 11, u'P'] [u'a', 11, u'A'] [u'b', 2, u'P'] [u'c', 1, u'P'] [u'c', 2, u'P'] [u'd', 1, u'P'] [u'e', 3, u'P'] [u'f', 2, u'P'] [u'a', 1, u'P'] [u'a', 2, u'P'] [u'b', 1, u'P'] [u'b', 11, u'P'] how to merge above lists,to loop the list to add up like below [u'a', 11, u'P'] + [u'a', 2...
[ "You could consider using collections.defaultdict and iterating through the list of dicts in the values.\nimport collections\nd = collections.defaultdict(list)\nl = [[u'a', 11, u'P'],[u'a', 11, u'A'],[u'a', 3, u'P'],[u'b', 2, u'P'],[u'c', 1, u'P'],[u'c', 2, u'P'],[u'd', 1, u'P'],[u'e', 3, u'P']]\nfor k1, v, k2 in l...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005177154_python.txt
Q: nose, unittest.TestCase and metaclass: auto-generated test_* methods not discovered This is a follow-up question for unittest and metaclass: automatic test_* method generation: For this (fixed) unittest.TestCase layout: #!/usr/bin/env python import unittest class TestMaker(type): def __new__(cls, name, base...
nose, unittest.TestCase and metaclass: auto-generated test_* methods not discovered
This is a follow-up question for unittest and metaclass: automatic test_* method generation: For this (fixed) unittest.TestCase layout: #!/usr/bin/env python import unittest class TestMaker(type): def __new__(cls, name, bases, attrs): callables = dict([ (meth_name, meth) for (meth_name, meth...
[ "So, after sleuthing through both stdlib's unittest and nose's loader and selector source code, it turns out that nose overrides unittest.TestLoader.getTestCaseNames to use its own selector (with plugin points).\nNow, nose's selector looks for a potential method's method.__name__ to match certain regexes, black and...
[ 18 ]
[]
[]
[ "metaclass", "nose", "python", "unit_testing" ]
stackoverflow_0005176396_metaclass_nose_python_unit_testing.txt
Q: segmentation fault in pi calculation (python) def pi(times): seq = [] counter = 0 for x in range(times): counter += 2 seq.append("((%f**2)/(%f*%f))*"%(float(counter), float(counter-1), float(counter+1))) seq.append("1.0") seq = "".join(seq) seq = eval(seq) return seq*2 ...
segmentation fault in pi calculation (python)
def pi(times): seq = [] counter = 0 for x in range(times): counter += 2 seq.append("((%f**2)/(%f*%f))*"%(float(counter), float(counter-1), float(counter+1))) seq.append("1.0") seq = "".join(seq) seq = eval(seq) return seq*2 Anywhere past 85000 terms I get a segmentation faul...
[ "You appear to have found a bug in eval where it can't handle insanely long expressions:\n>>> eval(\"1.0*\"*10000+\"1.0\")\n1.0\n>>> eval(\"1.0*\"*100000+\"1.0\")\n# segfault here\n\nI use the phrase \"insanely long\" advisedly though. Don't do it that way, calculate the pieces as you go. There is no reason to be u...
[ 5, 2 ]
[]
[]
[ "for_loop", "pi", "python", "segmentation_fault", "series" ]
stackoverflow_0005177432_for_loop_pi_python_segmentation_fault_series.txt
Q: Python String encode method In Python, there is an encode method in unicode strings to encode from unicode to byte string. There is a decode method in string to do the reverse. But I'm confused what the encode method in string for? A: It's useful for non-text codecs. >>> 'Hello, world!'.encode('hex') '48656c6c6f...
Python String encode method
In Python, there is an encode method in unicode strings to encode from unicode to byte string. There is a decode method in string to do the reverse. But I'm confused what the encode method in string for?
[ "It's useful for non-text codecs.\n>>> 'Hello, world!'.encode('hex')\n'48656c6c6f2c20776f726c6421'\n>>> 'Hello, world!'.encode('base64')\n'SGVsbG8sIHdvcmxkIQ==\\n'\n>>> 'Hello, world!'.encode('zlib')\n'x\\x9c\\xf3H\\xcd\\xc9\\xc9\\xd7Q(\\xcf/\\xcaIQ\\x04\\x00 ^\\x04\\x8a'\n\n", "It first decodes to Unicode using ...
[ 10, 5 ]
[ "Why don't you want to read the fine Python documentation yourself?\nhttp://docs.python.org/release/2.5.2/lib/string-methods.html\n\"\"\" encode( [encoding[,errors]]) Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handli...
[ -4 ]
[ "python", "unicode" ]
stackoverflow_0005177502_python_unicode.txt
Q: Adding new line at the end of each line using Python How can I preserve the file structure after substitution? # -*- coding: cp1252 -*- import os import os.path import sys import fileinput path = "C:\\Search_replace" # Insert the path to the directory of interest #os.path.exists(path) #raise SystemExit Abspat...
Adding new line at the end of each line using Python
How can I preserve the file structure after substitution? # -*- coding: cp1252 -*- import os import os.path import sys import fileinput path = "C:\\Search_replace" # Insert the path to the directory of interest #os.path.exists(path) #raise SystemExit Abspath = os.path.abspath(path) print(Abspath) dirList = os.list...
[ "The question is not great in the clarity department, but if you want Python to print stuff to standard out without a newline at the end you can use sys.stdout.write() instead of print().\nIf you want to perform substitution and save it to a file, you can do what Senthil Kumaran suggested.\n", "Instead of print l...
[ 4, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005177557_python.txt
Q: Correct Regexp for japanese sentence tokenizer- python This is the current text that i've but the regex isn't correct to split the sentences correction. please help to correct my regex, thank you. import nltk import os, sys, re, glob from nltk.tokenize import RegexpTokenizer jp_sent_tokenizer = nltk.RegexpTokeniz...
Correct Regexp for japanese sentence tokenizer- python
This is the current text that i've but the regex isn't correct to split the sentences correction. please help to correct my regex, thank you. import nltk import os, sys, re, glob from nltk.tokenize import RegexpTokenizer jp_sent_tokenizer = nltk.RegexpTokenizer(u'[^ 「」!?。]*[!?。]') para = [] para.append (jp_sent_token...
[ "Try this:\nu'[^!?。]*[!?。]'\n\nIt looks like quotes (「」) do belong in sentences, so you want to allow them.\nI should warn that in general (well, in English grammar), it is very difficult (or even impossible) to parse whole current sentences. (consider 1.2, Dr. Fleishman, etc.)\n" ]
[ 6 ]
[]
[]
[ "nltk", "python", "regex", "tokenize" ]
stackoverflow_0005177850_nltk_python_regex_tokenize.txt
Q: Please explain this python "for" statement: methodList = [method for method in dir(object) if callable(getattr(object, method))] I am trying to use introspection to get a list of my objects functions. I have been reading "Dive into Python", and the aforementioned statement: methodList = [method for method in dir...
Please explain this python "for" statement: methodList = [method for method in dir(object) if callable(getattr(object, method))]
I am trying to use introspection to get a list of my objects functions. I have been reading "Dive into Python", and the aforementioned statement: methodList = [method for method in dir(object) if callable(getattr(object, method))] does the trick. The problem is, I have no idea what it is doing. To me it looks like...
[ "Another way to look at this:\nmethodList = []\nfor method in dir(object): # for every attribute in object\n # note that methods are considered attributes\n if callable(getattr(object, method)) # is it callable?\n methodList.append(method)\nreturn methodList\n\nThe construct it...
[ 3, 3, 2, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005177919_list_python.txt
Q: Serial ports on Windows or Ubuntu VBox to talk to Arduino from Python I have an Arduino microcontroller listening on COM3. Using the arduino IDE and the Serial monitor works fine to send and receive data. I would like to send and receive data from Python, but it's not immediately obvious how to do so. (I'd also be...
Serial ports on Windows or Ubuntu VBox to talk to Arduino from Python
I have an Arduino microcontroller listening on COM3. Using the arduino IDE and the Serial monitor works fine to send and receive data. I would like to send and receive data from Python, but it's not immediately obvious how to do so. (I'd also be fine doing it in C# if it was substantially easier.) I found arduino_seria...
[ "pySerial may or may not be built in to Python. Regardless, if it's not, pySerial is the library to download and install.\nAnd since you already know the Arduino is on COM3, just use this:\nimport serial\nser = serial.Serial(\"COM3\", 19200, timeout=1)\nser.write(\"Whatever\")\n\nFor a Linux box, it's relatively ea...
[ 4, 2, 0, 0 ]
[]
[]
[ "arduino", "pyserial", "python", "serial_port" ]
stackoverflow_0005175971_arduino_pyserial_python_serial_port.txt
Q: numpy - 2d array indexing According to docs numpy's default behaviour is to index arrays first by rows then by columns: a = numpy.arange(6).reshape(3,2) [[0 1] [2 3] [4 5]] print a[0][1] # is 1 I want to index the array using the geometrically oriented-convention a[x][y], as in x-axis and y-axis. How can I ch...
numpy - 2d array indexing
According to docs numpy's default behaviour is to index arrays first by rows then by columns: a = numpy.arange(6).reshape(3,2) [[0 1] [2 3] [4 5]] print a[0][1] # is 1 I want to index the array using the geometrically oriented-convention a[x][y], as in x-axis and y-axis. How can I change the indexing order without...
[ "You can write a.T[0,1] to use indices of the transpose of the array, which are the other way around in 2D.\n" ]
[ 8 ]
[]
[]
[ "indexing", "multidimensional_array", "numpy", "python" ]
stackoverflow_0005178009_indexing_multidimensional_array_numpy_python.txt
Q: Python: How to execute a thread in a new terminal window/command prompt? How to execute a thread in a script in a new terminal window/command prompt? So that the results of the thread will be displayed on a separate window while still having control on the main interpreter? The thread is a continuous remote server...
Python: How to execute a thread in a new terminal window/command prompt?
How to execute a thread in a script in a new terminal window/command prompt? So that the results of the thread will be displayed on a separate window while still having control on the main interpreter? The thread is a continuous remote server pinging thread for alive check.
[ "The -S option of xterm can be used to pass a PTY slave file descriptor. Data written to the corresponding PTY master should then appear in the xterm window.\nSo in your thread, you could call os.openpty() to open a new PTY, start an xterm with subprocess.Popen(), passing a suitable -S option, and write all thread'...
[ 0 ]
[]
[]
[ "multithreading", "python", "terminal" ]
stackoverflow_0005177030_multithreading_python_terminal.txt
Q: How to move each figure toward the goal between the poin that I click on graphics and the center of my object in Python Each time, the figure should move 1/16 of its current distance from the goal (the distance gets smaller each time). Thanks!!!!!!!!! for i in range(len(aaa)): midxtoptx = pt.getX() - midpt...
How to move each figure toward the goal between the poin that I click on graphics and the center of my object in Python
Each time, the figure should move 1/16 of its current distance from the goal (the distance gets smaller each time). Thanks!!!!!!!!! for i in range(len(aaa)): midxtoptx = pt.getX() - midptslist[i].getX() midytopty = pt.getY() - midptslist[i].getY() moveAll(aaa[i], midxtoptx/16, midytopty/16) len(aaa) m...
[ "def move(obj, goal):\n obj.x = ((obj.x - goal.x) * 15.0 / 16) + goal.x\n obj.y = ((obj.y - goal.y) * 15.0 / 16) + goal.y\n\nHere's how to think of it:\n\n|========|--------------| \n0 goal obj\n\n|--------------| subtract =======\n0 obj\n\n|------------| ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005177663_python.txt
Q: how to install Virtualenv when Network is unreachable i use this to download Virtualenv : sudo easy_install virtualenv but it show error : Download error: [Errno 101] Network is unreachable -- Some packages may not be found! so how to install Virtualenv when this error , thanks A: You could ask someone to dow...
how to install Virtualenv when Network is unreachable
i use this to download Virtualenv : sudo easy_install virtualenv but it show error : Download error: [Errno 101] Network is unreachable -- Some packages may not be found! so how to install Virtualenv when this error , thanks
[ "You could ask someone to download (Download Link) and give a copy to you via any physical medium which can carry and preserve bytes. But as with many things with easy_install process, a good network connection is essential in order for the package to resolve it's dependencies.\nIf the pypi site is down, as it look...
[ 0, 0 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0005177761_python_virtualenv.txt
Q: Curve fitting in python Hey, I have a set of values for frequency and power spectrum and I have to plot Power spectrum Versus frequency on log scale. Once done, I need to pass the best fit straight line through it.. I get the line on a linear scale.. but when I try to superimpose it onto the freq-power spectrum pl...
Curve fitting in python
Hey, I have a set of values for frequency and power spectrum and I have to plot Power spectrum Versus frequency on log scale. Once done, I need to pass the best fit straight line through it.. I get the line on a linear scale.. but when I try to superimpose it onto the freq-power spectrum plot, the resultant plot does n...
[ "Despite the fact that the plot line commands are not correct in your example I assume it is similar to what you actually do.\nThe second plot command plots on a different x range:\nloglog(yval,zval) # plot yval vs zval\nloglog(line) # plots range(0,len(line)) vs line\n\nAlso have you look at the values of line, ...
[ 2, 2 ]
[]
[]
[ "curve_fitting", "matplotlib", "numpy", "python" ]
stackoverflow_0005178055_curve_fitting_matplotlib_numpy_python.txt
Q: Getting started with the Python debugger, pdb I want to add pdb—the Python debugger—to my toolbox. What's the best way to get started? A: Here's a list of resources to get started with the Python debugger: Read Steve Ferb's article "Debugging in Python" Watch Eric Holscher's screencast "Using pdb, the Python De...
Getting started with the Python debugger, pdb
I want to add pdb—the Python debugger—to my toolbox. What's the best way to get started?
[ "Here's a list of resources to get started with the Python debugger:\n\nRead Steve Ferb's article \"Debugging in Python\"\nWatch Eric Holscher's screencast \"Using pdb, the Python Debugger\"\nRead the Python documentation for pdb — The Python Debugger\nRead Chapter 9—When You Don't Even Know What to Log: Using Debu...
[ 118, 16 ]
[]
[]
[ "pdb", "python" ]
stackoverflow_0004228637_pdb_python.txt
Q: How to tell python non-class objects from class objects I am new to python. I think non-class objects do not have bases attribute whereas class objects do have it. But I am not sure. How does python\cpython checks if an object is non-class or class and passes the correct arguments to the object's descriptor attrib...
How to tell python non-class objects from class objects
I am new to python. I think non-class objects do not have bases attribute whereas class objects do have it. But I am not sure. How does python\cpython checks if an object is non-class or class and passes the correct arguments to the object's descriptor attribute accordingly during the attribute access? ================...
[ "As the commenters asked: Why do you care? Usually that's a sign of not using Python the way it was meant to be used.\nA very powerful concept of Python is duck typing. You don't care about the type or class of an object as long as it exposes the attributes you need. \n", "how about inspect.isclass(objectname)?\n...
[ 1, 0 ]
[]
[]
[ "attributes", "class", "descriptor", "python", "types" ]
stackoverflow_0005177100_attributes_class_descriptor_python_types.txt
Q: easy_install libmysqld-dev error :'NoneType' object has no attribute 'clone' this is the error : (mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ ./bin/easy_install libmysqld-dev Searching for libmysqld-dev Reading http://pypi.python.org/simple/libmysqld-dev/ Couldn't find index page for 'libmysqld-dev' (maybe...
easy_install libmysqld-dev error :'NoneType' object has no attribute 'clone'
this is the error : (mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ ./bin/easy_install libmysqld-dev Searching for libmysqld-dev Reading http://pypi.python.org/simple/libmysqld-dev/ Couldn't find index page for 'libmysqld-dev' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading http:...
[ "Try to update setuptools:\neasy_install -U setuptools\n\n", "This error indicates that easy-install cannot locate the package, meaning that it is not found.\nYou'd be better off installing the dev package via your distribution's package manager (apt-get etc)\nIf you examine the output carefully, notice:\n\nReadi...
[ 5, 4 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0005178535_easy_install_python.txt
Q: How can I get CVtypes for OpenCV working in Python on Ubuntu I have downloaded CVtypes and tried the example scripts with it but cannot get it working. The error I get is: pete@pete-MacBookPro:~/python_scratch/cvtypes$ python showcam.py Traceback (most recent call last): File "showcam.py", line 1, in <module> ...
How can I get CVtypes for OpenCV working in Python on Ubuntu
I have downloaded CVtypes and tried the example scripts with it but cannot get it working. The error I get is: pete@pete-MacBookPro:~/python_scratch/cvtypes$ python showcam.py Traceback (most recent call last): File "showcam.py", line 1, in <module> from CVtypes import cv File "/home/pete/python_scratch/cvtype...
[ "Turns out CVtypes is ooooold. I needed PyOpenCV instead. As a Perl coder who is a newbie to Python I find the instability and deprecation a bit annoying.\n" ]
[ 0 ]
[]
[]
[ "opencv", "python", "ubuntu" ]
stackoverflow_0005166871_opencv_python_ubuntu.txt
Q: Intercepting subprocess.Popen call in Python I'm writing a functional test for a legacy Python script so that I can make a one-line change to it without being paralysed by fear. ;) The script in question invokes wget(1) using subprocess.Popen to download an XML file which is then parsed: def download_files(): ...
Intercepting subprocess.Popen call in Python
I'm writing a functional test for a legacy Python script so that I can make a one-line change to it without being paralysed by fear. ;) The script in question invokes wget(1) using subprocess.Popen to download an XML file which is then parsed: def download_files(): os.mkdir(FEED_DIR) os.chdir(FEED_DIR) wge...
[ "Several problems with my approach:\nI didn't realise that args is magical in Python, nor that I needed kwargs as well.\nI was replacing subprocess.Popen.__call__, when I should be replacing subprocess.Popen itself.\nMost importantly, replacing Popen is obviously only going to affect the current process, not the ne...
[ 4, 3, 1 ]
[]
[]
[ "functional_testing", "mocking", "python", "testing" ]
stackoverflow_0005166851_functional_testing_mocking_python_testing.txt
Q: How can PyUSB be understood? I am unable to proceed on how PyUSB works. I am stuck for a week now. How do I proceed? A: At first glance, documentation for PyUSB seems to be entirely absent. But not so. From a Python prompt you can: >>> import usb >>> help(usb) And it turns out to have documentation! >>> help...
How can PyUSB be understood?
I am unable to proceed on how PyUSB works. I am stuck for a week now. How do I proceed?
[ "At first glance, documentation for PyUSB seems to be entirely absent. But not so.\nFrom a Python prompt you can:\n >>> import usb\n >>> help(usb)\n\nAnd it turns out to have documentation!\n >>> help(usb.core)\n\nWas quite useful. It seems quite straightforward.\n" ]
[ 14 ]
[]
[]
[ "python", "pyusb", "usb" ]
stackoverflow_0005178445_python_pyusb_usb.txt
Q: Python Ask For Decimal Number Can someone please tell me how to get the code to ask for a value (say the user would enter 100.00) and put that number with it's 2 decimal points value for more functions later on, ie: multipling it, etc. Thanks. A: Here's a start (for Python 3; for Python 2, use raw_input instead ...
Python Ask For Decimal Number
Can someone please tell me how to get the code to ask for a value (say the user would enter 100.00) and put that number with it's 2 decimal points value for more functions later on, ie: multipling it, etc. Thanks.
[ "Here's a start (for Python 3; for Python 2, use raw_input instead of input):\nwhile True:\n snum = input(\"Please enter a decimal number:\")\n try:\n num = float(snum)\n break\n except ValueError:\n print(\"This is not a valid decimal number!\")\nprint(\"This number, rounded to two pl...
[ 3, 0 ]
[]
[]
[ "decimal", "python" ]
stackoverflow_0005179307_decimal_python.txt
Q: 'JSONDecoder' object has no attribute 'object_pairs_hook' error this is my error : (mysite)zjm1126@zjm1126-G41MT-S2:~/Code/trinity_src$ python manage_dev.py runserver Validating models... Unhandled exception in thread started by <function inner_run at 0xa20c064> Traceback (most recent call last): File "/home/zjm...
'JSONDecoder' object has no attribute 'object_pairs_hook' error
this is my error : (mysite)zjm1126@zjm1126-G41MT-S2:~/Code/trinity_src$ python manage_dev.py runserver Validating models... Unhandled exception in thread started by <function inner_run at 0xa20c064> Traceback (most recent call last): File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/django/core/manageme...
[ "According to this bug report in Django this can be caused by not importing simplejson using:\nfrom django.utils import simplejson\n\nIt seems that you might be experiencing a conflict between the version of simplejson included with Django and the one included with rekoo_lib. I can't find anything useful about reko...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005179198_django_python.txt
Q: How to check the performance of a django application? I have created a django app. Now i want to test the application's performance with some 5000 data. Is there any method to do it ? Is there any method to randomly enter this data into db and run the application ? I believe there should be some method rather than...
How to check the performance of a django application?
I have created a django app. Now i want to test the application's performance with some 5000 data. Is there any method to do it ? Is there any method to randomly enter this data into db and run the application ? I believe there should be some method rather than typing 5000 data manually into db. The database i use is m...
[ "Check out django-dilla. It helps you to spam your database with random data\nThere's no real good documentation, but you'll need to install it and add it to your INSTALLED_APPS, then run python manage.py run_dilla from the command line.\nTo view the options run python manage.py run_dilla --help which let you spec...
[ 4, 2 ]
[]
[]
[ "django", "profiling", "python" ]
stackoverflow_0005163389_django_profiling_python.txt
Q: Python limit of the * operator and zip() function I have a Python code similar to this one: for lines in zip(*files): # do something where files is a list of files, each file is a list of lines and each line is a list of strings. Therefore, the code above should first unpack the list files and then apply the f...
Python limit of the * operator and zip() function
I have a Python code similar to this one: for lines in zip(*files): # do something where files is a list of files, each file is a list of lines and each line is a list of strings. Therefore, the code above should first unpack the list files and then apply the function zip(), returning a tuple with the first line of...
[ "If one of the files is empty, zip will return an empty list. As of Python 2.6 you can use itertools.izip_longest to handle that. On older versions, you can use map(None, *files), courtesy of @Sven Marnach.\n" ]
[ 9 ]
[]
[]
[ "memory", "python", "zip" ]
stackoverflow_0005179663_memory_python_zip.txt
Q: Python Lists - How this connection is made? I'm reading about algorithms in Python but I'm also new in Python. I just need to understand how this is made: a, b, c, d, e, f, g, h = range(8) N = [ [b, c, d, e, f], # a [c, e], # b [d], # c [e], # d [f], # e [c, g, h], # f [f, h], # g [f, g] # h ] print(N[a]) --> Res...
Python Lists - How this connection is made?
I'm reading about algorithms in Python but I'm also new in Python. I just need to understand how this is made: a, b, c, d, e, f, g, h = range(8) N = [ [b, c, d, e, f], # a [c, e], # b [d], # c [e], # d [f], # e [c, g, h], # f [f, h], # g [f, g] # h ] print(N[a]) --> Result: [1, 2, 3, 4, 5] How can Python knows that t...
[ "Well, in the first line the range(8), which is a list with numbers from 0 to 7, is unpacked to 8 names (vars). The a name has the value 0 then. So, N[a] is actually N[0] is actually [b, c, d, e, f] is actually [1, 2, 3, 4, 5].\n", "Here are two hints for you:\n\nFigure out what values get assigned to variables a...
[ 4, 2, 2, 1, 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0005179823_algorithm_python.txt
Q: Python Chosing To Ignore String Value Using Python v2, is there a way to ignore a value in a string if it is there? For instance: I want someone to enter a value of $100.00, or they could enter a value of 100.00 without the leading $ symbol. What I want to do is ignore the '$' value if it is typed in. Any push in ...
Python Chosing To Ignore String Value
Using Python v2, is there a way to ignore a value in a string if it is there? For instance: I want someone to enter a value of $100.00, or they could enter a value of 100.00 without the leading $ symbol. What I want to do is ignore the '$' value if it is typed in. Any push in the right direction would be appreciated.
[ "Maybe\ns = \" $100.00 \"\nf = float(s.strip().lstrip(\"$\"))\n\nThe .strip() strips whitespace from the beginning and the end of the string, and the .lstrip(\"$\") strips a dollar sign from the beginning, if present.\n", "Just filter out unwanted characters from the string. There are multiple ways of doing this...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0005179934_python_string.txt
Q: PyGTK how to "load-on-demand" data to TreeView I'm using PyGTK TreeView (as list) for my data. Is there any way to load more data on demand by going throu the list. For example: I have database table where is 200 000 records. At application start- loads 200 records from table. when i scroll download more data to t...
PyGTK how to "load-on-demand" data to TreeView
I'm using PyGTK TreeView (as list) for my data. Is there any way to load more data on demand by going throu the list. For example: I have database table where is 200 000 records. At application start- loads 200 records from table. when i scroll download more data to treeView.
[ "I believe you could do following:\n\nAdd empty lines to your model, I believe you should be using GtkListStore\nFor the treeview cell renderer define a data function.\nIn the data function check if current model row is loaded and load it from SQL if it's not. I guess you can use cashing here and load more then one...
[ 3, 0 ]
[]
[]
[ "gtk", "gtktreeview", "listview", "python" ]
stackoverflow_0005155407_gtk_gtktreeview_listview_python.txt
Q: importing from subdirectories in Python I am new to Python and I am confused in importing files from subdirectories. My filesystem structure is as follows: /doc/a/main.py /second.py /doc/b/prog.py Now I want to import main and second in prog.py. Can anyone suggest me a method to do so? A: import sys sys...
importing from subdirectories in Python
I am new to Python and I am confused in importing files from subdirectories. My filesystem structure is as follows: /doc/a/main.py /second.py /doc/b/prog.py Now I want to import main and second in prog.py. Can anyone suggest me a method to do so?
[ "import sys\nsys.path.append(\"../a\")\nimport main, second\n\nand then call prog.py while in directory b.\n", "First you should learn what a proper Python package makes: it needs to contain a file named __init__.py\nThe search path of Python can be configured either by modifying sys.path or setting the $PYTHONPA...
[ 4, 4 ]
[]
[]
[ "import", "python" ]
stackoverflow_0005180215_import_python.txt
Q: How to format unicode strings to utf-8 in Python? I'm reading in a JSON string which is littered with u'string' style strings. Example: [ { "!\/award\/award_honor\/honored_for": { "award": { "id": "\/en\/spiel_des_jahres" }, "year": { "value": "1996" ...
How to format unicode strings to utf-8 in Python?
I'm reading in a JSON string which is littered with u'string' style strings. Example: [ { "!\/award\/award_honor\/honored_for": { "award": { "id": "\/en\/spiel_des_jahres" }, "year": { "value": "1996" } }, "guid": "#9202a8c04000641f800000000...
[ ">>> # example\n>>> s = u\"Jägermütze\"\n>>> s.encode(\"utf-8\")\n'J\\xc3\\xa4germ\\xc3\\xbctze'\n>>> print s.encode(\"utf-8\") # on a utf-8 terminal\nJägermütze\n\nDon't know much about Django, but not accepting snicode strings seems unpythonic to me.\n", "The comma at the end of games[\"name\"] = name, makes it...
[ 1, 1, 0 ]
[]
[]
[ "django", "freebase", "json", "python" ]
stackoverflow_0004495173_django_freebase_json_python.txt