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: On App Engine, what does optimization for reads mean? In the documentation for Google App Engine, it says that when designing data models for the datastore, you should "optimize for reads, not writes". What exactly does this mean? What is more 'expensive', CPU intensive or time consuming? A: It means that "reads...
On App Engine, what does optimization for reads mean?
In the documentation for Google App Engine, it says that when designing data models for the datastore, you should "optimize for reads, not writes". What exactly does this mean? What is more 'expensive', CPU intensive or time consuming?
[ "It means that \"reads\" are cheaper than \"writes\". \"Writes\" takes more time and more resources. For more information check the presentation \"Building Scalable Web Applications with Google App Engine\" by Brett Slatkin from Google I/0 2008 (slides 7-8)\n", "\"Optimize for reads, not writes\" means that you s...
[ 2, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002694542_google_app_engine_python.txt
Q: `strip`ing the results of a split in python i'm trying to do something pretty simple: line = "name : bob" k, v = line.lower().split(':') k = k.strip() v = v.strip() is there a way to combine this into one line somehow? i found myself writing this over and over again when making parsers, and sometimes this...
`strip`ing the results of a split in python
i'm trying to do something pretty simple: line = "name : bob" k, v = line.lower().split(':') k = k.strip() v = v.strip() is there a way to combine this into one line somehow? i found myself writing this over and over again when making parsers, and sometimes this involves way more than just two variables. i kno...
[ "k, v = [x.strip() for x in line.lower().split(':')]\n\n", "import 're'\nk,v = re.split(r'\\s*:\\s*', line)\nline = ':'.join((k,v))\n\n", ">>> map(str.strip,line.lower().split(\":\"))\n['name', 'bob']\n\n" ]
[ 7, 1, 1 ]
[ "\":\".join([k, v])\n\n" ]
[ -1 ]
[ "parsing", "python" ]
stackoverflow_0002695464_parsing_python.txt
Q: Convert a list of strings [ '3', '1', '2' ] to a list of sorted integers [1, 2, 3] I have a list of integers in string representation, similar to the following: L1 = ['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8'] I need to make it a list of integers l...
Convert a list of strings [ '3', '1', '2' ] to a list of sorted integers [1, 2, 3]
I have a list of integers in string representation, similar to the following: L1 = ['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8'] I need to make it a list of integers like: L2 = [11, 10, 13, 12, 15, 14, 1, 3, 2, 5, 4, 7, 6, 9, 8] Finally I will sort it li...
[ "You could do it in one step like this:\nL3 = sorted(map(int, L1))\n\nIn more detail, here are the steps:\n>>> L1 = ['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8']\n>>> L1\n['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8']\n>>> map(int, L1)\n[11, 10,...
[ 19, 5, 4 ]
[]
[]
[ "integer", "list", "python", "sorting", "string" ]
stackoverflow_0002695472_integer_list_python_sorting_string.txt
Q: Can you access registers from python functions in vim It seems vims python sripting is designed to edit buffer and files rather than work nicely with vims registers. You can use some of the vim packages commands to get access to the registers but its not pretty. My solution for creating a vim function using python...
Can you access registers from python functions in vim
It seems vims python sripting is designed to edit buffer and files rather than work nicely with vims registers. You can use some of the vim packages commands to get access to the registers but its not pretty. My solution for creating a vim function using python that uses a register is something like this. function prin...
[ "If you use single quotes everything you need is to replace every occurence of single quote with two single quotes.\nSomething like that:\npython import vim, re\npython def senclose(str): return \"'\"+re.sub(re.compile(\"'\"), \"''\", str)+\"'\"\npython vim.command(\"let @r=\"+senclose(\"string with single 'quotes'...
[ 6 ]
[]
[]
[ "delimiter", "python", "vim" ]
stackoverflow_0002695443_delimiter_python_vim.txt
Q: "from _json import..." - python I am inspecting the JSON module of python 3.1, and am currently in /Lib/json/scanner.py. At the top of the file is the following line: from _json import make_scanner as c_make_scanner There are five .py files in the module's directory: __init__ (two leading and trailing underscores...
"from _json import..." - python
I am inspecting the JSON module of python 3.1, and am currently in /Lib/json/scanner.py. At the top of the file is the following line: from _json import make_scanner as c_make_scanner There are five .py files in the module's directory: __init__ (two leading and trailing underscores, it's formatting as bold), decoder, ...
[ "It's coming from a C-compiled _json.pyd (or _json.so, etc, etc, depending on the platform) that lives elsewhere on the sys.path. You can always find out where that is in your specific Python installation by importing the module yourself and looking at its __file__, e.g.:\n>>> import _json\n>>> _json.__file__\n'/L...
[ 6, 1 ]
[]
[]
[ "import", "json", "module", "python" ]
stackoverflow_0002696125_import_json_module_python.txt
Q: How to insert and call by row and column into sqlite3 python Lets say i have a simple array of x rows and y columns with corresponding values, What is the best method to do 3 things? How to insert, update a value at a specific row column? How to select a value for each row and column, import sqlite3 con = sqlite...
How to insert and call by row and column into sqlite3 python
Lets say i have a simple array of x rows and y columns with corresponding values, What is the best method to do 3 things? How to insert, update a value at a specific row column? How to select a value for each row and column, import sqlite3 con = sqlite3.connect('simple.db') c = con.cursor() c.execute('''create table ...
[ "So you have a dictionary of dictionaries, that you want to convert into a SQL table.\nSteps I'd take\n\nFind the columns you'll need.\nCreate the table schema.\nLoop through each row.\n\n\nCompile the set of values for each column.\nInsert it.\n\n\nSo:\nimport sqlite3\ncon = sqlite3.connect('simple.db')\nc = con.c...
[ 2 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0002694442_python_sqlite.txt
Q: problem plotting on logscale in matplotlib in python I am trying to plot the following numbers on a log scale as a scatter plot in matplotlib. Both the quantities on the x and y axes have very different scales, and one of the variables has a huge dynamic range (nearly 0 to 12 million roughly) while the other is b...
problem plotting on logscale in matplotlib in python
I am trying to plot the following numbers on a log scale as a scatter plot in matplotlib. Both the quantities on the x and y axes have very different scales, and one of the variables has a huge dynamic range (nearly 0 to 12 million roughly) while the other is between nearly 0 and 2. I think it might be good to plot b...
[ "I don't know why you only get those two points. For this case, you can manually adjust the limits to make sure all your points fit. I ran:\nimport matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(8, 8)) # You were missing the =\nax = fig.add_subplot(1, 1, 1)\nax.set_yscale('log')\nax.set_xscale('log')\nplt.sc...
[ 3, 2 ]
[]
[]
[ "graphing", "numpy", "plot", "python", "scipy" ]
stackoverflow_0002695598_graphing_numpy_plot_python_scipy.txt
Q: Getting an entry before and after a given entry in a Django Queryset I am creating a simple blog as part of a website and I am getting stuck on something that I am assuming is simple. If I call any blog post, say by it's title, from a queryset, how can I get the entry before and after the post in it's published or...
Getting an entry before and after a given entry in a Django Queryset
I am creating a simple blog as part of a website and I am getting stuck on something that I am assuming is simple. If I call any blog post, say by it's title, from a queryset, how can I get the entry before and after the post in it's published order. I can iterate over the whole thing, get the position of the entry I h...
[ "You're looking for Posts.get_{next,previous}_by_FOO().\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002696677_django_python.txt
Q: Python, concise way to test membership in collection using partial match What is the pythonic way to test if there is a tuple starting with another tuple in collection? actually, I am really after the index of match, but I can probably figure out from test example for example: c = ((0,1),(2,3)) # (0,) should matc...
Python, concise way to test membership in collection using partial match
What is the pythonic way to test if there is a tuple starting with another tuple in collection? actually, I am really after the index of match, but I can probably figure out from test example for example: c = ((0,1),(2,3)) # (0,) should match first element, (3,)should match no element I should add my python is 2.4 an...
[ "Edit:\nThanks to the OP for the addition explanation of the problem.\nS.Mark's nested list comprehensions are pretty wicked; check 'em out.\nI might opt to use an auxiliary function:\ndef tup_cmp(mytup, mytups):\n return any(x for x in mytups if mytup == x[:len(mytup)])\n\n>>> c = ((0, 1, 2, 3), (2, 3, 4, 5))\n...
[ 3, 2, 1 ]
[]
[]
[ "collections", "membership", "python" ]
stackoverflow_0002696432_collections_membership_python.txt
Q: how to make a thread of never stop, and write something to database every 10 second i using gae and django this is my code: class LogText(db.Model): content = db.StringProperty(multiline=True) class MyThread(threading.Thread): def __init__(self,threadname): threading.Thread.__init__(self, name=thr...
how to make a thread of never stop, and write something to database every 10 second
i using gae and django this is my code: class LogText(db.Model): content = db.StringProperty(multiline=True) class MyThread(threading.Thread): def __init__(self,threadname): threading.Thread.__init__(self, name=threadname) def run(self,request): log=LogText() log.content=request.PO...
[ "It's impossible to do in GAE since all requests (including cron job) have 30 seconds deadline.\n" ]
[ 1 ]
[]
[]
[ "django", "google_app_engine", "multithreading", "python" ]
stackoverflow_0002696644_django_google_app_engine_multithreading_python.txt
Q: How to override inner class methods if the inner class is defined as a property of the top class I have a code snippet like this class A(object): class b: def print_hello(self): print "Hello world" b = property(b) And I want to override the inner class b (please dont worry about the lo...
How to override inner class methods if the inner class is defined as a property of the top class
I have a code snippet like this class A(object): class b: def print_hello(self): print "Hello world" b = property(b) And I want to override the inner class b (please dont worry about the lowercase name) behaviour. Say, I want to add a new method or I want to change an existing method, like:...
[ "I'm not really sure why you would define the inner class as a property of the outer class. (I'm no Python expert, so perhaps there's a reason I'm not aware of).\nIt seems to work fine without the properties:\nclass A(object):\n class b:\n def print_hello(self):\n print \"A Hello world\"\n\ncla...
[ 1, 1, 0 ]
[]
[]
[ "inheritance", "inner_classes", "python" ]
stackoverflow_0002697062_inheritance_inner_classes_python.txt
Q: How to Disassemble an object creation in Python? Having a class like this: class Spam(object): def __init__(self, name=''): self.name = name eggs = Spam('systempuntoout') using dis, is it possible to see how an instance of a class and the respective hex Identity are created? A: Yes, but it isn't obvio...
How to Disassemble an object creation in Python?
Having a class like this: class Spam(object): def __init__(self, name=''): self.name = name eggs = Spam('systempuntoout') using dis, is it possible to see how an instance of a class and the respective hex Identity are created?
[ "Yes, but it isn't obvious from the output, which is at the level of Python bytecode, e.g.:\n>>> class Foo(object):\n... def f(x): return x * x\n... \n>>> dis.dis(Foo)\nDisassembly of f:\n 2 0 LOAD_FAST 0 (x)\n 3 LOAD_FAST 0 (x)\n 6 BINARY_MULTIPL...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002697355_python.txt
Q: how to dispose a incoming email and then send some words back using google-app-engine I read the doc: from google.appengine.api import mail mail.send_mail(sender="support@example.com", to="Albert Johnson <Albert.Johnson@example.com>", subject="Your account has been approved"...
how to dispose a incoming email and then send some words back using google-app-engine
I read the doc: from google.appengine.api import mail mail.send_mail(sender="support@example.com", to="Albert Johnson <Albert.Johnson@example.com>", subject="Your account has been approved", body=""" Dear Albert: Your example.com account has been approved. ...
[ "Here's the page in the docs that deals with how to receive email.\n" ]
[ 1 ]
[]
[]
[ "django", "google_app_engine", "incoming_mail", "python" ]
stackoverflow_0002696955_django_google_app_engine_incoming_mail_python.txt
Q: Urllib and concurrency - Python I'm serving a python script through WSGI. The script accesses a web resource through urllib, computes the resource and then returns a value. Problem is that urllib doesn't seem to handle many concurrent requests to a precise URL. As soon as the requests go up to 30 concurrent reques...
Urllib and concurrency - Python
I'm serving a python script through WSGI. The script accesses a web resource through urllib, computes the resource and then returns a value. Problem is that urllib doesn't seem to handle many concurrent requests to a precise URL. As soon as the requests go up to 30 concurrent request, the requests slow to a crawl! :( ...
[ "Yeah, urllib doesn't do much concurrency. Every time you urlopen, it has to set up the connection, send the HTTP request, and get the status code and headers from the response (and possibly handle a redirect from there). So although you get to read the body of the response at your own pace, the majority of the wai...
[ 3 ]
[]
[]
[ "concurrency", "http", "python", "urllib", "wsgi" ]
stackoverflow_0002697349_concurrency_http_python_urllib_wsgi.txt
Q: How GAE emulator limits list of available Python modules? I installed Python Mock module using PIP. When I try to import mock running under 'dev_appserver', GAE says that it can't find module 'mock'. import mock works perfectly in Python interpreter. I understand that dev_appserver behaves absolutely correctly bec...
How GAE emulator limits list of available Python modules?
I installed Python Mock module using PIP. When I try to import mock running under 'dev_appserver', GAE says that it can't find module 'mock'. import mock works perfectly in Python interpreter. I understand that dev_appserver behaves absolutely correctly because I can't install modules with PIP on GAE servers. My questi...
[ "The dev_appserver uses import hooks to prevent importing modules that shouldn't be available. The relevant code is here, but be warned - it's easily the most complicated bit of the dev_appserver!\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002697457_google_app_engine_python.txt
Q: Python syntax error: can't assign to operator in module but works in interpreter I have a string a and I would like to split it in half depending on its length, so I have a-front = len(a) / 2 + len(a) % 2 this works fine in the interpreter but when i run the module from the command line python gives me a SyntaxEr...
Python syntax error: can't assign to operator in module but works in interpreter
I have a string a and I would like to split it in half depending on its length, so I have a-front = len(a) / 2 + len(a) % 2 this works fine in the interpreter but when i run the module from the command line python gives me a SyntaxError: can't assign to operator. What could be the issue here.
[ "You might mistype hyphen and underscore, try\na_front = len(a) / 2 + len(a) % 2\n\n" ]
[ 13 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002697610_python_syntax.txt
Q: Multiprocessing Bomb I was working the following example from Doug Hellmann tutorial on multiprocessing: import multiprocessing def worker(): """worker function""" print 'Worker' return if __name__ == '__main__': jobs = [] for i in range(5): p = multiprocessing.Process(target=worker) ...
Multiprocessing Bomb
I was working the following example from Doug Hellmann tutorial on multiprocessing: import multiprocessing def worker(): """worker function""" print 'Worker' return if __name__ == '__main__': jobs = [] for i in range(5): p = multiprocessing.Process(target=worker) jobs.append(p) ...
[ "On Windows there is no fork() routine, so multiprocessing imports the current module to get access to the worker function. Without the if statement the child process starts its own children and so on.\n", "Note that the documentation mentions that you need the if statement on windows (here).\nHowever, the docume...
[ 47, 10, 4 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0002697640_multiprocessing_python.txt
Q: Socket Lose Connection I know Twisted can do this well but what about just plain socket? How'd you tell if you randomly lost your connection in socket? Like, If my internet was to go out of a second and come back on. A: I'm assuming you're talking about TCP. If your internet connection is out for a second, you m...
Socket Lose Connection
I know Twisted can do this well but what about just plain socket? How'd you tell if you randomly lost your connection in socket? Like, If my internet was to go out of a second and come back on.
[ "I'm assuming you're talking about TCP.\nIf your internet connection is out for a second, you might not lose the TCP connection at all, it'll just retransmit and resume operation.\nThere's ofcourse 100's of other reasons you could lose the connection(e.g. a NAT gateway inbetween decided to throw out the connection ...
[ 1, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002697989_python_sockets.txt
Q: How to start a program with Python? How to start a program with Python? I thougt this would be very easy like: open(r"C:\Program Files\Mozilla Firefox\Firefox.exe") But nothing happens. How to do this? Thanks in advance. A: In general you can do that using subprocess.call >>> from subprocess import call >>> c...
How to start a program with Python?
How to start a program with Python? I thougt this would be very easy like: open(r"C:\Program Files\Mozilla Firefox\Firefox.exe") But nothing happens. How to do this? Thanks in advance.
[ "In general you can do that using subprocess.call \n>>> from subprocess import call\n>>> call(r\"C:\\Program Files\\Mozilla Firefox\\Firefox.exe\")\n\nBut if all you want to do is open a page in a browser you can do:\n>>> import webbrowser\n>>> webbrowser.open('http://stackoverflow.com/')\nTrue\n\nSee http://docs.p...
[ 13, 7, 2 ]
[]
[]
[ "load", "python" ]
stackoverflow_0002698331_load_python.txt
Q: Why does Fabric display the disconnect from server message for almost 2 minutes? Fabric displays Disconnecting from username@server... done. for almost 2 minutes prior to showing a new command prompt whenever I issue a fab command. This problem exists when using Fabric commands issued to both an internal server an...
Why does Fabric display the disconnect from server message for almost 2 minutes?
Fabric displays Disconnecting from username@server... done. for almost 2 minutes prior to showing a new command prompt whenever I issue a fab command. This problem exists when using Fabric commands issued to both an internal server and a Rackspace cloud server. Below I've included the auth.log from the server, and I di...
[ "Solution\nThe problem no longer persists after I issued the following command in my virtualenv:\npip install -U paramiko\n\nThis installed paramiko-1.7.6 and pycrypto-2.0.1. Previously, I had paramiko-1.7.4 and pycrypto-2.0.1.\nAppears that paramiko was the culprit given that the pycrypto version didn't change. At...
[ 6, 2 ]
[]
[]
[ "fabric", "paramiko", "python", "ssh", "virtualenv" ]
stackoverflow_0002685788_fabric_paramiko_python_ssh_virtualenv.txt
Q: removing pairs of elements from numpy arrays that are NaN (or another value) in Python I have an array with two columns in numpy. For example: a = array([[1, 5, nan, 6], [10, 6, 6, nan]]) a = transpose(a) I want to efficiently iterate through the two columns, a[:, 0] and a[:, 1] and remove any pairs th...
removing pairs of elements from numpy arrays that are NaN (or another value) in Python
I have an array with two columns in numpy. For example: a = array([[1, 5, nan, 6], [10, 6, 6, nan]]) a = transpose(a) I want to efficiently iterate through the two columns, a[:, 0] and a[:, 1] and remove any pairs that meet a certain condition, in this case if they are NaN. The obvious way I can think of i...
[ "If you want to take only the rows that have no NANs, this is the expression you need:\n>>> import numpy as np\n>>> a[~np.isnan(a).any(1)]\narray([[ 1., 10.],\n [ 5., 6.]])\n\nIf you want the rows that do not have a specific number among its elements, e.g. 5:\n>>> a[~(a == 5).any(1)]\narray([[ 1., 10.]...
[ 31, 3, 3, 2 ]
[]
[]
[ "arrays", "numpy", "python", "scipy" ]
stackoverflow_0002695503_arrays_numpy_python_scipy.txt
Q: file output in python giving me garbage When I write the following code I get garbage for an output. It is just a simple program to find prime numbers. It works when the first for loops range only goes up to 1000 but once the range becomes large the program fail's to output meaningful data output = open("output.da...
file output in python giving me garbage
When I write the following code I get garbage for an output. It is just a simple program to find prime numbers. It works when the first for loops range only goes up to 1000 but once the range becomes large the program fail's to output meaningful data output = open("output.dat", 'w') for i in range(2, 10000): prime ...
[ "You're setting a single variable named prime ten thousand times to 1, then 9998 times possibly setting it to 0, and finally (if it's not been set to 0) outputting one incomplete line (no line-end). I suspect that's not what you want to do! Maybe something like...:\noutput = open(\"output.dat\", 'w')\nfor i in ra...
[ 3, 3, 1, 0, 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0002699014_file_python.txt
Q: Regex: Matching a space-joined list of words, excluding last whitespace How would I match a space separated list of words followed by whitespace and some optional numbers? I have this: >>> import re >>> m = re.match('(?P<words>(\S+\s+)+)(?P<num>\d+)?\r\n', 'Foo Bar 12345\r\n') >>> m.groupdict() {'num': '12345', '...
Regex: Matching a space-joined list of words, excluding last whitespace
How would I match a space separated list of words followed by whitespace and some optional numbers? I have this: >>> import re >>> m = re.match('(?P<words>(\S+\s+)+)(?P<num>\d+)?\r\n', 'Foo Bar 12345\r\n') >>> m.groupdict() {'num': '12345', 'words': 'Foo Bar '} I'd like the words group to not include the last whites...
[ "I'm a bit confused by your double capturing group, and the fact that you're using \\w but want to match a non-word character like & (maybe you mean \\S, non-spaces, where you say \\w...?), but, maybe...:\n>>> import re\n>>> r = re.compile(r'(?P<words>\\w+(?:\\s+\\S+)*?)\\s*(?P<num>\\d+)?\\r\\n')\n>>> for s in ('Fo...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002699366_python_regex.txt
Q: cx_Oracle and output variables I'm trying to do this again an Oracle 10 database: cursor = connection.cursor() lOutput = cursor.var(cx_Oracle.STRING) cursor.execute(""" BEGIN %(out)s := 'N'; END;""", {'out' : lOutput}) print lOutput.value but I'm getting Databas...
cx_Oracle and output variables
I'm trying to do this again an Oracle 10 database: cursor = connection.cursor() lOutput = cursor.var(cx_Oracle.STRING) cursor.execute(""" BEGIN %(out)s := 'N'; END;""", {'out' : lOutput}) print lOutput.value but I'm getting DatabaseError: ORA-01036: illegal variable ...
[ "Yes, you can do anonymous PL/SQL blocks. Your bind variable for the output parameter is not in the correct format. It should be :out instead of %(out)s\ncursor = connection.cursor()\nlOutput = cursor.var(cx_Oracle.STRING)\ncursor.execute(\"\"\"\n BEGIN\n :out := 'N';\n END;\"...
[ 9 ]
[]
[]
[ "cx_oracle", "oracle", "oracle10g", "python" ]
stackoverflow_0002698008_cx_oracle_oracle_oracle10g_python.txt
Q: python unittest howto I`d like to know how I could unit-test the following module. def download_distribution(url, tempdir): """ Method which downloads the distribution from PyPI """ print "Attempting to download from %s" % (url,) try: url_handler = urllib2.urlopen(url) distribution_con...
python unittest howto
I`d like to know how I could unit-test the following module. def download_distribution(url, tempdir): """ Method which downloads the distribution from PyPI """ print "Attempting to download from %s" % (url,) try: url_handler = urllib2.urlopen(url) distribution_contents = url_handler.read() ...
[ "Vague question. If you're just looking for a primer for unit testing in general with a Python slant, I recommend Mark Pilgrim's \"Dive Into Python\" which has a chapter on unit testing with Python. Otherwise you need to clear up what specific issues you are having testing that code.\n", "Unit test propositione...
[ 5, 5, 0 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0002655697_python_unit_testing.txt
Q: Is it possible to retrieve an uri chunk on AppEngine? Let's say i go to myblog.com/post/12. The /post handler is already defined, but how can i get the parameter being passed? 12 in this case is the post_id. I'm using the Python SDK. A: Sure. Example rule: ('/post/(\d+)', views.PostHandler) Example view: clas...
Is it possible to retrieve an uri chunk on AppEngine?
Let's say i go to myblog.com/post/12. The /post handler is already defined, but how can i get the parameter being passed? 12 in this case is the post_id. I'm using the Python SDK.
[ "Sure.\nExample rule:\n('/post/(\\d+)', views.PostHandler)\n\nExample view:\nclass PostHandler(BaseHandler):\n ''' Handler for viewing blog posts. '''\n def get(self, id):\n blog_post = models.BlogPost.get_by_id(int(id))\n\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "python", "uri" ]
stackoverflow_0002700159_google_app_engine_python_uri.txt
Q: Python if statement not working as expected I'm searching for a string in a website and checking to see if the location of this string is in the expected location. I know the string starts at the 182nd character, and if I print temp it will even tell me that it is 182, however, the if statement says 182 is not 18...
Python if statement not working as expected
I'm searching for a string in a website and checking to see if the location of this string is in the expected location. I know the string starts at the 182nd character, and if I print temp it will even tell me that it is 182, however, the if statement says 182 is not 182. Some code f = urllib.urlopen(link) #store pa...
[ "str.find returns integer, not string. String-integers comparison always returns False.\n", "Im not a python guru, but ill take a shot\nTry it like this\nif (temp == 182)\n\nWhy? See SilentGhost answer. It involves types\n" ]
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002700255_python.txt
Q: Django and Reportlab Question I have written this small Django view to return pdf. @login_required def code_view(request,myid): try: deal = Deal.objects.get(id=myid) except: raise Http404 header = deal.header code = deal.code response = HttpResponse(mimetype='application/pdf') ...
Django and Reportlab Question
I have written this small Django view to return pdf. @login_required def code_view(request,myid): try: deal = Deal.objects.get(id=myid) except: raise Http404 header = deal.header code = deal.code response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] ...
[ "You should move to the next level and use DocTemplates.\nImages are quite easy, but using bullets is really hard - you have to define styles and more!\nI use a set of classes like the below:\n# -*- coding: utf-8 -*-\n\nfrom django.utils.encoding import smart_str\nfrom reportlab.lib.colors import Color\nfrom report...
[ 10, 2 ]
[]
[]
[ "django", "pdf", "python", "reportlab" ]
stackoverflow_0002467042_django_pdf_python_reportlab.txt
Q: Importing Classes Within a Module Currently, I have a parser with multiple classes that work together. For Instance: TreeParser creates multiple Product and Reactant modules which in turn create multiple Element classes. The TreeParser is called by a render method within the same module, which is called from the i...
Importing Classes Within a Module
Currently, I have a parser with multiple classes that work together. For Instance: TreeParser creates multiple Product and Reactant modules which in turn create multiple Element classes. The TreeParser is called by a render method within the same module, which is called from the importer. Finally, if the package has de...
[ "I think this is the key statement in your question.\n\nI don't really want to add the module name in front of every call to the class\n\nMy response: I hear what you're saying, but this is standard practice in Python.\nAny Python programmer reading code like \"result = match(blah)\" will presume you're calling a l...
[ 3, 2 ]
[]
[]
[ "module", "namespaces", "python" ]
stackoverflow_0002699987_module_namespaces_python.txt
Q: Storing hierarchical (parent/child) data in Python/Django: MPTT alternative? I'm looking for a good way to store and use hierarchical (parent/child) data in Django. I've been using django-mptt, but it seems entirely incompatible with my brain - I end up with non-obvious bugs in non-obvious places, mostly when movi...
Storing hierarchical (parent/child) data in Python/Django: MPTT alternative?
I'm looking for a good way to store and use hierarchical (parent/child) data in Django. I've been using django-mptt, but it seems entirely incompatible with my brain - I end up with non-obvious bugs in non-obvious places, mostly when moving things around in the tree: I end up with inconsistent state, where a node and i...
[ "django-treebeard is another option. It has great documentation. I believe it meets all of your above requirements and includes some functions for checking the tree for problems and fixing those problems in the tree.\nNode.find_problems() https://tabo.pe/projects/django-treebeard/docs/1.60/api.html#treebeard.models...
[ 4 ]
[]
[]
[ "django", "django_mptt", "mptt", "python", "tree" ]
stackoverflow_0002699881_django_django_mptt_mptt_python_tree.txt
Q: How to suppress error messages in rpy2 The following code does not work. It seems that the R warning message raises a python error. # enable use of python objects in rpy2 import rpy2.robjects.numpy2ri import numpy as np from rpy2.robjects import r # create an example array a = np.array([[5,2,5],[3,7,8]]) # this...
How to suppress error messages in rpy2
The following code does not work. It seems that the R warning message raises a python error. # enable use of python objects in rpy2 import rpy2.robjects.numpy2ri import numpy as np from rpy2.robjects import r # create an example array a = np.array([[5,2,5],[3,7,8]]) # this line leads to a warning message, which in t...
[ "Put a print statement right before the error:\nprint(r)\nresult = r['chisq.test'](a)\n\nThe error message TypeError: 'module' object is unsubscriptable is claiming that r is referencing a module. When you run the script with the print statement, you'll see something like\n<module 'rpy2' from '/usr/lib/python2.6/di...
[ 1 ]
[]
[]
[ "numpy", "python", "rpy2" ]
stackoverflow_0002700051_numpy_python_rpy2.txt
Q: Using Sphinx to create context-sensitive help files in HTML I am currently using AsciiDoc for documenting my software projects because it supports PDF and HTML help generation. I am currently running it through Cygwin so that the a2x toolchain functions properly. This works well for me but is a pain to setup on ot...
Using Sphinx to create context-sensitive help files in HTML
I am currently using AsciiDoc for documenting my software projects because it supports PDF and HTML help generation. I am currently running it through Cygwin so that the a2x toolchain functions properly. This works well for me but is a pain to setup on other Windows computers. I have been looking for alternative method...
[ "I do not know about AcsiiDoc much, but in Sphinx you can reference arbitrary locations by placing anchors where you need them. See :ref: role.\n" ]
[ 2 ]
[]
[]
[ "asciidoc", "python", "python_sphinx" ]
stackoverflow_0002690732_asciidoc_python_python_sphinx.txt
Q: Installing python2.6 and assorted libraries on DreamHost I managed to install python2.6 on DreamHost following this guide. I also tried to easy_install "lxml" but it fails horribly. Anyone ever accomplished this? TIA A: You should try http://wiki.dreamhost.com/Django and http://wiki.dreamhost.com/Python#Building...
Installing python2.6 and assorted libraries on DreamHost
I managed to install python2.6 on DreamHost following this guide. I also tried to easy_install "lxml" but it fails horribly. Anyone ever accomplished this? TIA
[ "You should try http://wiki.dreamhost.com/Django and http://wiki.dreamhost.com/Python#Building_a_custom_version_of_Python - it contains the most up to date info.\n" ]
[ 0 ]
[]
[]
[ "dreamhost", "lxml", "python" ]
stackoverflow_0002694944_dreamhost_lxml_python.txt
Q: Python: need to get energies of charge pairs I am new to python. I have to make a program for a project that takes a PDB format file as input and returns a list of all the intra-chain and inter-chain charge pairs and their energies (using coulomb’s law assuming a dielectric constant of () of 40.0). For simplici...
Python: need to get energies of charge pairs
I am new to python. I have to make a program for a project that takes a PDB format file as input and returns a list of all the intra-chain and inter-chain charge pairs and their energies (using coulomb’s law assuming a dielectric constant of () of 40.0). For simplicity, the charged residues for this program are just...
[ "Where exactly is your problem? Your description is much too general.\nThe general idea is as follows:\n\nLoad the PDB file and parse each line.\nThat will give you a list of atoms and their (x, y, z) positions.\nIterate over the list in a nested loop to compare each atom with each other.\nCompute the distance of t...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002700236_python.txt
Q: Bipartite matching in Python Does anybody know any module in Python that computes the best bipartite matching? I have tried the following two: munkres hungarian However, in my case, I have to deal with non-complete graph (i.e., there might not be an edge between two nodes), and therefore, there might not be a ...
Bipartite matching in Python
Does anybody know any module in Python that computes the best bipartite matching? I have tried the following two: munkres hungarian However, in my case, I have to deal with non-complete graph (i.e., there might not be an edge between two nodes), and therefore, there might not be a match if the node has no edge. The...
[ "Set cost to infinity or a large value for an edge that does not exist. You can then tell by the result whether an invalid edge was used.\n" ]
[ 5 ]
[]
[]
[ "bipartite", "graph", "python" ]
stackoverflow_0002700847_bipartite_graph_python.txt
Q: Regular Expression Question I'm trying to use regular expression to extract the comments in the heading of a file. For example, the source code may look like: //This is an example file. //Please help me. #include "test.h" int main() //main function { ... } What I want to extract from the code are the first two...
Regular Expression Question
I'm trying to use regular expression to extract the comments in the heading of a file. For example, the source code may look like: //This is an example file. //Please help me. #include "test.h" int main() //main function { ... } What I want to extract from the code are the first two lines, i.e. //This is an example...
[ "Why use regex?\n>>> f = file('/tmp/source')\n>>> for line in f.readlines():\n... if not line.startswith('//'):\n... break\n... print line\n... \n\n", ">>> code=\"\"\"//This is an example file.\n... //Please help me.\n...\n... #include \"test.h\"\n... int main() //main function\n... {\n... ...\n... ...
[ 5, 2, 1, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0002699417_python_regex_string.txt
Q: Endless problems with a very simple python subprocess.Popen task I'd like python to send around a half-million integers in the range 0-255 each to an executable written in C++. This executable will then respond with a few thousand integers. Each on one line. This seems like it should be very simple to do with subp...
Endless problems with a very simple python subprocess.Popen task
I'd like python to send around a half-million integers in the range 0-255 each to an executable written in C++. This executable will then respond with a few thousand integers. Each on one line. This seems like it should be very simple to do with subprocess but i've had endless troubles. Right now im testing with code: ...
[ "This works perfectly for me:\n#include <iostream>\n\nint main()\n{\n int num;\n std::cin >> num;\n\n char* data = new char[num];\n for (int i = 0; i < num; ++i)\n std::cin >> data[i];\n\n // test output / spit it back out\n for (int i = 0; i < num; ++i)\n std::cout << data[i] << std...
[ 1, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0002701364_python_subprocess.txt
Q: Python re.IGNORECASE being dynamic I'd like to do something like this: re.findall(r"(?:(?:\A|\W)" + 'Hello' + r"(?:\Z|\W))", 'hello world',re.I) And have re.I be dynamic, so I can do case-sensitive or insensitive comparisons on the fly. This works but is undocumented: re.findall(r"(?:(?:\A|\W)" + 'Hello' + r"(?:...
Python re.IGNORECASE being dynamic
I'd like to do something like this: re.findall(r"(?:(?:\A|\W)" + 'Hello' + r"(?:\Z|\W))", 'hello world',re.I) And have re.I be dynamic, so I can do case-sensitive or insensitive comparisons on the fly. This works but is undocumented: re.findall(r"(?:(?:\A|\W)" + 'Hello' + r"(?:\Z|\W))", 'hello world',1) To set it to...
[ "To get the default behavior, you can use 0 for the flags parameter. You should not use 1, as it will set the undocumented re.TEMPLATE flag, which disables backtracking.\nSo you can use:\nflags = 0 if case_sensitive else re.I\nre.findall(r'pattern', s, flags)\n\nThe flags parameter is actually a combination of flag...
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002701844_python_regex.txt
Q: Fast iterating over first n items of an iterable (not a list) in python I'm looking for a pythonic way of iterating over first n items of an iterable (upd: not a list in a common case, as for lists things are trivial), and it's quite important to do this as fast as possible. This is how I do it now: count = 0 for ...
Fast iterating over first n items of an iterable (not a list) in python
I'm looking for a pythonic way of iterating over first n items of an iterable (upd: not a list in a common case, as for lists things are trivial), and it's quite important to do this as fast as possible. This is how I do it now: count = 0 for item in iterable: do_something(item) count += 1 if count >= n: break Does...
[ "for item in itertools.islice(iterable, n): is the most obvious, easy way to do it. It works for arbitrary iterables and is O(n), like would be any sane solution.\nIt's conceivable that another solution could have better performance; we wouldn't know without timing. I wouldn't recommend bothering with timing unless...
[ 16, 6, 2, 2, 1 ]
[]
[]
[ "generator", "iterator", "performance", "python" ]
stackoverflow_0002702158_generator_iterator_performance_python.txt
Q: 'int' object is not callable I'm trying to define a simply Fraction class And I'm getting this error: python fraction.py Traceback (most recent call last): File "fraction.py", line 20, in <module> f.numerator(2) TypeError: 'int' object is not callable The code follows: class Fraction(object): def __init_...
'int' object is not callable
I'm trying to define a simply Fraction class And I'm getting this error: python fraction.py Traceback (most recent call last): File "fraction.py", line 20, in <module> f.numerator(2) TypeError: 'int' object is not callable The code follows: class Fraction(object): def __init__( self, n=0, d=0 ): self....
[ "You're using numerator as both a method name (def numerator(...)) and member variable name (self.numerator = n). Use set_numerator and set_denominator for the method names and it will work.\nBy the way, Python 2.6 has a built-in fraction class.\n", "You can't overload the name numerator to refer to both the memb...
[ 18, 8, 7 ]
[]
[]
[ "python" ]
stackoverflow_0002702344_python.txt
Q: Generating Mouse-Keyboard combination events in python I want to be able to do a combination of keypresses and mouseclicks simultaneously, as in for example Control+LeftClick At the moment I am able to do Control and then a left click with the following code: import win32com, win32api, win32con def CopyBox( x, y):...
Generating Mouse-Keyboard combination events in python
I want to be able to do a combination of keypresses and mouseclicks simultaneously, as in for example Control+LeftClick At the moment I am able to do Control and then a left click with the following code: import win32com, win32api, win32con def CopyBox( x, y): time.sleep(.2) wsh = win32com.client.Dispatch("WScr...
[ "to press control:\nwin32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0)\n\nto release it:\nwin32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0)\n\nso your code will look like this:\nimport win32api, win32con\ndef CopyBox(x, y):\n t...
[ 3 ]
[]
[]
[ "combinations", "keyboard_hook", "mouseevent", "python" ]
stackoverflow_0002702617_combinations_keyboard_hook_mouseevent_python.txt
Q: best way to find out type I have a dict val_dict - {'val1': 'abcd', 'val': '1234', 'val3': '1234.00', 'val4': '1abcd 2gfff'} All the values to my keys are string. So my question is how to find out type for my values in the dict. I mean if i say`int(val_dict['val1']) will give me error. Basically what I am trying ...
best way to find out type
I have a dict val_dict - {'val1': 'abcd', 'val': '1234', 'val3': '1234.00', 'val4': '1abcd 2gfff'} All the values to my keys are string. So my question is how to find out type for my values in the dict. I mean if i say`int(val_dict['val1']) will give me error. Basically what I am trying to do is find out if the string...
[ "Maybe this:\nis_int = True\ntry:\n as_int = int (val_dict['val1'])\nexcept ValueError:\n is_int = False\n as_float = float (val_dict['val1'])\n\nif is_int:\n ...\nelse:\n ...\n\nYou can get rid of is_int, but then there will be a lot of code (all float value handling) in try...except and I'd feel un...
[ 3, 2, 0 ]
[ "A simple solution, if you don't have too many formats, could involve checking the format of each value.\ndef intlike(value):\n return value.isdigit()\ndef floatlike(value):\n import re\n return re.match(\"^\\d+\\.\\d+$\")\n\nif intlike(val_dict['val1']):\n dosomething(int(val_dict['val1']))\nelif float...
[ -1 ]
[ "python" ]
stackoverflow_0002701426_python.txt
Q: Operations on Python hashes I've got a rather strange problem. For a Distributed Hash Table I need to be able to do some simple math operations on MD5 hashes. These include a sum (numeric sum represented by the hash) and a modulo operation. Now I'm wondering what the best way to implement these operations is. I'm ...
Operations on Python hashes
I've got a rather strange problem. For a Distributed Hash Table I need to be able to do some simple math operations on MD5 hashes. These include a sum (numeric sum represented by the hash) and a modulo operation. Now I'm wondering what the best way to implement these operations is. I'm using hashlib to calculate the ha...
[ "You can use the hexdigest() method to get hexadecimal digits, and then convert them to a number:\n>>> h = hashlib.md5('data')\n>>> int(h.hexdigest(), 16)\n188041611063492600696317361555123480284L\n\nIf you already have the output of digest(), you can convert it to hexadecimal digits:\n>>> hexDig = ''.join('%02x' %...
[ 35 ]
[]
[]
[ "dht", "hash", "hashlib", "math", "python" ]
stackoverflow_0002702751_dht_hash_hashlib_math_python.txt
Q: Check if the internet cannot be accessed in Python I have an app that makes a HTTP GET request to a particular URL on the internet. But when the network is down (say, no public wifi - or my ISP is down, or some such thing), I get the following traceback at urllib2.urlopen: 70, in get u = urllib2.urlopen(req) ...
Check if the internet cannot be accessed in Python
I have an app that makes a HTTP GET request to a particular URL on the internet. But when the network is down (say, no public wifi - or my ISP is down, or some such thing), I get the following traceback at urllib2.urlopen: 70, in get u = urllib2.urlopen(req) File "/Library/Frameworks/Python.framework/Versions/2.6...
[ "You should wrap the request in a try/except statement so that you catch the fault and then let them know.\ntry:\n u = urllib2.urlopen(req)\nexcept HTTPError as e:\n #inform them of the specific error here (based off the error code)\nexcept URLError as e:\n #inform them of the specific error here\nexcept Exce...
[ 8, 1, 1 ]
[]
[]
[ "exception", "networking", "python", "urllib2" ]
stackoverflow_0002702802_exception_networking_python_urllib2.txt
Q: Intelligent search and generation of Java code, preferrably using Python? Basically, I do lots of one-off code generation, large-scale refactorings, etc. etc. in Java. My tool language of choice is Python, but I'll take whatever solutions you can offer. Here is a simplified illustration of what I would like, in a...
Intelligent search and generation of Java code, preferrably using Python?
Basically, I do lots of one-off code generation, large-scale refactorings, etc. etc. in Java. My tool language of choice is Python, but I'll take whatever solutions you can offer. Here is a simplified illustration of what I would like, in a pseudocode Generating an implementation for an interface search within my proj...
[ "First, I am not aware of any tool or libraries implemented in Python that specifically designed for refactoring Java code, and a Google search did not give me any leads.\nSecond, I would posit that writing such a decent tool or library for refactoring Java in Python would be a large task. You would have to impleme...
[ 2, 0, 0 ]
[]
[]
[ "code_generation", "java", "parsing", "python" ]
stackoverflow_0002702315_code_generation_java_parsing_python.txt
Q: How do I add a method with a decorator to a class in python? How do I add a method with a decorator to a class? I tried def add_decorator( cls ): @dec def update(self): pass cls.update = update usage add_decorator( MyClass ) MyClass.update() but MyClass.update does not have the decorator...
How do I add a method with a decorator to a class in python?
How do I add a method with a decorator to a class? I tried def add_decorator( cls ): @dec def update(self): pass cls.update = update usage add_decorator( MyClass ) MyClass.update() but MyClass.update does not have the decorator @dec did not apply to update I'm trying to use this with orm.reco...
[ "If you want class decorator in python >= 2.6 you can do this\ndef funkyDecorator(cls):\n cls.funky = 1\n\n@funkyDecorator\nclass MyClass(object):\n pass\n\nor in python 2.5\nMyClass = funkyDecorator(MyClass)\n\nBut looks like you are interested in method decorator, for which you can do this\ndef logDecorator...
[ 7, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002703182_decorator_python.txt
Q: PyFacebook with Pylons I'd like to implement PyFacebook in my Python + Pylons application. Where should I include the package? What's the cleanest way to import it? What directory should I put the files in? Thanks! A: Most of your libraries are on your pythonpath, which mostly is lib/site-packages. You shoul...
PyFacebook with Pylons
I'd like to implement PyFacebook in my Python + Pylons application. Where should I include the package? What's the cleanest way to import it? What directory should I put the files in? Thanks!
[ "Most of your libraries are on your pythonpath, which mostly is lib/site-packages. You should just install those and most installers will make sure they're on your python-path. Then you should be able to import them normally.\n" ]
[ 1 ]
[]
[]
[ "facebook", "pyfacebook", "pylons", "python" ]
stackoverflow_0002703540_facebook_pyfacebook_pylons_python.txt
Q: Gtk: How can I get a part of a file in a textview with scrollbars relating to the full file I'm trying to make a very large file editor (where the editor only stores a part of the buffer in memory at a time), but I'm stuck while building my textview object. Basically- I know that I have to be able to update the t...
Gtk: How can I get a part of a file in a textview with scrollbars relating to the full file
I'm trying to make a very large file editor (where the editor only stores a part of the buffer in memory at a time), but I'm stuck while building my textview object. Basically- I know that I have to be able to update the text view buffer dynamically, and I don't know hot to get the scrollbars to relate to the full fil...
[ "You probably should create your own Gtk.TextBuffer implementation, as the default one relies on storing whole buffer in memory.\n", "I agree with el.pescado's answer, but you could also try to fake it. Count the number of lines in the file you're editing. Put one screenful of text in the buffer and fill the rest...
[ 1, 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002698533_gtk_pygtk_python.txt
Q: What is the incoming email address used on google-app-engine? I'm reading this article : http://code.google.com/intl/zh-CN/appengine/docs/python/mail/receivingmail.html I'd like to know, is this the right article to read to deal with mail from others sent to me ? My Gmail is zjm1126@gmail.com, so when someone send...
What is the incoming email address used on google-app-engine?
I'm reading this article : http://code.google.com/intl/zh-CN/appengine/docs/python/mail/receivingmail.html I'd like to know, is this the right article to read to deal with mail from others sent to me ? My Gmail is zjm1126@gmail.com, so when someone sends email to zjm1126@gmail.com, can I do something automatically with...
[ "\nis article used to deal with mail from others send to me ?\n\nYes\n\nand my gmail is zjm1126@gmail.com , so someone send email to zjm1126@gmail.com,i can do something automatically use incoming mail ,yes ?\n\nNo (unless you configure GMail to forward it to the address the article tells you to use)\n\nwhere to se...
[ 1 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0002703709_email_google_app_engine_python.txt
Q: How to give color to your code in open-office-writer? I have code blocks written in Open Office Write and want colorize it. How can I do this? EDIT: When I copy syntax-highlighted code back to open office writer it becomes black again. How can I change this? A: I think you need to take a look at coooder plugin f...
How to give color to your code in open-office-writer?
I have code blocks written in Open Office Write and want colorize it. How can I do this? EDIT: When I copy syntax-highlighted code back to open office writer it becomes black again. How can I change this?
[ "I think you need to take a look at coooder plugin for LibreOffice(OpenOffice).\n", "You could try pygments.\n", "I know this works for MS Word, but it may also work for Open Office.\nhttp://www.planetb.ca/2008/11/syntax-highlight-code-in-word-documents/\n" ]
[ 2, 1, 0 ]
[]
[]
[ "colors", "openoffice_writer", "python", "syntax_highlighting" ]
stackoverflow_0002703675_colors_openoffice_writer_python_syntax_highlighting.txt
Q: Problem building PyGTK on CentOS I am trying to build PyGTK on CentOS for a non-standard Python (2.6, vs the out-of-the-box 2.4). It requires that I first build pygobject. pygobject-2.18.0 fails at the configure step. The error messages is as follows: checking for GLIB - version >= 2.14.0... no *** Could not run G...
Problem building PyGTK on CentOS
I am trying to build PyGTK on CentOS for a non-standard Python (2.6, vs the out-of-the-box 2.4). It requires that I first build pygobject. pygobject-2.18.0 fails at the configure step. The error messages is as follows: checking for GLIB - version >= 2.14.0... no *** Could not run GLIB test program, checking why... *** ...
[ "Looks like your glib version is not up to date.\nIn gentoo, following versions apply in PyGTK 2.16.0:\n\nglib 2.8.0\npygobject-2.16.1\npycairo 2.0.1\n\n" ]
[ 4 ]
[]
[]
[ "pygobject", "pygtk", "python" ]
stackoverflow_0002642238_pygobject_pygtk_python.txt
Q: Building proper link with spaces I have the following code in Python: linkHTML = "<a href=\"page?q=%s\">click here</a>" % strLink The problem is that when strLink has spaces in it the link shows up as <a href="page?q=with space">click here</a> I can use strLink.replace(" ","+") But I am sure there are other char...
Building proper link with spaces
I have the following code in Python: linkHTML = "<a href=\"page?q=%s\">click here</a>" % strLink The problem is that when strLink has spaces in it the link shows up as <a href="page?q=with space">click here</a> I can use strLink.replace(" ","+") But I am sure there are other characters which can cause errors. I tried...
[ "Make sure you use the urllib.quote_plus(string[, safe]) to replace spaces with plus sign.\nurllib.quote_plus(string[, safe])\n\n\nLike quote(), but also replaces spaces\n by plus signs, as required for quoting\n HTML form values when building up a\n query string to go into a URL. Plus\n signs in the original s...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002703638_python.txt
Q: Paver 0.8.1 compatibility with python 2.6 Does anyone manage to bootstrap its development area using paver with python 2.6 ? I have install python 2.6, install paver with easy_install-2.6, everything looks fine. But when I try to launch the bootstrap method it raises an urllib2.HTTPError (: HTTP Error 404: Not Fou...
Paver 0.8.1 compatibility with python 2.6
Does anyone manage to bootstrap its development area using paver with python 2.6 ? I have install python 2.6, install paver with easy_install-2.6, everything looks fine. But when I try to launch the bootstrap method it raises an urllib2.HTTPError (: HTTP Error 404: Not Found) while trying to download http://pypi.python...
[ "You should try newer version. =) http://www.blueskyonmars.com/projects/paver/\n" ]
[ 2 ]
[]
[]
[ "bootstrapper", "build_environment", "python" ]
stackoverflow_0000178300_bootstrapper_build_environment_python.txt
Q: Multiply with find and replace Can regular expressions be used to perform arithmetic? Such as find all numbers in a file and multiply them by a scalar value. A: You can achieve this using re.sub() with a callback: import re def repl(matchobj): i = int(matchobj.group(0)) return str(i * 2) print re.sub(r'\d...
Multiply with find and replace
Can regular expressions be used to perform arithmetic? Such as find all numbers in a file and multiply them by a scalar value.
[ "You can achieve this using re.sub() with a callback:\nimport re\n\ndef repl(matchobj):\n i = int(matchobj.group(0))\n return str(i * 2)\n\nprint re.sub(r'\\d+', repl, '1 a20 300c')\n\nOutput:\n2 a40 600c\n\nFrom the docs:\n\nre.sub(pattern, repl, string[,\n count])\nIf repl is a function, it is called\n for ev...
[ 8, 4, 2, 1, 1 ]
[ "Ayman Hourieh's answer can be reduced to be a little bit simpler, and imo more readable:\n>>> import re\n>>> repl = lambda m: str(int(m.group(0)) * 2)\n>>> print re.sub(r'\\d+', repl, '1 a20 300c')\n2 a40 600c\n\n" ]
[ -1 ]
[ "python", "regex", "sed" ]
stackoverflow_0002701063_python_regex_sed.txt
Q: A lightweight protocol for Python and Erlang interaction What protocol preferred to use for interaction between Python-code and Erlang-code over Internet? ASN.1 would be ideally for me, but its implementation in Python cannot generate encoder/decoder out from notation. A: Did you check Google's protocol buffers?...
A lightweight protocol for Python and Erlang interaction
What protocol preferred to use for interaction between Python-code and Erlang-code over Internet? ASN.1 would be ideally for me, but its implementation in Python cannot generate encoder/decoder out from notation.
[ "Did you check Google's protocol buffers?\nIt is very easy to use and there is an Erlang implementation available\n", "Well, you could use JSON or BERT.\nJSON is easily reable by humans, as it is ASCII only. To send binary data, you need to encode them (e.g. with base64).\nAnother solution would be using BERT. BE...
[ 5, 4, 4 ]
[]
[]
[ "asn.1", "erlang", "python" ]
stackoverflow_0002701397_asn.1_erlang_python.txt
Q: What's the easiest way to get my facebook status and photos using python? I just want to import my facebook status and photos to my personal django website but all the examples and documentation i can find are for developing facebook applications. A simple rss feed would be enough but it doesnt seem to exist in fa...
What's the easiest way to get my facebook status and photos using python?
I just want to import my facebook status and photos to my personal django website but all the examples and documentation i can find are for developing facebook applications. A simple rss feed would be enough but it doesnt seem to exist in facebook. Do i really have to create a full facebook app to do this?
[ "A simple facebook application isn't that hard ... excluding trying to decipher the soup on developers.facebook.com.\nThe \"problem\" is that you need to get an application key, application secret, and sometimes a session key in order to access the web services. Unless someone is sharing a service to do just that (...
[ 2, 0, 0 ]
[]
[]
[ "django", "facebook", "pyfacebook", "python" ]
stackoverflow_0002582627_django_facebook_pyfacebook_python.txt
Q: What is the easiest, most concise way to make selected attributes in an instance be readonly? In Python, I want to make selected instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the inst...
What is the easiest, most concise way to make selected attributes in an instance be readonly?
In Python, I want to make selected instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below.....
[ "You should use the @property decorator.\n>>> class a(object):\n... def __init__(self, x):\n... self.x = x\n... @property\n... def xval(self):\n... return self.x\n... \n>>> b = a(5)\n>>> b.xval\n5\n>>> b.xval = 6\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in...
[ 7, 2, 2, 1, 0, 0 ]
[]
[]
[ "attributes", "python", "readonly" ]
stackoverflow_0000125034_attributes_python_readonly.txt
Q: Intercept method calls in Python I'm implementing a RESTful web service in python and would like to add some QOS logging functionality by intercepting function calls and logging their execution time and so on. Basically i thought of a class from which all other services can inherit, that automatically overrides th...
Intercept method calls in Python
I'm implementing a RESTful web service in python and would like to add some QOS logging functionality by intercepting function calls and logging their execution time and so on. Basically i thought of a class from which all other services can inherit, that automatically overrides the default method implementations and w...
[ "Something like this? This implictly adds a decorator to your method (you can also make an explicit decorator based on this if you prefer that):\nclass Foo(object):\n def __getattribute__(self,name):\n attr = object.__getattribute__(self, name)\n if hasattr(attr, '__call__'):\n def newfu...
[ 73, 5 ]
[]
[]
[ "python" ]
stackoverflow_0002704434_python.txt
Q: Why is '\x' invalid in Python? I was experimenting with '\' characters, using '\a\b\c...' just to enumerate for myself which characters Python interprets as control characters, and to what. Here's what I found: \a - BELL \b - BACKSPACE \f - FORMFEED \n - LINEFEED \r - RETURN \t - TAB \v - VERTICAL TAB Most of th...
Why is '\x' invalid in Python?
I was experimenting with '\' characters, using '\a\b\c...' just to enumerate for myself which characters Python interprets as control characters, and to what. Here's what I found: \a - BELL \b - BACKSPACE \f - FORMFEED \n - LINEFEED \r - RETURN \t - TAB \v - VERTICAL TAB Most of the other characters I tried, '\g', '\...
[ "There is a table listing all the escape codes and their meanings in the documentation.\n\nEscape Sequence Meaning Notes\n\\xhh Character with hex value hh (4,5)\n\n\nNotes:\n4. Unlike in Standard C, exactly two hex digits are required.\n 5. In a string literal, hexadecim...
[ 21, 6, 6, 4, 1 ]
[]
[]
[ "ascii", "backslash", "control_characters", "python", "string" ]
stackoverflow_0002704654_ascii_backslash_control_characters_python_string.txt
Q: List comprehension, map, and numpy.vectorize performance I have a function foo(i) that takes an integer and takes a significant amount of time to execute. Will there be a significant performance difference between any of the following ways of initializing a: a = [foo(i) for i in xrange(100)] a = map(foo, range(1...
List comprehension, map, and numpy.vectorize performance
I have a function foo(i) that takes an integer and takes a significant amount of time to execute. Will there be a significant performance difference between any of the following ways of initializing a: a = [foo(i) for i in xrange(100)] a = map(foo, range(100)) vfoo = numpy.vectorize(foo) a = vfoo(range(100)) (I don...
[ "\nWhy are you optimizing this? Have you written working, tested code, then examined your algorithm profiled your code and found that optimizing this will have an effect? Are you doing this in a deep inner loop where you found you are spending your time? If not, don't bother.\nYou'll only know which works fastest f...
[ 24, 13, 7, 4 ]
[]
[]
[ "list_comprehension", "numpy", "performance", "python" ]
stackoverflow_0002703310_list_comprehension_numpy_performance_python.txt
Q: Can I create threads in App Enging using Python? Can this code create threads in Google App Engine. If no, why not? class LogText(db.Model): content = db.StringProperty(multiline=True) class MyThread(threading.Thread): def __init__(self,threadname): threading.Thread.__init__(self, name=thre...
Can I create threads in App Enging using Python?
Can this code create threads in Google App Engine. If no, why not? class LogText(db.Model): content = db.StringProperty(multiline=True) class MyThread(threading.Thread): def __init__(self,threadname): threading.Thread.__init__(self, name=threadname) def run(self,request): log=LogText...
[ "App Engine does not allow you to create new threads, probably because primarily the goal of App Engine is to build simple request-response apps, and threads are usually not considered \"simple\".\nManaging threads for an app to prevent abuse (accidental or otherwise) would be difficult, or impossible, for App Engi...
[ 2 ]
[]
[]
[ "google_app_engine", "multithreading", "python" ]
stackoverflow_0002702888_google_app_engine_multithreading_python.txt
Q: Api to analyse complex graph I am looking for an API (preferably in python) that could be used to analyze complex networks. Basically I want to find things like: Average shortest path, Degree distribution Giant Component local clustering coefficient, global clustering coefficient etc.. Thanks A: I would suggest ...
Api to analyse complex graph
I am looking for an API (preferably in python) that could be used to analyze complex networks. Basically I want to find things like: Average shortest path, Degree distribution Giant Component local clustering coefficient, global clustering coefficient etc.. Thanks
[ "I would suggest Networkx and PyGraphViz. I've used them for a similar (but not as complex) graphing project in python and I love it.\n", "The boost graph library has Python bindings.\n", "I've used igraph on Linux. It started to grind on 64k nodes but that graph was becoming unwieldy any way. \nNot sure about ...
[ 3, 0, 0 ]
[]
[]
[ "api", "graph", "python", "social_networking" ]
stackoverflow_0002701101_api_graph_python_social_networking.txt
Q: Why isn't the regular expression's "non-capturing" group working? In the snippet below, the non-capturing group "(?:aaa)" should be ignored in the matching result, The result should be "_bbb" only. However, I get "aaa_bbb" in the matching result; only when I specify group(2) does it show "_bbb". >>> import re >>> ...
Why isn't the regular expression's "non-capturing" group working?
In the snippet below, the non-capturing group "(?:aaa)" should be ignored in the matching result, The result should be "_bbb" only. However, I get "aaa_bbb" in the matching result; only when I specify group(2) does it show "_bbb". >>> import re >>> s = "aaa_bbb" >>> print(re.match(r"(?:aaa)(_bbb)", s).group()) aaa_bbb...
[ "I think you're misunderstanding the concept of a \"non-capturing group\". The text matched by a non-capturing group still becomes part of the overall regex match.\nBoth the regex (?:aaa)(_bbb) and the regex (aaa)(_bbb) return aaa_bbb as the overall match. The difference is that the first regex has one capturing g...
[ 129, 61, 3, 3, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002703029_python_regex.txt
Q: is the sender of google-app-engine allow my own gmail my gmail is zjm1126@gmail.com i can only use zjm1126@gmail.com in the sender=".." ,yes ?? from google.appengine.api import mail message = mail.EmailMessage(sender="hahahaha@gmail.com", subject="Your account has been approved...
is the sender of google-app-engine allow my own gmail
my gmail is zjm1126@gmail.com i can only use zjm1126@gmail.com in the sender=".." ,yes ?? from google.appengine.api import mail message = mail.EmailMessage(sender="hahahaha@gmail.com", subject="Your account has been approved") message.to = "zjm1126@qq.com" message.body = ""...
[ "There are two kinds of FROM addresses allowed by GAE's e-mail API:\n\nThe currently authenticated Google user of your app (if your app uses Google auth and someone's logged in)\nThe Google address of any administrator of the app engine app (e.g. you, as the owner)\n\n\"If you want to send email on behalf of the ap...
[ 3 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0002705816_email_google_app_engine_python.txt
Q: Code Coverage and Unit Testing of Python Code I have already visited Preferred Python unit-testing framework. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across coverage.py. Is there any better option? An interesting option for ...
Code Coverage and Unit Testing of Python Code
I have already visited Preferred Python unit-testing framework. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across coverage.py. Is there any better option? An interesting option for me is to integrate cpython, unit testing of Python ...
[ "We use this Django coverage integration, but instead of using the default coverage.py reporting, we generate some simple HTML: \nColorize Python source using the built-in tokenizer.\n", "PyDev seems to allow code coverage from within Eclipse. \nI've yet to find how to integrate that with my own (rather complex) ...
[ 5, 4, 2, 2, 1, 0 ]
[]
[]
[ "code_coverage", "python", "unit_testing", "visual_studio_2008" ]
stackoverflow_0000272188_code_coverage_python_unit_testing_visual_studio_2008.txt
Q: Decorator Module Standard I was wondering if it's frowned upon to use the decorator module that comes with python. Should I be creating decorators using the original means or is it considered okay practice to use the module? A: the decorator module in pypi is a third party module from Michele Simionato. It does ...
Decorator Module Standard
I was wondering if it's frowned upon to use the decorator module that comes with python. Should I be creating decorators using the original means or is it considered okay practice to use the module?
[ "the decorator module in pypi is a third party module from Michele Simionato. It does not belong to the python standard library.\nIn most cases you dont need this module to work with decorators.\nStill it provides you with some useful tools that can simplify some uses of decorators. In any case it is a nice module ...
[ 3, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002701772_decorator_python.txt
Q: High memory usage only when multiprocessing I am trying to use python's multiprocessing library to hopefully gain some performance. Specifically I am using its map function. Now, for some reason when I swap it out with its single processed counterpart I don't get high memory usage. But using the multiprocessing ve...
High memory usage only when multiprocessing
I am trying to use python's multiprocessing library to hopefully gain some performance. Specifically I am using its map function. Now, for some reason when I swap it out with its single processed counterpart I don't get high memory usage. But using the multiprocessing version of map causes my memory to go through the r...
[ "You realize that multiprocessing does not use threads, yes? I say this because you mention a \"single threaded counterpart\".\nAre you sending a lot of data through multiprocessing's map? A likely cause is the serialization multiprocessing has to do in many cases. multiprocessing uses pickle, which does typically ...
[ 4 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0002705968_multiprocessing_python.txt
Q: How to pick a chunksize for python multiprocessing with large datasets I am attempting to to use python to gain some performance on a task that can be highly parallelized using http://docs.python.org/library/multiprocessing. When looking at their library they say to use chunk size for very long iterables. Now, my ...
How to pick a chunksize for python multiprocessing with large datasets
I am attempting to to use python to gain some performance on a task that can be highly parallelized using http://docs.python.org/library/multiprocessing. When looking at their library they say to use chunk size for very long iterables. Now, my iterable is not long, one of the dicts that it contains is huge: ~100000 ent...
[ "The only way to handle this single large item in multiple workers at once is by splitting it up. multiprocessing works by dividing up the work in units, but the smallest unit you can feed it is one object -- it can't know how to split up a single object in a way that's sensible. You have to do it yourself, instead...
[ 3 ]
[]
[]
[ "large_data_volumes", "multiprocessing", "python" ]
stackoverflow_0002705953_large_data_volumes_multiprocessing_python.txt
Q: python operation not permitted (graphtecprint) I'm running a python program. When it get's to these lines: f = open("/dev/bus/usb/007/005", "r") x = fcntl.ioctl(f.fileno(), 0x84005001, '\x00' * 256) It fails saying: IOError: [Errno 1] Operation not permitted What could be causing this problem? A: file system p...
python operation not permitted (graphtecprint)
I'm running a python program. When it get's to these lines: f = open("/dev/bus/usb/007/005", "r") x = fcntl.ioctl(f.fileno(), 0x84005001, '\x00' * 256) It fails saying: IOError: [Errno 1] Operation not permitted What could be causing this problem?
[ "file system permissions?\nwhat does ls -l /dev/bus/usb/007/005 say?\ndoes cat /dev/bus/usb/007/005 work or does it report the same error?\n", "The third argument to fcntl.ioctl, as documented here, should be either a 1024-byte string (not just 256), or, better, a possibly even-larger writeable buffer -- the unde...
[ 1, 0 ]
[]
[]
[ "file_io", "linux", "python", "usb" ]
stackoverflow_0002705974_file_io_linux_python_usb.txt
Q: Using arrays with other arrays in Python Trying to find an efficient way to extract all instances of items in an array out of another. For example array1 = ["abc", "def", "ghi", "jkl"] array2 = ["abc", "ghi", "456", "789"] Array 1 is an array of items that need to be extracted out of array 2. Thus, array 2 shou...
Using arrays with other arrays in Python
Trying to find an efficient way to extract all instances of items in an array out of another. For example array1 = ["abc", "def", "ghi", "jkl"] array2 = ["abc", "ghi", "456", "789"] Array 1 is an array of items that need to be extracted out of array 2. Thus, array 2 should be modified to ["456", "789"] I know how to...
[ "These are lists, not arrays. (The word \"array\" means different things to different people, but in python the objects call themselves lists, and that's that; there are other modules that provide objects that call themselves arrays, such as array and numpy)\nTo answer your question, the easiest way is to not modif...
[ 6, 3, 0 ]
[]
[]
[ "arrays", "extract", "python" ]
stackoverflow_0002706440_arrays_extract_python.txt
Q: How to import *.pyc file from different version of python? I used python 2.5 and imported a file named "irit.py" from C:\util\Python25\Lib\site-packages directory. This files imports the file "_irit.pyc which is in the same directory. It worked well and did what I wanted. Than, I tried the same thing with python v...
How to import *.pyc file from different version of python?
I used python 2.5 and imported a file named "irit.py" from C:\util\Python25\Lib\site-packages directory. This files imports the file "_irit.pyc which is in the same directory. It worked well and did what I wanted. Than, I tried the same thing with python version 2.6.4. "irit.py" which is in C:\util\Python26\Lib\site-pa...
[ "\"DLL load failed\" can't directly refer to the .pyc, since that's a bytecode file, not a DLL; a DLL would be .pyd on Windows. So presumably that _irit.pyc bytecode file tries to import some .pyd and that .pyd is not available in a 2.6-compatible version in the appropriate directory. Unfortunately it also appear...
[ 5, 1 ]
[]
[]
[ "import", "pyc", "python", "version" ]
stackoverflow_0002705304_import_pyc_python_version.txt
Q: super() in Python 2.x without args Trying to convert super(B, self).method() into a simple nice bubble() call. Did it, see below! Is it possible to get reference to class B in this example? class A(object): pass class B(A): def test(self): test2() class C(B): pass import inspect def test2(): fra...
super() in Python 2.x without args
Trying to convert super(B, self).method() into a simple nice bubble() call. Did it, see below! Is it possible to get reference to class B in this example? class A(object): pass class B(A): def test(self): test2() class C(B): pass import inspect def test2(): frame = inspect.currentframe().f_back c...
[ "Found a shorter way to do super(B, self).test() -> bubble() from below. \n(Works with multiple inheritance, doesn't require arguments, correcly behaves with sub-classes)\nThe solution was to use inspect.getmro(type(back_self)) (where back_self is a self from callee), then iterating it as cls with method_name in cl...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002706623_python.txt
Q: Source for Names to use in web scraping Can anyone suggest a good source of names that I can use to help analyze some tables on web pages. The first column of the tables I am scraping have names alone, names and titles or just titles. The names can be as varied as John Smith to Vikram Saksena. I have been pokin...
Source for Names to use in web scraping
Can anyone suggest a good source of names that I can use to help analyze some tables on web pages. The first column of the tables I am scraping have names alone, names and titles or just titles. The names can be as varied as John Smith to Vikram Saksena. I have been poking around for a compiled list of words that ca...
[ "Download the Febrl project source code.\nIt's data folder contains tables for names (given/middle/surnames/etc). You may have to massage the data for your own needs.\nFor surnames you can check around for U.S. Census data. I don't have the link right now, but know I've used the common U.S. surnames from that sourc...
[ 1 ]
[]
[]
[ "python", "web_scraping" ]
stackoverflow_0002706786_python_web_scraping.txt
Q: I want the actual file name that is returned by a PHP script I am writing a python script that downloads a file given by a URL. Unfortuneatly the URL is in the form of a PHP script i.e. www.website.com/generatefilename.php?file=5233 If you visit the link in a browser, you are prompted to download the actual file a...
I want the actual file name that is returned by a PHP script
I am writing a python script that downloads a file given by a URL. Unfortuneatly the URL is in the form of a PHP script i.e. www.website.com/generatefilename.php?file=5233 If you visit the link in a browser, you are prompted to download the actual file and extension. I need to send this link to the downloader, but I ca...
[ "What you need to do is examine the Content-Disposition header sent by the PHP script. it will look something like:\nContent-Disposition: attachment; filename=theFilenameYouWant\nAs to how you actually examine that header it depends on the python code you're currently using to fetch the URL. If you post some code I...
[ 2, 0 ]
[]
[]
[ "php", "python", "scripting", "url" ]
stackoverflow_0002705856_php_python_scripting_url.txt
Q: how to scrape html generated by javascript using python? I want to scrape the html generated by javascript , just like what you can see in Firebug. UPDATE: I've found this article: http://blog.motane.lu/2009/07/07/downloading-a-pages-content-with-python-and-webkit/ which use PyQt to solve the problem and it work...
how to scrape html generated by javascript using python?
I want to scrape the html generated by javascript , just like what you can see in Firebug. UPDATE: I've found this article: http://blog.motane.lu/2009/07/07/downloading-a-pages-content-with-python-and-webkit/ which use PyQt to solve the problem and it works well for me. BUT another problem occur: I have to login the ...
[ "Have a look at this article which describes using Windmill to do scrape a page after Javascript has been executed by the browser.\n\nThis article will show how to extract the desired information using the same three steps when the web page is not written directly using HTML, but is auto-generated using JavaScript ...
[ 5, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002707108_python.txt
Q: Problems inserting file data into sqlite database using python I'm trying to open an image file in python and add that data to an sqlite table. I created the table using: "CREATE TABLE "images" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "description" VARCHAR, "image" BLOB );" I am trying to add the image...
Problems inserting file data into sqlite database using python
I'm trying to open an image file in python and add that data to an sqlite table. I created the table using: "CREATE TABLE "images" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "description" VARCHAR, "image" BLOB );" I am trying to add the image to the db using: imageFile = open(imageName, 'rb') b = sqlite3.Bina...
[ "It works for me with Python 2.6.4, pysqlite (sqlite3.version) 2.4.1, and a png test image. You have to unpack the tuple.\n>>> import sqlite3 \n>>> conn = sqlite3.connect(\":memory:\") \n>>> targetCursor = conn.cursor() ...
[ 2, 0 ]
[]
[]
[ "blob", "python", "sqlite" ]
stackoverflow_0002707070_blob_python_sqlite.txt
Q: There is a system alert of (13, 'Permission denied'), how to solve that? def upload_file(request, step_id): def handle_uploaded_file (file): current_step = Step.objects.get(pk=step_id) current_project = Project.objects.get(pk=current_step.project.pk) path = "%s/upload/file/%s/%s" % (s...
There is a system alert of (13, 'Permission denied'), how to solve that?
def upload_file(request, step_id): def handle_uploaded_file (file): current_step = Step.objects.get(pk=step_id) current_project = Project.objects.get(pk=current_step.project.pk) path = "%s/upload/file/%s/%s" % (settings.MEDIA_ROOT, current_project.project_no, current_step.name) if ...
[ "Make sure path has the necessary permissions. The user running the python/django process needs to have write permissions. chmod the path to 0777 - this isn't a good mode for production, but it will quickly verify if filesystem permissions are the root of the problem.\n" ]
[ 2 ]
[]
[]
[ "django", "file_upload", "python" ]
stackoverflow_0002707344_django_file_upload_python.txt
Q: Python: x-y-plot with matplotlib I want to plot some data. The first column contains the x-data. But matplotlib doesn't plot this. Where is my mistake? import numpy as np from numpy import cos from scipy import * from pylab import plot, show, ylim, yticks from matplotlib import * from pprint import pprint n1 = 1....
Python: x-y-plot with matplotlib
I want to plot some data. The first column contains the x-data. But matplotlib doesn't plot this. Where is my mistake? import numpy as np from numpy import cos from scipy import * from pylab import plot, show, ylim, yticks from matplotlib import * from pprint import pprint n1 = 1.0 n2 = 1.5 #alpha, beta, intensity da...
[ "You can do this by converting data to a numpy array:\ndata = np.array(data) # insert this new line after your appends\n\npprint(data)\nx = data[:,0] # use the multidimensional slicing notation\ny1 = data[:,2]\ny3 = data[:,3]\nplot(x, y1, x, y3)\n\nA few additional points:\nYou can do the calculation in a more c...
[ 5, 2, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002699353_matplotlib_python.txt
Q: How to slice a list of objects in association of the object attributes I have a list of fixtures.Each fixture has a home club and a away club attribute.I want to slice the list in association of its home club and away club.The sliced list should be of homeclub items and awayclub items. Easier way to implement this...
How to slice a list of objects in association of the object attributes
I have a list of fixtures.Each fixture has a home club and a away club attribute.I want to slice the list in association of its home club and away club.The sliced list should be of homeclub items and awayclub items. Easier way to implement this is to first slice a list of fixtures.Then make a new list of the correspond...
[ "It's not very clear what you're trying to do, but this code will take the first five fixtures, and return a list of tuples, each of which contains a home and an away value of the respective object:\nresult = [(i.home, i.away) for i in fixtures[:5]]\n\nThis will separate the two into two lists:\nhomes = [i.home for...
[ 3, 0, 0 ]
[]
[]
[ "list", "object", "python" ]
stackoverflow_0002707413_list_object_python.txt
Q: What category of combinatorial problems appear on the logic games section of the LSAT? EDIT: See Solving "Who owns the Zebra" programmatically? for a similar class of problem There's a category of logic problem on the LSAT that goes like this: Seven consecutive time slots for a broadcast, numbered in chronologic...
What category of combinatorial problems appear on the logic games section of the LSAT?
EDIT: See Solving "Who owns the Zebra" programmatically? for a similar class of problem There's a category of logic problem on the LSAT that goes like this: Seven consecutive time slots for a broadcast, numbered in chronological order I through 7, will be filled by six song tapes-G, H, L, O, P, S-and exactly one new...
[ "This is easy to solve (a few lines of code) as an integer program. Using a tool like the GNU Linear Programming Kit, you specify your constraints in a declarative manner and let the solver come up with the best solution. Here's an example of a GLPK program.\nYou could code this using a general-purpose programming ...
[ 1, 0 ]
[]
[]
[ "combinations", "combinatorics", "puzzle", "python" ]
stackoverflow_0002707619_combinations_combinatorics_puzzle_python.txt
Q: Text-based one-on-one chat with Flash interface: what to power the backend? I'm building a website where I hook people up so that they can anonymously vent to strangers. You either choose to be a listener, or a talker, and then you get catapulted into a one-on-one chat room. The reason for the app's construction ...
Text-based one-on-one chat with Flash interface: what to power the backend?
I'm building a website where I hook people up so that they can anonymously vent to strangers. You either choose to be a listener, or a talker, and then you get catapulted into a one-on-one chat room. The reason for the app's construction is because you often can't vent to friends, because your deepest vulnerabilities ...
[ "Unless you expect super high load, this is simple enough that it doesn't really matter what you use on the backend: just pick something you're comfortable with. PHP, Python, Ruby, Even a bash script using CGI - your skill level with the language is likely to make more difference that the language features themselv...
[ 3, 2, 1, 1 ]
[]
[]
[ "actionscript", "chat", "flash", "python" ]
stackoverflow_0002691955_actionscript_chat_flash_python.txt
Q: Django ORM and multiprocessing I am using Django ORM in my python script in a decoupled fashion i.e. it's not running in context of a normal Django Project. I am also using the multi processing module. And different process in turn are making queries. The process ran successfully for an hr and exited with this me...
Django ORM and multiprocessing
I am using Django ORM in my python script in a decoupled fashion i.e. it's not running in context of a normal Django Project. I am also using the multi processing module. And different process in turn are making queries. The process ran successfully for an hr and exited with this message "IOError: [Errno 32] Broken p...
[ "It's a little hard to say without more information, but the problem is probably caused by having an open database connection as you spawn new processes, and then trying to use that database connection in the separate processes. Don't re-use database connections from the parent process in multiprocessing workers yo...
[ 0 ]
[]
[]
[ "django", "django_models", "message_queue", "multiprocessing", "python" ]
stackoverflow_0002707811_django_django_models_message_queue_multiprocessing_python.txt
Q: Python. Strange class attributes behavior >>> class Abcd: ... a = '' ... menu = ['a', 'b', 'c'] ... >>> a = Abcd() >>> b = Abcd() >>> a.a = 'a' >>> b.a = 'b' >>> a.a 'a' >>> b.a 'b' It's all correct and each object has own 'a', but... >>> a.menu.pop() 'c' >>> a.menu ['a', 'b'] >>> b.menu ['a', 'b'] How...
Python. Strange class attributes behavior
>>> class Abcd: ... a = '' ... menu = ['a', 'b', 'c'] ... >>> a = Abcd() >>> b = Abcd() >>> a.a = 'a' >>> b.a = 'b' >>> a.a 'a' >>> b.a 'b' It's all correct and each object has own 'a', but... >>> a.menu.pop() 'c' >>> a.menu ['a', 'b'] >>> b.menu ['a', 'b'] How could this happen? And how to use list as clas...
[ "This is because the way you're initializing the menu property is setting all of the instances to point to the same list, as opposed to different lists with the same value.\nInstead, use the __init__ member function of the class to initialize values, thus creating a new list and assigning that list to the property ...
[ 7, 4, 0 ]
[]
[]
[ "attributes", "class", "python" ]
stackoverflow_0002707472_attributes_class_python.txt
Q: Socket: Get user information How can I get information about a user's PC connected to my socket A: a socket is a "virtual" channel established between to electronic devices through a network (a bunch of wires). the only informations available about a remote host are those published on the network. the basic info...
Socket: Get user information
How can I get information about a user's PC connected to my socket
[ "a socket is a \"virtual\" channel established between to electronic devices through a network (a bunch of wires). the only informations available about a remote host are those published on the network.\nthe basic informations are those provided in the TCP/IP headers, namely the remote IP address, the size of the r...
[ 3, 1, 0 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002707599_python_sockets.txt
Q: Python Pari Library? Pari/GP is an excellent library for functions relating to number theory. The problem is that there doesn't seem to be an up to date wrapper for python anywhere around, (pari-python uses an old version of pari) and I'm wondering if anyone knows of some other library/wrapper that is similar to p...
Python Pari Library?
Pari/GP is an excellent library for functions relating to number theory. The problem is that there doesn't seem to be an up to date wrapper for python anywhere around, (pari-python uses an old version of pari) and I'm wondering if anyone knows of some other library/wrapper that is similar to pari or one that uses pari....
[ "Actually, pari-python works with the latest stable release of PARI. And it is very easy to use:\n>>> from pari import *\n>>> fibonacci(100)\n354224848179261915075\n>>> intnum(0,1,lambda x:x**2)\n0.3333333333333333333333333333\n>>> \n\n" ]
[ 5 ]
[]
[]
[ "pari", "python" ]
stackoverflow_0002506087_pari_python.txt
Q: Strange Syntax Parsing Error in Python? Am I missing something here? Why shouldn't the code under the "Broken" section work? I'm using Python 2.6. #!/usr/bin/env python def func(a,b,c): print a,b,c #Working: Example #1: p={'c':3} func(1, b=2, c=3, ) #Working: Example #2: func(1, b=2,...
Strange Syntax Parsing Error in Python?
Am I missing something here? Why shouldn't the code under the "Broken" section work? I'm using Python 2.6. #!/usr/bin/env python def func(a,b,c): print a,b,c #Working: Example #1: p={'c':3} func(1, b=2, c=3, ) #Working: Example #2: func(1, b=2, **p) #Broken: Example #3: func(1, ...
[ "This is the relevant bit from the grammar:\narglist: (argument ',')* (argument [',']\n |'*' test (',' argument)* [',' '**' test] \n |'**' test)\n\nThe first line here allows putting a comma after the last parameter when not using varargs/kwargs (this is why your firs...
[ 9, 5 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0002708614_python_syntax_error.txt
Q: xlwt data garbled I retrieve the data of chinese characters from DB and write the data into excel by xlwt, code as below: ws0.write(0,0, unicode(cell, 'big5')) It is ok under Windows, but when I deloyed it under Linux, the data in excel garbled, Could you help to do with it? A: It would help if you posted the...
xlwt data garbled
I retrieve the data of chinese characters from DB and write the data into excel by xlwt, code as below: ws0.write(0,0, unicode(cell, 'big5')) It is ok under Windows, but when I deloyed it under Linux, the data in excel garbled, Could you help to do with it?
[ "It would help if you posted the code that you actually ran. Assuming that ws0 is a Worksheet object, the correct syntax is ws0.write(row_index, column_index, unicode_text).\nWhat does cell refer to, and how did you extract it from what database?\nWhat does \"the data in excel garbled\" mean? What are you using on ...
[ 0 ]
[]
[]
[ "python", "xlwt" ]
stackoverflow_0002708530_python_xlwt.txt
Q: Python script repeated auto start up I am designing a python web app, where people can have an email sent to them on a particular day. So a user puts in his emai and date in a form and it gets stored in my database. My script would then search through the database looking for all records of todays date, retrive th...
Python script repeated auto start up
I am designing a python web app, where people can have an email sent to them on a particular day. So a user puts in his emai and date in a form and it gets stored in my database. My script would then search through the database looking for all records of todays date, retrive the email, sends them out and deletes the en...
[ "\nIs it possible to have a setup, where\n the script starts up automatically at\n a give time, say 1 pm everyday, sends\n out the email and then quits?\n\nIt's surely possible in general, but it entirely depends on what your shared web hosting provider is offering you. For these purposes, you'd use some kind o...
[ 3 ]
[]
[]
[ "email", "python" ]
stackoverflow_0002708705_email_python.txt
Q: How to setup RAM disk drive using python or WMI? The background of my question is associated with Tesseract, the free OCR engine (1985-1995 by HP, now hosting in Google). It specifically requires an input file and an output file; the argument only takes filename (not stream / binary string), so in order to use the...
How to setup RAM disk drive using python or WMI?
The background of my question is associated with Tesseract, the free OCR engine (1985-1995 by HP, now hosting in Google). It specifically requires an input file and an output file; the argument only takes filename (not stream / binary string), so in order to use the wrapper API such as pytesser and / or python-tesser.p...
[ "Are you on linux? You could try to send a file to the program through a pipe and refer to /dev/fd/0 -- it's the standard input's pathname for the current process. It should work if the application does not seek() through it.\n", "By searching at Google, I found a possible solution (that does not include WMI, but...
[ 0, 0 ]
[]
[]
[ "ocr", "python", "tesseract", "wmi" ]
stackoverflow_0002699318_ocr_python_tesseract_wmi.txt
Q: Help to run it in the background Here's a simple python daemon I can't manage to run as a background process: #!/usr/bin/env python import socket host = '' port = 843 backlog = 5 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog) while 1: client, ...
Help to run it in the background
Here's a simple python daemon I can't manage to run as a background process: #!/usr/bin/env python import socket host = '' port = 843 backlog = 5 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog) while 1: client, address = s.accept() data = client...
[ "Try\nnohup python that_server.py &\n\nAlso,\nYou're trying to use a port below 1024 which will require privileged/root access. Try a higher port.\n", "Where is the output going? nohup.out? What's in there? Is there an exception trace?\n", "I instrumented your code and it works fine here:\n$ cat server.py\n#!/...
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002708212_python.txt
Q: Stopping long-running requests in Pylons I'm working on an application using Pylons and I was wondering if there was a way to make sure it doesn't spend way too much time handling one request. That is, I would like to find a way to put a timer on each request such that when too much time elapses, the request just...
Stopping long-running requests in Pylons
I'm working on an application using Pylons and I was wondering if there was a way to make sure it doesn't spend way too much time handling one request. That is, I would like to find a way to put a timer on each request such that when too much time elapses, the request just stops (and possibly returns some kind of erro...
[ "Rather than terminate a request with an error, a better approach might be to perform long-running calculations in a separate thread (or threads) or process (or processes):\n\nWhen the calculation request is received, it is added to a queue and identified with a unique id. You redirect to a results page referencing...
[ 3 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002709371_pylons_python.txt
Q: OR in regular expression? I have text file with several thousands lines. I want to parse this file into database and decided to write a regexp. Here's part of file: blablabla checked=12 unchecked=1 blablabla unchecked=13 blablabla checked=14 As a result, I would like to get something like (12,1) (0,13) (14,0) Is...
OR in regular expression?
I have text file with several thousands lines. I want to parse this file into database and decided to write a regexp. Here's part of file: blablabla checked=12 unchecked=1 blablabla unchecked=13 blablabla checked=14 As a result, I would like to get something like (12,1) (0,13) (14,0) Is it possible?
[ "It's simplest to use two different regexes to pull the two numbers out: r\" checked=(\\d+)\" and r\" unchecked=(\\d+)\".\n", "import re\n\nlines = [\"blablabla checked=12 unchecked=1\", \"blablabla unchecked=13\"]\n\np1 = re.compile('checked=(\\d)+\\sunchecked=(\\d)')\np2 = re.compile('checked=(\\d)')\np3 = re.c...
[ 6, 1, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002697828_python_regex.txt
Q: Python script to calculate aded combinations from a dictionary I am trying to write a script that will take a dictionary of items, each containing properties of values from 0 - 10, and add the various elements to select which combination of items achieve the desired totals. I also need the script to do this, usin...
Python script to calculate aded combinations from a dictionary
I am trying to write a script that will take a dictionary of items, each containing properties of values from 0 - 10, and add the various elements to select which combination of items achieve the desired totals. I also need the script to do this, using only items that have the same "slot" in common. For example: item_...
[ "Since the properties can have both positive and negative values, and you need all satisfactory combinations, I believe there is no \"essential\" optimization possible -- that is, no polynomial-time solution (assuming P != NP...;-). All solutions will come down to enumerating all the one-per-slot combinations and ...
[ 7, 4, 3, 1 ]
[]
[]
[ "algorithm", "combinations", "combinatorics", "language_agnostic", "python" ]
stackoverflow_0002708913_algorithm_combinations_combinatorics_language_agnostic_python.txt
Q: Setting the vim color theme for highlighted braces How do you change the vim color scheme for highlighted braces? I'm looking to actually edit the .vim theme file to make the change permanent. Regards, Craig A: The automatic highlight colour for matching brackets is called MatchParen. You can change the colour i...
Setting the vim color theme for highlighted braces
How do you change the vim color scheme for highlighted braces? I'm looking to actually edit the .vim theme file to make the change permanent. Regards, Craig
[ "The automatic highlight colour for matching brackets is called MatchParen. You can change the colour in your .vimrc by doing eg:\nhighlight MatchParen cterm=bold ctermfg=cyan\n\n", "After reading the FAQ, I can answer my own question. :)\n\n24.9. Is there a built-in function to syntax-highlight the corresponding...
[ 14, 3 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0002709064_python_vim.txt
Q: setup.py adding options (aka setup.py --enable-feature ) I'm looking for a way to include some feature in a python (extension) module in installation phase. In a practical manner: I have a python library that has 2 implementations of the same function, one internal (slow) and one that depends from an external libr...
setup.py adding options (aka setup.py --enable-feature )
I'm looking for a way to include some feature in a python (extension) module in installation phase. In a practical manner: I have a python library that has 2 implementations of the same function, one internal (slow) and one that depends from an external library (fast, in C). I want that this library is optional and can...
[ "The docs for distutils include a section on extending the standard functionality. The relevant suggestion seems to be to subclass the relevant classes from the distutils.command.* modules (such as build_py or install) and tell setup to use your new versions (through the cmdclass argument, which is a dictionary map...
[ 4, 2 ]
[]
[]
[ "distutils", "packaging", "python" ]
stackoverflow_0002709278_distutils_packaging_python.txt
Q: Conventional Approaches for Passing Data to Back-End? I'm fairly new to web development, so please pardon the painfully newbie question that's about to follow. My computer science class group and I are developing a web application for class, which is built in Python (under Django) and uses jQuery on the front end....
Conventional Approaches for Passing Data to Back-End?
I'm fairly new to web development, so please pardon the painfully newbie question that's about to follow. My computer science class group and I are developing a web application for class, which is built in Python (under Django) and uses jQuery on the front end. It's primarily an Ajax-ified application, and passing data...
[ "You simply send AJAX request and pack all the data to POST request params then read it in Django.\nExample of basic voting app in django + ajax: http://lethain.com/entry/2007/dec/11/two-faced-django-part-5-jquery-ajax/\n" ]
[ 3 ]
[]
[]
[ "ajax", "django", "jquery", "python" ]
stackoverflow_0002709893_ajax_django_jquery_python.txt
Q: Python regular expressions assigning to named groups When you use variables (is that the correct word?) in python regular expressions like this: "blah (?P\w+)" ("value" would be the variable), how could you make the variable's value be the text after "blah " to the end of the line or to a certain character not pay...
Python regular expressions assigning to named groups
When you use variables (is that the correct word?) in python regular expressions like this: "blah (?P\w+)" ("value" would be the variable), how could you make the variable's value be the text after "blah " to the end of the line or to a certain character not paying any attention to the actual content of the variable. F...
[ "For that you'd want a regular expression of \n\"say (?P<value>.+) endsay\"\n\nThe period matches any character, and the plus sign indicates that that should be repeated one or more times... so .+ means any sequence of one or more characters. When you put endsay at the end, the regular expression engine will make s...
[ 12, 10 ]
[]
[]
[ "python", "regex", "variable_assignment", "variables" ]
stackoverflow_0002710486_python_regex_variable_assignment_variables.txt
Q: How to install python physics engine I want a python physics engine that works on mac and makes it easy to simulate physics. I have VPython and it works fine, but it is not quite what I want. VPython just shows visual elements and all the physics is in formulas. I looked at the documentation for PyODE and it looke...
How to install python physics engine
I want a python physics engine that works on mac and makes it easy to simulate physics. I have VPython and it works fine, but it is not quite what I want. VPython just shows visual elements and all the physics is in formulas. I looked at the documentation for PyODE and it looked like more what I want. It allowed you to...
[ "You can easily install ODE on your Mac with darwinports -- instructions here. You can easily list PyODE versions for darwinports -- then pick the right one for your chosen Python version -- by entering PyODE on the \"search in darwinports\" text box, and similarly for Pyrex (Cython is not 100% compatible with Pyr...
[ 2, 0 ]
[]
[]
[ "installation", "ode_library", "physics", "python" ]
stackoverflow_0002710173_installation_ode_library_physics_python.txt
Q: How can I validate form data using Google App Engine? I have no idea about this. A: You can use Django's form library to validate. Google has an article on it. http://code.google.com/appengine/articles/djangoforms.html
How can I validate form data using Google App Engine?
I have no idea about this.
[ "You can use Django's form library to validate. Google has an article on it.\nhttp://code.google.com/appengine/articles/djangoforms.html\n" ]
[ 3 ]
[]
[]
[ "django", "forms", "google_app_engine", "python", "validation" ]
stackoverflow_0002710636_django_forms_google_app_engine_python_validation.txt
Q: Can I use Django templatetags on Google App Engine? My Django site has many templatetags directories, can I use Django templatetags on Google App Engine? A: Yes.
Can I use Django templatetags on Google App Engine?
My Django site has many templatetags directories, can I use Django templatetags on Google App Engine?
[ "Yes.\n" ]
[ 4 ]
[]
[]
[ "django", "google_app_engine", "python", "templatetags" ]
stackoverflow_0002710832_django_google_app_engine_python_templatetags.txt