content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python GIL and globals In python, I have a global variable defined that gets read/incremented by different threads. Because of the GIL, will this ever cause problems without using any kind of locking mechanism? A: The GIL only requires that the interpreter completely executes a single bytecode instruction before...
Python GIL and globals
In python, I have a global variable defined that gets read/incremented by different threads. Because of the GIL, will this ever cause problems without using any kind of locking mechanism?
[ "The GIL only requires that the interpreter completely executes a single bytecode instruction before another thread can take over. However, there is no reason to assume that an increment operation is a single instruction. For example:\n>>> import dis\n>>> dis.dis(compile(\"x=753\",\"\",\"exec\"))\n 1 0 L...
[ 6, 3 ]
[]
[]
[ "gil", "python" ]
stackoverflow_0002157208_gil_python.txt
Q: Calling An Inherited Class Method From Java In Python, class methods can be inherited. e.g. >>> class A: ... @classmethod ... def main(cls): ... return cls() ... >>> class B(A): pass ... >>> b=B.main() >>> b <__main__.B instance at 0x00A6FA58> How would you do the equivalent in Java? I currently have: public ...
Calling An Inherited Class Method From Java
In Python, class methods can be inherited. e.g. >>> class A: ... @classmethod ... def main(cls): ... return cls() ... >>> class B(A): pass ... >>> b=B.main() >>> b <__main__.B instance at 0x00A6FA58> How would you do the equivalent in Java? I currently have: public class A{ public void show(){ System.o...
[ "Your class B does not have a main method and static methods are not inherited.\n", "The only way I can see this happening is to find whatever is calling A.main( String[] arg ) and change it to call B.main instead.\nB.main:\n public static void main( String[] arg ) {\n new B().run();\n }\n\nHow is you...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "class_method", "inheritance", "java", "python" ]
stackoverflow_0002157159_class_method_inheritance_java_python.txt
Q: exe generated with py2exe can't find pywinauto I've been trying to pack my app with py2exe. The application works fine but it keeps failing to find/use pywinauto. I been googling but I get nothing, I'm now I'm totally lost... Here's the packing script: from distutils.core import setup setup( windows = ["mainF...
exe generated with py2exe can't find pywinauto
I've been trying to pack my app with py2exe. The application works fine but it keeps failing to find/use pywinauto. I been googling but I get nothing, I'm now I'm totally lost... Here's the packing script: from distutils.core import setup setup( windows = ["mainForm.py"], data_files=[ ('', ['mainForm.ui'])...
[ "From my experience, py2exe handles imports in a weird way. Sometimes it has trouble finding linked-imports (like you import WindowHandler, which imports pywinauto).\nI would start with this in mainForm.py:\nimport sys\nimport WordOps \nimport Voice \nimport WindowHandler\nfrom PyQt import QtCore, QtGui, uic\n\nAn...
[ 1 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0002156875_py2exe_python.txt
Q: Python: Finding average of a nested list I have a list a = [[1,2,3],[4,5,6],[7,8,9]] Now I want to find the average of these inner list so that a = [(1+4+7)/3,(2+5+8)/3,(3+6+9)/3] 'a' should not be a nested list in the end. Kindly provide an answer for the generic case A: a = [sum(x)/len(x) for x in zip(*a)] ...
Python: Finding average of a nested list
I have a list a = [[1,2,3],[4,5,6],[7,8,9]] Now I want to find the average of these inner list so that a = [(1+4+7)/3,(2+5+8)/3,(3+6+9)/3] 'a' should not be a nested list in the end. Kindly provide an answer for the generic case
[ "a = [sum(x)/len(x) for x in zip(*a)]\n# a is now [4, 5, 6] for your example\n\nIn Python 2.x, if you don't want integer division, replace sum(x)/len(x) by 1.0*sum(x)/len(x) above.\nDocumentation for zip.\n", "If you have numpy installed:\n>>> import numpy as np\n>>> a = [[1,2,3],[4,5,6],[7,8,9]]\n>>> arr = np.ar...
[ 12, 6, 5 ]
[]
[]
[ "python" ]
stackoverflow_0002153444_python.txt
Q: Using namedtuple._replace with a variable as a fieldname Can I reference a namedtuple fieldame using a variable? from collections import namedtuple import random Prize = namedtuple("Prize", ["left", "right"]) this_prize = Prize("FirstPrize", "SecondPrize") if random.random() > .5: choice = "left" else: ...
Using namedtuple._replace with a variable as a fieldname
Can I reference a namedtuple fieldame using a variable? from collections import namedtuple import random Prize = namedtuple("Prize", ["left", "right"]) this_prize = Prize("FirstPrize", "SecondPrize") if random.random() > .5: choice = "left" else: choice = "right" #retrieve the value of "left" or "righ...
[ "Tuples are immutable, and so are NamedTuples. They are not supposed to be changed!\nthis_prize._replace(choice = \"Yay\") calls _replace with the keyword argument \"choice\". It doesn't use choice as a variable and tries to replace a field by the name of choice. \nthis_prize._replace(**{choice : \"Yay\"} ) would...
[ 16, 2 ]
[]
[]
[ "namedtuple", "python" ]
stackoverflow_0002157561_namedtuple_python.txt
Q: RPX, OpenID - How to write a proper SignIn Handler for AppEngine Ive spent days searching the web and im drawing a blank -im new to python too! I simply want to integrate RPX (janrain) into Appengine - loads of code for the script inserts and the return of the openid token - that's all great - but other than that ...
RPX, OpenID - How to write a proper SignIn Handler for AppEngine
Ive spent days searching the web and im drawing a blank -im new to python too! I simply want to integrate RPX (janrain) into Appengine - loads of code for the script inserts and the return of the openid token - that's all great - but other than that no-one seems to take it any further as in actually creating an openid ...
[ "GAE gives you access to a database, right? Generate a secure token and store it with the user URL returned by RPX in the database. Set the secure token as a cookie so that you get it on every request - look the token up in the database and then do the rest from there.\nWhile I'm worried about performance it actual...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "openid", "python", "rpx" ]
stackoverflow_0002149240_google_app_engine_openid_python_rpx.txt
Q: How do I change which version of python mod_python uses I'm doing some introductory work with django which seems really easy (and fun) so far but I have been doing all this from Python 2.6 which I installed in /opt/local (RedHat 5.3) because the python that came with redhat was 2.4. I set up a symlink: /usr/bin/py...
How do I change which version of python mod_python uses
I'm doing some introductory work with django which seems really easy (and fun) so far but I have been doing all this from Python 2.6 which I installed in /opt/local (RedHat 5.3) because the python that came with redhat was 2.4. I set up a symlink: /usr/bin/python2.6 -> /opt/local/bin/python and I have been using that ...
[ "You would have to rebuild mod_python against your python2.6 installation. Since mod_python loads python as a library the version is fixed at compile time.\n", "Don't use mod_python any more. mod_wsgi is the recommended way to deploy Django appliations now.\n", "You can rebuild mod_python to link against libpyt...
[ 4, 3, 2 ]
[]
[]
[ "apache", "django", "mod_python", "python" ]
stackoverflow_0002147695_apache_django_mod_python_python.txt
Q: Is this a memory leak ( a program in python with sqlalchemy/sqlite) I have the following code runs over a large set of data (2M). It eats up all my 4G mem before finishing. for sample in session.query(CodeSample).yield_per(100): for proj in projects: if sample.filename.startswit...
Is this a memory leak ( a program in python with sqlalchemy/sqlite)
I have the following code runs over a large set of data (2M). It eats up all my 4G mem before finishing. for sample in session.query(CodeSample).yield_per(100): for proj in projects: if sample.filename.startswith(proj.abs_source): sample.filename = "some o...
[ "Most DBAPIs, including psycopg2 and mysql-python, fully load all results into memory before releasing them to the client. SQLA's yield_per() option doesn't work around this, with one exception below, which is why its generally not a very useful option(edit: useful in the sense that it begins streaming results be...
[ 6, 2 ]
[]
[]
[ "memory", "memory_leaks", "python", "sqlalchemy" ]
stackoverflow_0002145177_memory_memory_leaks_python_sqlalchemy.txt
Q: Change the color of a node or an edge I want to redraw a Graph g with only the color of a node or edge changed. How do I do that? A: Your version of networkx is too old. try $ easy_install networkx to get the current version
Change the color of a node or an edge
I want to redraw a Graph g with only the color of a node or edge changed. How do I do that?
[ "Your version of networkx is too old.\ntry\n$ easy_install networkx\n\nto get the current version\n" ]
[ 1 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0002157530_networkx_python.txt
Q: Python regex split, integer of arbitrary length I'm trying to do a simple regex split in Python. The string is in the form of FooX where Foo is some string and X is an arbitrary integer. I have a feeling this should be really simple, but I can't quite get it to work. On that note, can anyone recommend some good Re...
Python regex split, integer of arbitrary length
I'm trying to do a simple regex split in Python. The string is in the form of FooX where Foo is some string and X is an arbitrary integer. I have a feeling this should be really simple, but I can't quite get it to work. On that note, can anyone recommend some good Regex reading materials?
[ "You can't use split() since that has to consume some characters, but you can use normal matching to do it.\n>>> import re\n>>> r = re.compile(r'(\\D+)(\\d+)')\n>>> r.match('abc444').groups()\n('abc', '444')\n\n", "Using groups:\nimport re\n\nm=re.match('^(?P<first>[A-Za-z]+)(?P<second>[0-9]+)$',\"Foo9\")\nprint ...
[ 6, 1, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002157894_python_regex.txt
Q: Python code for determining which normal form tabular data is in I'm looking for Python code that can take tabular data and establish which normal form(s) it is in (if any) and show any functional dependencies, etc. A: There are logical tests for "normalization". However, they're not trivial exercises in progra...
Python code for determining which normal form tabular data is in
I'm looking for Python code that can take tabular data and establish which normal form(s) it is in (if any) and show any functional dependencies, etc.
[ "There are logical tests for \"normalization\". However, they're not trivial exercises in programming; they're relationships in the metadata that are imposed on the data. They require \"thinking\".\n1NF -- no repeating groups. How does one identify a \"repeating group\"? It would be an array structure imposed o...
[ 2 ]
[]
[]
[ "database_normalization", "normalization", "python", "relational_algebra" ]
stackoverflow_0002157531_database_normalization_normalization_python_relational_algebra.txt
Q: How to create a django model field that has a default value if ever set to null Given a model class Template(models.Model): colour = models.CharField(default="red", blank = True, null=True) How can I arrange it so that any access to colour either returns the value stored in the field, or if the field is blank...
How to create a django model field that has a default value if ever set to null
Given a model class Template(models.Model): colour = models.CharField(default="red", blank = True, null=True) How can I arrange it so that any access to colour either returns the value stored in the field, or if the field is blank/null then it returns red? The default=red will put "red" in the field when it's firs...
[ "You can create a separate method instead:\ndef get_colour(self):\n if not self.colour:\n return 'red'\n else:\n return self.colour\n\nAn alternative is to use property.\nhttp://www.djangoproject.com/documentation/models/properties/\n", "Use the save method to implement this.\ndef save( self, ...
[ 4, 1, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002156585_django_django_models_python.txt
Q: How do I access a python list from a django templatetag? I have created a templatetag that loads a yaml document into a python list. In my template I have {% get_content_set %}, this dumps the raw list data. What I want to be able to do is something like {% for items in get_content_list %} <h2>{{items.t...
How do I access a python list from a django templatetag?
I have created a templatetag that loads a yaml document into a python list. In my template I have {% get_content_set %}, this dumps the raw list data. What I want to be able to do is something like {% for items in get_content_list %} <h2>{{items.title}}</h2> {% endfor %}`
[ "If the list is in a python variable X, then add it to the template context context['X'] = X and then you can do\n{% for items in X %}\n {{ items.title }}\n{% endfor %}\n\nA template tag is designed to render output, so won't provide an iterable list for you to use. But you don't need that as the normal cont...
[ 3, -1 ]
[]
[]
[ "django", "django_templates", "python", "templates", "yaml" ]
stackoverflow_0002157665_django_django_templates_python_templates_yaml.txt
Q: How to extend the Turbogears 2.1 login functionality I'm using Turbogears 2.1 and repoze.who/what and am having trouble figuring out how to extend the basic authentication functionality. I am essentially attempting to require users to activate their account via an emailed link before they can login. If they try to...
How to extend the Turbogears 2.1 login functionality
I'm using Turbogears 2.1 and repoze.who/what and am having trouble figuring out how to extend the basic authentication functionality. I am essentially attempting to require users to activate their account via an emailed link before they can login. If they try to login without activating their account, I want to display...
[ "It's impossible to give a really good answer without seeing your actual code, but here's one idea:\n\nCreate a repoze.who metadata provider plugin that \"scribbles\" something that indicates whether the user has activated their account.\nCreate a \"challenger decider\" plugin that looks at both whether the user ha...
[ 4 ]
[]
[]
[ "python", "turbogears", "turbogears2" ]
stackoverflow_0001960747_python_turbogears_turbogears2.txt
Q: Easy way to upload files to S3 via HTTP Form I have written a tiny web appication in python that allows me to browse my S3 buckets. The web appication runs inside the Google App Engine. Now, I want to create a html form for this web appication that allows me to upload a file into the bucket. These information are...
Easy way to upload files to S3 via HTTP Form
I have written a tiny web appication in python that allows me to browse my S3 buckets. The web appication runs inside the Google App Engine. Now, I want to create a html form for this web appication that allows me to upload a file into the bucket. These information are already inside the form: AWSAccessKeyId and the n...
[ "Read the developer documentation from Amazon: Browser Uploads to S3 using HTML POST Forms\nThere is Python examples in there to get you started.\n" ]
[ 4 ]
[]
[]
[ "amazon_s3", "google_app_engine", "html", "python" ]
stackoverflow_0002158871_amazon_s3_google_app_engine_html_python.txt
Q: How to append a file's creation date to its filename? I would like to create a python script that appends the file created date to the end of the filename while retaining the oringinal file name (Report) for a batch of pdf documents. directory = T:\WISAARD_Web Portal Projects\PortalLogging\WebLogExpert filenames =...
How to append a file's creation date to its filename?
I would like to create a python script that appends the file created date to the end of the filename while retaining the oringinal file name (Report) for a batch of pdf documents. directory = T:\WISAARD_Web Portal Projects\PortalLogging\WebLogExpert filenames = Report.pdf
[ "import os,time\nroot=\"/home\"\npath=os.path.join(root,\"dir1\")\nos.chdir(path)\nfor files in os.listdir(\".\"):\n if files.endswith(\".pdf\"):\n f,ext = os.path.splitext(files) \n d=time.ctime(os.path.getmtime(files)).split() #here is just example. you can use strftime, strptime etc to fo...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002158961_python.txt
Q: Strange Python set and hash behaviour - how does this work? I have a class called GraphEdge which I would like to be uniquely defined within a set (the built-in set type) by its tail and head members, which are set via __init__. If I do not define __hash__, I see the following behaviour: >>> E = GraphEdge('A', 'B'...
Strange Python set and hash behaviour - how does this work?
I have a class called GraphEdge which I would like to be uniquely defined within a set (the built-in set type) by its tail and head members, which are set via __init__. If I do not define __hash__, I see the following behaviour: >>> E = GraphEdge('A', 'B') >>> H = GraphEdge('A', 'B') >>> hash(E) 139731804758160 >>> has...
[ "You have a hash collision. On hash collision, the set uses the == operator to check on whether or not they are truly equal to each other.\n", "It's important to understand how hash and == work together, because both are used by sets. For two values x and y, the important rule is that:\nx == y ==> hash(x) == has...
[ 15, 7, 6 ]
[]
[]
[ "hash", "python", "set" ]
stackoverflow_0002159232_hash_python_set.txt
Q: Python 3.0 urllib.parse error "Type str doesn't support the buffer API" File "/usr/local/lib/python3.0/cgi.py", line 477, in __init__ self.read_urlencoded() File "/usr/local/lib/python3.0/cgi.py", line 577, in read_urlencoded self.strict_parsing): File "/usr/local/lib/python3.0/urllib/parse.py", line...
Python 3.0 urllib.parse error "Type str doesn't support the buffer API"
File "/usr/local/lib/python3.0/cgi.py", line 477, in __init__ self.read_urlencoded() File "/usr/local/lib/python3.0/cgi.py", line 577, in read_urlencoded self.strict_parsing): File "/usr/local/lib/python3.0/urllib/parse.py", line 377, in parse_qsl pairs = [s2 for s1 in qs.split('&') for s2 in s1.split...
[ "urllib is trying to do:\nb'a,b'.split(',')\n\nWhich doesn't work. byte strings and unicode strings mix even less smoothly in Py3k than they used to — deliberately, to make encoding problems go wrong sooner rather than later.\nSo the error is rather opaquely telling you ‘you can't pass a byte string to urllib.parse...
[ 28, 13 ]
[]
[]
[ "cgi", "python", "python_3.x", "urllib" ]
stackoverflow_0000540342_cgi_python_python_3.x_urllib.txt
Q: javax.script.ScriptEngine fails at runtime Any ideas? public class Main { public static void main(String[] args) throws ScriptException { ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); engine.put("hello_str", ""); engine.eval("for i in range(10):"); engine.eval(" hello...
javax.script.ScriptEngine fails at runtime
Any ideas? public class Main { public static void main(String[] args) throws ScriptException { ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); engine.put("hello_str", ""); engine.eval("for i in range(10):"); engine.eval(" hello_str += str(i)"); Object x = engine.get("hel...
[ "Looks like you are trying to evaluate an incomplete statement in the lines:\nengine.eval(\"for i in range(10):\");\nengine.eval(\" hello_str += str(i)\");\n\nHere, I assume eval() is trying to evaluate these one-by-one, and finding nothing after the for is erroring out since that is an incomplete statement. Try ...
[ 2 ]
[]
[]
[ "java", "python", "scriptengine" ]
stackoverflow_0002159273_java_python_scriptengine.txt
Q: lxml has essentially nothing The lxml package for Python seems to absolutely broken on my system. I am not sure of the problem, as all of the files are in place, it seems. My suspicion is that the problem is in __init__.py, but I don't have enough practice with the system to make an accurate diagnosis or fix the p...
lxml has essentially nothing
The lxml package for Python seems to absolutely broken on my system. I am not sure of the problem, as all of the files are in place, it seems. My suspicion is that the problem is in __init__.py, but I don't have enough practice with the system to make an accurate diagnosis or fix the problem. Here is some code that I t...
[ "No, you're just doing it wrong! Try, e.g., from lxml import etree, and you should be able to use etree fully. import lxml -- importing the package! -- does not give you implicit access to any of the package's modules!-)\n", "I think all the lxml code is in subpackages. Try\nfrom lxml import etree\n\n", "It'...
[ 10, 1, 1 ]
[]
[]
[ "lxml", "package", "python" ]
stackoverflow_0002159690_lxml_package_python.txt
Q: Why Python on Windows can't read an image in binary mode? I want to read a image in binary mode so that I could save it into my database, like this: img = open("Last_Dawn.jpg") t = img.read() save_to_db(t) This is working on Mac. But on Windows, what img.read() is incorrect. It's just a little out of the whole se...
Why Python on Windows can't read an image in binary mode?
I want to read a image in binary mode so that I could save it into my database, like this: img = open("Last_Dawn.jpg") t = img.read() save_to_db(t) This is working on Mac. But on Windows, what img.read() is incorrect. It's just a little out of the whole set. So my first question is: why code above doesn't work in Wind...
[ "You need to open in binary mode:\nimg = open(\"Last_Dawn.jpg\", 'rb')\n\n", "You need to tell Python to open the file in binary mode:\nimg = open('whatever.whatever', 'rb')\n\nSee the documentation for the open function here: http://docs.python.org/library/functions.html#open\n", "open(filename, 'rb')\n\n", ...
[ 6, 4, 2, 2 ]
[]
[]
[ "binary", "image", "python" ]
stackoverflow_0002159794_binary_image_python.txt
Q: Signing requests in Python for OAuth currently I'm interfacing the Twitter API using the OAuth protocol and writing the code in Python. As most of the users out there, I think the toughest part of the specs is dealing with signatures. After wandering around the web in search for a solution, I decided to go for my ...
Signing requests in Python for OAuth
currently I'm interfacing the Twitter API using the OAuth protocol and writing the code in Python. As most of the users out there, I think the toughest part of the specs is dealing with signatures. After wandering around the web in search for a solution, I decided to go for my custom code, so as to have a better unders...
[ "My knee-jerk reaction to this is If You're Typing The Letters A-E-S Into Your Code, You're Doing It Wrong. Or, as redditor khafra recently reminded us of the Sicilian's version:\n\nHaha.. you fool! You fell victim to one of the classic blunders. The most famous is: Never get involved in a land war in Asia. But on...
[ 2 ]
[]
[]
[ "oauth", "python", "signature" ]
stackoverflow_0002138656_oauth_python_signature.txt
Q: Boost::Python, static factories, and inheritance So I may have a rather unique use case here, but I'm thinking it should work- But it's not working correctly. Basically, I have a class that uses a static factory method ( create ) that returns a shared_ptr to the newly created instance of the class. This class also...
Boost::Python, static factories, and inheritance
So I may have a rather unique use case here, but I'm thinking it should work- But it's not working correctly. Basically, I have a class that uses a static factory method ( create ) that returns a shared_ptr to the newly created instance of the class. This class also has a virtual function that I'd like to override from...
[ "I ended up rethinking my design using intrusive_ptrs. There was a little more work to be done with the wrappers than using shared_ptr, but it worked out fairly well. Thanks to everyone for their time.\n" ]
[ 1 ]
[]
[]
[ "boost", "c++", "python" ]
stackoverflow_0002148777_boost_c++_python.txt
Q: Suggestions on manipulating an SVG map I'm working on a map of the native languages of California for Wikipedia. The map contains areas that each correspond to a language. The original looks like this (click it to see the SVG): I want to make "locator maps" for each of those individual languages by hand (in Inksc...
Suggestions on manipulating an SVG map
I'm working on a map of the native languages of California for Wikipedia. The map contains areas that each correspond to a language. The original looks like this (click it to see the SVG): I want to make "locator maps" for each of those individual languages by hand (in Inkscape), like this one, for a language called C...
[ "I would recommend using Python and specifically creating extensions for Inkscape. I don't think you really need 60 SVG unless you really want to because the source map will have everything you need.\nWhat I would do is use Inkscape to rename the various regions to the same language code you will be using. For exam...
[ 8, 4 ]
[]
[]
[ "cartography", "python", "svg" ]
stackoverflow_0002054438_cartography_python_svg.txt
Q: Blogger (Python) API: How do I retrieve a post by post ID? Having previously obtained a post ID from a call to gdata.blogger.client.add_post()... post = client.add_post(...) post_id = post.get_post_id() ...how do I use that post id to retrieve the post in the future? I thought maybe gdata.blogger.client.Query wo...
Blogger (Python) API: How do I retrieve a post by post ID?
Having previously obtained a post ID from a call to gdata.blogger.client.add_post()... post = client.add_post(...) post_id = post.get_post_id() ...how do I use that post id to retrieve the post in the future? I thought maybe gdata.blogger.client.Query would be the way to go, but this doesn't support post id as a quer...
[ "Continue my theme of answering my own questions...\nAfter lots of fiddling, it looks like this is one solution. Given:\n\nclient -- a gdata.blogger.client.BloggerClient instance, and\nblog -- a gdata.blogger.data.Blog instance\npost_id -- a post id as returned by gdata.blogger.data.BlogPost.get_post_id\n\nYou can ...
[ 1 ]
[]
[]
[ "blogger", "gdata", "python" ]
stackoverflow_0002152112_blogger_gdata_python.txt
Q: Has anybody tried html2pdf in django? Ok when im gonna make reports with Java I use iReport for JasperReports Template designs. But with python the alternative is html2pdf - pisa. It would be great to see an example of this. Any hint would be appreciated. A: The accounting software we are developing uses pisa to...
Has anybody tried html2pdf in django?
Ok when im gonna make reports with Java I use iReport for JasperReports Template designs. But with python the alternative is html2pdf - pisa. It would be great to see an example of this. Any hint would be appreciated.
[ "The accounting software we are developing uses pisa to generate pdf reports. The process is like this:\n\nRender a HTML template\nConvert the rendered string to pdf. You can directly use the HttpResponse object you will return as output file, or a StringIO object to store the pdf and send its content via HttpRespo...
[ 4, 3, 1 ]
[]
[]
[ "django", "pdf", "pdf_generation", "python" ]
stackoverflow_0001301442_django_pdf_pdf_generation_python.txt
Q: Adding an edge/node with a color attribute I a using the networkx package of Python. The documentation says we can do H.add_edge(1,2,color='blue') but the output shows an edge with the default (black) color. When I do H.add_node(12,color='green') I get a new node with same default red color. A: Peter, according ...
Adding an edge/node with a color attribute
I a using the networkx package of Python. The documentation says we can do H.add_edge(1,2,color='blue') but the output shows an edge with the default (black) color. When I do H.add_node(12,color='green') I get a new node with same default red color.
[ "Peter, according to the documentation, to change the color with which nodes/edges are drawn, you have to provide the node_color argument to the drawing function. I.e. from this example, to draw a graph like this (note different colors of nodes):\n\nThe code is:\n#!/usr/bin/env python\n\"\"\"\nDraw a graph with mat...
[ 4 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0002160161_networkx_python.txt
Q: imports while starting an interactive shell When I start the interactive django shell through manage.py, by executing python -v manage.py shell from the project directory, I see a lot of modules of format django.package.module getting imported in the verbose output but still I have to import them to use it in th...
imports while starting an interactive shell
When I start the interactive django shell through manage.py, by executing python -v manage.py shell from the project directory, I see a lot of modules of format django.package.module getting imported in the verbose output but still I have to import them to use it in the shell. The same happens when I just run the Py...
[ "-v traces the first import of a module -- the one that actually loads the module (executes its code, and so may take a bit of time) and sticks it into sys.modules.\nThat has nothing to do whether your interactive session (module __main__) gets the module injected into its namespace, of course. To ensure module 'g...
[ 1, 0, 0 ]
[]
[]
[ "django", "import", "python", "shell" ]
stackoverflow_0002160190_django_import_python_shell.txt
Q: Problem In Running easy_install.exe under Windows I am running Python under windows. I face no problem in installing pysqlite package. C:\>c:\Python26\Scripts\easy_install.exe pysqlite Searching for pysqlite Reading http://pypi.python.org/simple/pysqlite/ ........ Download error: [Errno 11001] getaddrinfo failed -...
Problem In Running easy_install.exe under Windows
I am running Python under windows. I face no problem in installing pysqlite package. C:\>c:\Python26\Scripts\easy_install.exe pysqlite Searching for pysqlite Reading http://pypi.python.org/simple/pysqlite/ ........ Download error: [Errno 11001] getaddrinfo failed -- Some packages may not be found! Reading http://initd....
[ "The psycopg PyPi posting does not contain a pre-built w32 installer that easy_install can use nor could it find a way to build from source.\nHere are some pre-built versions of the psycopg module.\n", "easy_install only knows how to install modules distributed with the Python standard distribution and packaging ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002159809_python.txt
Q: Addressing instance name string in __init__(self) in Python I am doing something like this: class Class(object): def __init__(self): self.var=#new instance name string# How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case: c=Class() I want c.var e...
Addressing instance name string in __init__(self) in Python
I am doing something like this: class Class(object): def __init__(self): self.var=#new instance name string# How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case: c=Class() I want c.var equal to 'c'. Thanks for your replies, I am implementing persisten...
[ "Python doesn't have variables, it has objects and names. When you do \nc = Class()\n\nyou're doing two things:\n\nCreating a new object of type Class\nBinding the object to the name c in the current scope.\n\nThe object you created doesn't have any concept of a \"variable name\" -- If later you do\na = c\n\nthen t...
[ 7, 3, 2, 2, 1, 1, 1, 0, 0 ]
[]
[]
[ "instance", "instantiation", "python" ]
stackoverflow_0000443775_instance_instantiation_python.txt
Q: Problem Install and Run psycopg2 + Windows + Apache2 + mod_wsgi 1) I try to setup a new web environment to host python + psycopg2 code. Here are my steps : 2) Download http://modwsgi.googlecode.com/files/mod_wsgi-win32-ap22py26-3.0.so 3) Copy mod_wsgi-win32-ap22py26-3.0.so to C:\Program Files\Apache Software Found...
Problem Install and Run psycopg2 + Windows + Apache2 + mod_wsgi
1) I try to setup a new web environment to host python + psycopg2 code. Here are my steps : 2) Download http://modwsgi.googlecode.com/files/mod_wsgi-win32-ap22py26-3.0.so 3) Copy mod_wsgi-win32-ap22py26-3.0.so to C:\Program Files\Apache Software Foundation\Apache2.2\modules, and rename it as mod_wsgi.so Add the followi...
[ "I am able to solve the problem, by moving python script outside htdocs\nWSGIScriptAlias /wsgi \"C:/wsgi/\"\n\n<Directory \"C:/wsgi\">\n AllowOverride None\n Options None\n Order deny,allow\n Allow from all\n</Directory>\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002160256_python.txt
Q: Python GTK+: create custom signals? Is it possible to create new signals in Python GTK+ ? I'd like a skeleton code example, please. A: An excerpt: Creating your own signals The other thing you probably want to use when subclassing GObject is define custom signals. You can create your own signals that ca...
Python GTK+: create custom signals?
Is it possible to create new signals in Python GTK+ ? I'd like a skeleton code example, please.
[ "An excerpt:\n\nCreating your own signals\nThe other thing you probably want to\n use when subclassing GObject is define\n custom signals. You can create your\n own signals that can be emitted so\n users of your class can connect to\n them.\nWhen a signal is emitted a set of\n closures will be executed. A clo...
[ 8, 4 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002057921_gtk_pygtk_python.txt
Q: Single linked list in Python, how to write pop and push? I am trying to code a class that makes use of Push and Pop from a stack (with single linked list). I am not sure how to write the push and pop functions. I really need a simple example written in Python with the following functions. Push Pop ifEmpty A: Fro...
Single linked list in Python, how to write pop and push?
I am trying to code a class that makes use of Push and Pop from a stack (with single linked list). I am not sure how to write the push and pop functions. I really need a simple example written in Python with the following functions. Push Pop ifEmpty
[ "From the docs that Dyno Fu linked to:\n\nThe list methods make it very easy to\n use a list as a stack, where the last\n element added is the first element\n retrieved (“last-in, first-out”). To\n add an item to the top of the stack,\n use append(). To retrieve an item from\n the top of the stack, use pop()\...
[ 8, 3 ]
[]
[]
[ "python", "stack" ]
stackoverflow_0002160994_python_stack.txt
Q: How do I pass compressed data using the Task Queue Python API in App Engine? I'm trying to use compressed data with my Tasks in the Task Queue like so: t = taskqueue.Task(url='/tasks/queue', params={'param': zlib.compress(some_string)} However when I try to decompress it in the queue handler li...
How do I pass compressed data using the Task Queue Python API in App Engine?
I'm trying to use compressed data with my Tasks in the Task Queue like so: t = taskqueue.Task(url='/tasks/queue', params={'param': zlib.compress(some_string)} However when I try to decompress it in the queue handler like so message = self.request.get('param') message = zlib.decompress(message) I ge...
[ "Instead of using params, use payload, which includes your data in the body of the request, unencoded. Then you can use zlib.decompress(self.request.body) to retrieve the data.\n", "Read the docs... (my emphasis!):\n\nparams Dictionary of parameters to use\n for this Task. Values in the\n dictionary may be iter...
[ 5, 2 ]
[]
[]
[ "google_app_engine", "python", "task_queue", "zlib" ]
stackoverflow_0002160011_google_app_engine_python_task_queue_zlib.txt
Q: JSON python to javascript I want to transfer some data from python to javascript. I use Django at python side and jQuery at javascript side. The object I serialize at python side is a dictionary. Besides simple objects like lists and variables, this dictionary contains instances of SomeClass. To serialize those i...
JSON python to javascript
I want to transfer some data from python to javascript. I use Django at python side and jQuery at javascript side. The object I serialize at python side is a dictionary. Besides simple objects like lists and variables, this dictionary contains instances of SomeClass. To serialize those instances I extendeded simplejso...
[ "\nEval the JSON string into an object\nRun through the values of the object and identify values with magicParameter='SomeClass'\nRun those values through a converter\nAssign the result back to where the value initially was in the result object\n\n" ]
[ 0 ]
[]
[]
[ "django", "javascript", "jquery", "json", "python" ]
stackoverflow_0002161457_django_javascript_jquery_json_python.txt
Q: Is it possible to access the GetLongPathName() Win32 API in Python? I need to convert paths in 8.3 convention to full path. In Perl, I can use Win32::GetLongPathName() as pointed out in How do I get full Win32 path from 8.3 DOS path with Perl? But, I need to do it in Python. A: Use ctypes which is available in t...
Is it possible to access the GetLongPathName() Win32 API in Python?
I need to convert paths in 8.3 convention to full path. In Perl, I can use Win32::GetLongPathName() as pointed out in How do I get full Win32 path from 8.3 DOS path with Perl? But, I need to do it in Python.
[ "Use ctypes which is available in the Python standard without the need of using the pywin32 API. Like this:\nfrom ctypes import *\n\nbuf = create_unicode_buffer(260)\nGetLongPathName = windll.kernel32.GetLongPathNameW\nrv = GetLongPathName(path, buf, 260)\nprint buf.value\n\nFrom http://mail.python.org/pipermail/py...
[ 8, 5 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0001587816_python_windows.txt
Q: python libxml2dom xpath question quick question... i can create/parse a chunk of html using libxml2dom, etc... however, is there a way to somehow display the xpath used to generate/extract the html chunk.. i'm assuming that there's some method/way of doing this that i can't find.. ex: import libxml2dom d = libxml2...
python libxml2dom xpath question
quick question... i can create/parse a chunk of html using libxml2dom, etc... however, is there a way to somehow display the xpath used to generate/extract the html chunk.. i'm assuming that there's some method/way of doing this that i can't find.. ex: import libxml2dom d = libxml2dom.parseString(s, html=1) ## hdr="...
[ "I did this by iterating each node and comparing the textContent with my expected text. For fuzzy comparisons I used the SequenceMatcher class from difflib.\n" ]
[ 0 ]
[]
[]
[ "libxml2", "python" ]
stackoverflow_0001937477_libxml2_python.txt
Q: Returning the first N characters of a unicode string I have a string in unicode and I need to return the first N characters. I am doing this: result = unistring[:5] but of course the length of unicode strings != length of characters. Any ideas? The only solution is using re? Edit: More info unistring = "Μεταλλικα...
Returning the first N characters of a unicode string
I have a string in unicode and I need to return the first N characters. I am doing this: result = unistring[:5] but of course the length of unicode strings != length of characters. Any ideas? The only solution is using re? Edit: More info unistring = "Μεταλλικα" #Metallica written in Greek letters result = unistring[:...
[ "When you say:\nunistring = \"Μεταλλικα\" #Metallica written in Greek letters\n\nYou do not have a unicode string. You have a bytestring in (presumably) UTF-8. That is not the same thing. A unicode string is a separate datatype in Python. You get unicode by decoding bytestrings using the right encoding:\nunistring ...
[ 7, 7, 4 ]
[]
[]
[ "python", "python_2.x", "unicode" ]
stackoverflow_0002153920_python_python_2.x_unicode.txt
Q: Modpython and virtualenv Is it any way to run django site on virtualenv without administration rights? How can I do it? Virtualenv is already installed. A: Yes, but not with mod_python.
Modpython and virtualenv
Is it any way to run django site on virtualenv without administration rights? How can I do it? Virtualenv is already installed.
[ "Yes, but not with mod_python.\n" ]
[ 0 ]
[]
[]
[ "django", "mod_python", "python", "virtualenv" ]
stackoverflow_0002162790_django_mod_python_python_virtualenv.txt
Q: Python path in environment I want to call a python script from batch script, but I dont want to hard-code path to python executable (python.exe) in my calling script. e.g. c:\python26\python.exe test.py $PYTHONPATH\python.exe test.py Is there any way to have PYTHONPATH like setting ? A: The simplest thing i...
Python path in environment
I want to call a python script from batch script, but I dont want to hard-code path to python executable (python.exe) in my calling script. e.g. c:\python26\python.exe test.py $PYTHONPATH\python.exe test.py Is there any way to have PYTHONPATH like setting ?
[ "The simplest thing is to add c:\\python26 to you system's PATH.\nAlso, depending on how you installed Python, you should be able to just use test.py on the command line.\n", "set PYTHON_INSTALL=D:\\python26\n\nthen:\n%PYTHON_INSTALL%\\python.exe test.py\n\nYou could set up the PYTHON_INSTALL var using My Compute...
[ 4, 3, 0 ]
[]
[]
[ "development_environment", "environment_variables", "python", "scripting", "windows" ]
stackoverflow_0002163429_development_environment_environment_variables_python_scripting_windows.txt
Q: Python: subprocess loops forever I'm trying to start/stop rsyslog through a python script: RSYSLOG_INIT_SCRIPT='/etc/init.s/rsyslogd' subprocess.call([RSYSLOG_INIT_SCRIPT,'stop']) /etc/init.d/rsyslogd is a regular init script. The problem is that it continues executing this script again and again. (I've added an ...
Python: subprocess loops forever
I'm trying to start/stop rsyslog through a python script: RSYSLOG_INIT_SCRIPT='/etc/init.s/rsyslogd' subprocess.call([RSYSLOG_INIT_SCRIPT,'stop']) /etc/init.d/rsyslogd is a regular init script. The problem is that it continues executing this script again and again. (I've added an echo to the script to confirm this). T...
[ "Not sure what is going on, but try creating your shell script like this:\n#!/bin/sh\nwhile :\ndo\n echo \"Sleeping...\"\n sleep 1\ndone\n\nThen confirm that your python program when running this script does the same thing.\nThen confirm the python call with this script:\n#!/bin/sh\necho \"I will exit\"\n\nSe...
[ 1, 0 ]
[]
[]
[ "python", "rsyslog", "subprocess" ]
stackoverflow_0002163582_python_rsyslog_subprocess.txt
Q: Running external subprocesses and reading return code I'm creating a python script to sort a lot of images (game screenshots). I found a way to do that in imagemagick : I know that, if a specific square of the image is the same as the reference crop, then the image is of category one. If not, I check for another c...
Running external subprocesses and reading return code
I'm creating a python script to sort a lot of images (game screenshots). I found a way to do that in imagemagick : I know that, if a specific square of the image is the same as the reference crop, then the image is of category one. If not, I check for another crop and another category, and if that doesn't fit either, I...
[ "import subprocess\n\nretcode = subprocess.call(['convert', 'file.jpg', '-crop', \n '80x10+90+980', '+repage', 'crop.jpg'])\nif retcode != 0:\n print 'error on convert'\nelse:\n retcode = subprocess.call(['compare', '-metric', 'PSNR', \n 'reference.jpg',...
[ 4 ]
[]
[]
[ "popen", "process", "python", "return", "subprocess" ]
stackoverflow_0002163579_popen_process_python_return_subprocess.txt
Q: How can I run a loop against 2 random elements from a list at a time? Let's say I have a list in python with several strings in it. I do not know the size. How can I run a loop to do an operation on 2 random elements of this string? What if I wanted to favour a certain subset of the strings in this randomizati...
How can I run a loop against 2 random elements from a list at a time?
Let's say I have a list in python with several strings in it. I do not know the size. How can I run a loop to do an operation on 2 random elements of this string? What if I wanted to favour a certain subset of the strings in this randomization, to be selected more often, but still make it possible for them to not b...
[ "you need to look into random module. It has for example a random.choice function that lets you select a random element from a sequence or a random.sample that selects given number of samples, it's easy to account for different weights too.\n", "explain better your problem, what operations and what elements you'r...
[ 4, 0 ]
[]
[]
[ "probability", "python" ]
stackoverflow_0002163765_probability_python.txt
Q: Check if a file is setuid root in Python I'm trying to check if a file has the setuid bit in Python. The stat doc mentions a S_ISUID function but it only works with os.chmod(), not to actually read the setuid bit. It also lists S_IMODE, but I have no idea how to interpret it. How can I easily check if a file as th...
Check if a file is setuid root in Python
I'm trying to check if a file has the setuid bit in Python. The stat doc mentions a S_ISUID function but it only works with os.chmod(), not to actually read the setuid bit. It also lists S_IMODE, but I have no idea how to interpret it. How can I easily check if a file as the setuid root bit set?
[ "stat.S_ISUID is the mode bit for 'setuid'. You compare the stat result's mode to see if it contains that bit:\n>>> ping = os.stat('/bin/ping')\n>>> ping.st_mode & stat.S_ISUID\n2048\n>>> echo = os.stat('/bin/echo')\n>>> echo.st_mode & stat.S_ISUID\n0\n\n" ]
[ 7 ]
[]
[]
[ "file", "python", "setuid", "stat" ]
stackoverflow_0002163800_file_python_setuid_stat.txt
Q: Can a Python package depend on a specific version control revision of another Python package? Some useful Python packages are broken on pypi, and the only acceptable version is a particular revision in a revision control system. Can that be expressed in setup.py e.g requires = 'svn://example.org/useful.package/tru...
Can a Python package depend on a specific version control revision of another Python package?
Some useful Python packages are broken on pypi, and the only acceptable version is a particular revision in a revision control system. Can that be expressed in setup.py e.g requires = 'svn://example.org/useful.package/trunk@1234' ?
[ "You need to do two things. First, require the exact version you want, e.g.:\ninstall_requires = \"useful.package==1.9dev-r1234\"\n\nand then include a dependency_links setting specifying where to find it:\ndependency_links = [\"svn://example.org/useful.package/trunk@1234#egg=useful.package-1.9dev-r1234\"]\n\nNote...
[ 12, 2, 2, 1 ]
[]
[]
[ "distutils", "easy_install", "pip", "python", "setuptools" ]
stackoverflow_0002087492_distutils_easy_install_pip_python_setuptools.txt
Q: m2crypto custom certificate verification I need to build an encrypted connection between two peers, and I need to authenticate both. Both peers already share a fingerprint (SHA256 hash) of the other peer public key. I'm not using X509 or OpenPGP keys/certs as they are too big and bulky for my needs and they don't ...
m2crypto custom certificate verification
I need to build an encrypted connection between two peers, and I need to authenticate both. Both peers already share a fingerprint (SHA256 hash) of the other peer public key. I'm not using X509 or OpenPGP keys/certs as they are too big and bulky for my needs and they don't fit in the security model. I'm trying to build...
[ "It seems your approach should work, but there is already a builtin fingerprint checker you might be able to use. See here: What to put for a commonName when making an OpenSSL key?\n" ]
[ 0 ]
[ "The answer is in the question: use proper x509 certificates, and validate/verify symmetrically. \"Is this secure?\" - no, because you have to ask.\nYour solution may work, but the fact you are asking for advice on \"Is this secure?\" tells me that you should probably use stuff straight from the box.\n" ]
[ -2 ]
[ "m2crypto", "python", "x509" ]
stackoverflow_0002160158_m2crypto_python_x509.txt
Q: force unpacking of certain egg directories I have an egg distribution of a PyQt application which i build myself, and it contains sphinx generated documentation. When i call the help file from the application it opens the sphinx index.html in a QtWebKit.QWebView window. Apparently, only the index.html file is extr...
force unpacking of certain egg directories
I have an egg distribution of a PyQt application which i build myself, and it contains sphinx generated documentation. When i call the help file from the application it opens the sphinx index.html in a QtWebKit.QWebView window. Apparently, only the index.html file is extracted from the egg into the OS's egg-directory (...
[ "I see that you've already found another way to do it, but for future reference, here's the non-workaround way to do it automatically, from the documentation at http://peak.telecommunity.com/DevCenter/setuptools#automatic-resource-extraction [emphasis added]:\n\nIf you are using tools that expect your resources to ...
[ 4, 2, 1 ]
[]
[]
[ "egg", "python", "python_sphinx", "setuptools" ]
stackoverflow_0001762306_egg_python_python_sphinx_setuptools.txt
Q: How can I manually register distributions with pkg_resources? I'm trying to get a package installed on Google App Engine. The package relies rather extensively on pkg_resources, but there's no way to run setup.py on App Engine. There's no platform-specific code in the source, however, so it's no problem to just z...
How can I manually register distributions with pkg_resources?
I'm trying to get a package installed on Google App Engine. The package relies rather extensively on pkg_resources, but there's no way to run setup.py on App Engine. There's no platform-specific code in the source, however, so it's no problem to just zip up the source and include those in the system path. And I've go...
[ "Yes, for setuptools-based libraries you'll need to deploy the library's \"Egg\" metadata along with it. The easiest way I've found is to deploy a whole virtualenv environment containing your project and the required libraries.\nI did this process manually and added this code to main.py to initialize the site-pack...
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "pkg_resources", "python", "setuptools" ]
stackoverflow_0000599205_google_app_engine_pkg_resources_python_setuptools.txt
Q: How can I deal with python eggs for multiple platforms in one location? We have a common python installation for all of our systems in order to ensure every system has the same python installation and to ease configuration issues. This installation is located on a shared drive. We also have multiple platforms th...
How can I deal with python eggs for multiple platforms in one location?
We have a common python installation for all of our systems in order to ensure every system has the same python installation and to ease configuration issues. This installation is located on a shared drive. We also have multiple platforms that share this installation. We get around conflicting platform-specific file...
[ "Try virtualenv ... http://pypi.python.org/pypi/virtualenv ... helps you create isolated environment with it's own python interpreter + site_packages folder. Thus you never have any conflicts with packages installed in say local path.\n", "What I ended up going with was manually moving the platform-dependent egg ...
[ 2, 2, 1, 0 ]
[]
[]
[ "easy_install", "pkg_resources", "python" ]
stackoverflow_0001903653_easy_install_pkg_resources_python.txt
Q: easy_install -f vs easy_install -i This is related to this question I asked a while back. The end game is I want to be able to install my package "identity.model" and all dependencies. like so... $ easy_install -f http://eggs.sadphaeton.com identity.model Searching for identity.model Reading http://eggs.sadphaeto...
easy_install -f vs easy_install -i
This is related to this question I asked a while back. The end game is I want to be able to install my package "identity.model" and all dependencies. like so... $ easy_install -f http://eggs.sadphaeton.com identity.model Searching for identity.model Reading http://eggs.sadphaeton.com Reading http://pypi.python.org/sim...
[ "-f will take the url you give it, and look there for packages, as well as on PyPI. An example of such a page is http://dist.plone.org/release/3.3.1/ As you see, this is a list of distribution files.\nWith -i you define the main index page. It defaults to http://pypi.python.org/simple/ As you see, the index page is...
[ 3, 0, 0 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0001585077_python_setuptools.txt
Q: Can I write browser plugins with Python? I'm thinking about writing a browser plugin, but I don't know any C. Can I write browser plugins with Java or Python? I was thinking... All those websites store cookies on my browser to identify me. If I wrote a plugin that would supply a browser GUID in the http headers, w...
Can I write browser plugins with Python?
I'm thinking about writing a browser plugin, but I don't know any C. Can I write browser plugins with Java or Python? I was thinking... All those websites store cookies on my browser to identify me. If I wrote a plugin that would supply a browser GUID in the http headers, webservers could identify the browser. I think ...
[ "You can certainly write an ActiveX plugin for IE in Python using the win32com interfaces. But you'd have to install Python and pywin32 along with your plugin for it to work, so it'd be pretty bulky. I don't think it's going to be popular to install all that just to get a GUID.\n(Actually most people specifically d...
[ 1 ]
[]
[]
[ "browser_plugin", "java", "python" ]
stackoverflow_0002163816_browser_plugin_java_python.txt
Q: Is it not possible to define multiple constructors in Python? Possible Duplicate: What is a clean, pythonic way to have multiple constructors in Python? Is it not possible to define multiple constructors in Python, with different signatures? If not, what's the general way of getting around it? For example, let'...
Is it not possible to define multiple constructors in Python?
Possible Duplicate: What is a clean, pythonic way to have multiple constructors in Python? Is it not possible to define multiple constructors in Python, with different signatures? If not, what's the general way of getting around it? For example, let's say you wanted to define a class City. I'd like to be able to sa...
[ "Unlike Java, you cannot define multiple constructors. However, you can define a default value if one is not passed.\ndef __init__(self, city=\"Berlin\"):\n self.city = city\n\n", "If your signatures differ only in the number of arguments, using default arguments is the right way to do it. If you want to be abl...
[ 365, 305, 14, 5, 4 ]
[]
[]
[ "constructor", "python" ]
stackoverflow_0002164258_constructor_python.txt
Q: Python looping: idiomatically comparing successive items in a list I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (I'm using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering if there's some way to do it which is more cl...
Python looping: idiomatically comparing successive items in a list
I need to loop over a list of objects, comparing them like this: 0 vs. 1, 1 vs. 2, 2 vs. 3, etc. (I'm using pysvn to extract a list of diffs.) I wound up just looping over an index, but I keep wondering if there's some way to do it which is more closely idiomatic. It's Python; shouldn't I be using iterators in some cle...
[ "This is called a sliding window. There's an example in the itertools documentation that does it. Here's the code:\nfrom itertools import islice\n\ndef window(seq, n=2):\n \"Returns a sliding window (of width n) over data from the iterable\"\n \" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... ...
[ 13, 4, 3, 0 ]
[ "Reduce can be used for this purpose, if you take care to leave a copy of the current item in the result of the reducing function.\ndef diff_summarize(revisionList, nextRevision):\n '''helper function (adaptor) for using svn.diff_summarize with reduce'''\n if revisionList:\n # remove the previously tac...
[ -1 ]
[ "iterator", "loops", "python" ]
stackoverflow_0002152640_iterator_loops_python.txt
Q: Python order of execution I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code. For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's no...
Python order of execution
I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code. For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it is impleme...
[ "The only thing I can think of that may surprise some people is:\ndef test():\n try:\n return True\n finally:\n return False\n\nprint test()\n\nOutput:\nFalse\n\nfinally clauses really are executed last, even if a return statement precedes them. However, this is not specific to Python.\n", "Ex...
[ 12, 3, 3, 3, 1, 0, 0 ]
[]
[]
[ "execution", "python" ]
stackoverflow_0002162975_execution_python.txt
Q: Django and Postgres transaction rollback I have a piece of code that works in a background process which looks like from django.db import transaction try: <some code> transaction.commit() except Exception, e: print e transaction.rollback() In a test, I break <some_code> with data that causes...
Django and Postgres transaction rollback
I have a piece of code that works in a background process which looks like from django.db import transaction try: <some code> transaction.commit() except Exception, e: print e transaction.rollback() In a test, I break <some_code> with data that causes a database error. The exception is following ...
[ "Default TestCase does not know anything about transactions, you need to use TransactionalTestCase in this case.\n", "I wrote this decorator based on the transaction middleware source. Hope it helps, works perfectly for me.\ndef djangoDBManaged(func):\n def f(*args, **kwargs):\n django.db.transaction.en...
[ 6, 2 ]
[]
[]
[ "django", "postgresql", "python", "transactions" ]
stackoverflow_0002161723_django_postgresql_python_transactions.txt
Q: Custom address field in Django Model What's the common practice to represent postal addresses in Django models? Is there a library for custom model fields that include postal address fields and potentially handle validation and formatting? If no library exists, how can I write one? Can I represent a composite fi...
Custom address field in Django Model
What's the common practice to represent postal addresses in Django models? Is there a library for custom model fields that include postal address fields and potentially handle validation and formatting? If no library exists, how can I write one? Can I represent a composite field (a field that gets serialized to multi...
[ "I don't know of a single form field for addresses, but you can use localflavor to validate the input and a combo of MultiWidget and MultiValueField for creating an address field. Mine looks something like this:\nclass SplitAddressWidget(forms.MultiWidget):\n def __init__(self, attrs=None): \n widget...
[ 6 ]
[]
[]
[ "django", "django_models", "field", "python" ]
stackoverflow_0002165252_django_django_models_field_python.txt
Q: How to get progress of os.walk in python? I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along os.walk is. How would I accomplish such a thing? I tried doing startpt = root....
How to get progress of os.walk in python?
I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along os.walk is. How would I accomplish such a thing? I tried doing startpt = root.count(os.sep) and gauging off of that but that ...
[ "It depends!\nIf the files and directories are distributed more or less evenly you could show rough process by assuming every toplevel directory is going to take the same amount of time. But if they are not distributed evenly you cannot find out about it cheaply. You either have to know roughly how populated every ...
[ 5, 4, 4, 2, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "os.walk", "python" ]
stackoverflow_0002164391_os.walk_python.txt
Q: In python django how do you print out an object's introspection? The list of all public methods of that object (variable and/or functions)? In python django how do you print out an object's inrospection? The list of all public methods of that object (variable and/or functions)? e.g.: def Factotum(models.Model): ...
In python django how do you print out an object's introspection? The list of all public methods of that object (variable and/or functions)?
In python django how do you print out an object's inrospection? The list of all public methods of that object (variable and/or functions)? e.g.: def Factotum(models.Model): id_ref = models.IntegerField() def calculateSeniorityFactor(): return (1000 - id_ref) * 1000 I want to be able to run a command line in...
[ "Well, things you can introspect are many, not just one.\nGood things to start with are:\n>>> help(object)\n>>> dir(object)\n>>> object.__dict__\n\nAlso take a look at the inspect module in the standard library.\nThat should make 99% of all the bases belong to you.\n", "Use inspect:\nimport inspect\ndef introspec...
[ 50, 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002164767_django_python.txt
Q: Modifying a Python class I'd like to modify all classes in Python. For example str and int and others like Person(object). I'd like to add an attribute to them and to change the way its methods works. Which is the best approach for this? Metaclasses? A: While you can do this for classes defined in python code (i...
Modifying a Python class
I'd like to modify all classes in Python. For example str and int and others like Person(object). I'd like to add an attribute to them and to change the way its methods works. Which is the best approach for this? Metaclasses?
[ "While you can do this for classes defined in python code (it will not work for builtin ones) by reassigning their attributes please do not actually do so. Just subclass and use the subclass, or write functions that take an instance of the class as argument instead of adding your own methods. Doing what you have to...
[ 3, 2, 1, 0 ]
[]
[]
[ "metaclass", "python" ]
stackoverflow_0002165200_metaclass_python.txt
Q: What would be the jquery equivalent of 'Dive into python'? I need to , well, dive into client side programming. Is there an equivalent to 'Dive into python' for jquery? I see that jquery 1.4 has been released. Does this change anything w.r.t answers? A: Well python is a language and jQuery is a framework, so I...
What would be the jquery equivalent of 'Dive into python'?
I need to , well, dive into client side programming. Is there an equivalent to 'Dive into python' for jquery? I see that jquery 1.4 has been released. Does this change anything w.r.t answers?
[ "Well python is a language and jQuery is a framework, so I'll give you one for javascript and then you can move to jQuery:\nThis book should be a required read for front end devs:\nJavaScript: The Good Parts by Douglas Crockford\nThen:\nThe jQuery Cookbook\nThis one is a pretty awesome dive into all the different ...
[ 4, 1 ]
[]
[]
[ "javascript", "jquery", "python" ]
stackoverflow_0002165811_javascript_jquery_python.txt
Q: How to make pyuic4 automatically set tabs to "MainWindow"? After adding a new label and textEdit to a grid right above these tabs, When I generate the ui.py file with pyuic4, It generates the the following lines for many different tabs which gives errors about not having enough arguments. self.tcTab.setTabText(sel...
How to make pyuic4 automatically set tabs to "MainWindow"?
After adding a new label and textEdit to a grid right above these tabs, When I generate the ui.py file with pyuic4, It generates the the following lines for many different tabs which gives errors about not having enough arguments. self.tcTab.setTabText(self.tcTab.indexOf(self.tab_6),) However the .ui would generate t...
[ "YAY!!!!\nThe setTabText field for tabs when using designer must have something in it. It turns out the ui was using white spaces as the tabText, whenever you open designer it got rid of the white spaces. So if you set the tab text to a space again after making your changes it works.\n" ]
[ 1 ]
[]
[]
[ "designer", "pyqt", "python", "qt" ]
stackoverflow_0002120232_designer_pyqt_python_qt.txt
Q: Regex to separate Numeric from Alpha I have a bunch of strings: "10people" "5cars" .. How would I split this to? ['10','people'] ['5','cars'] It can be any amount of numbers and text. I'm thinking about writing some sort of regex - however I'm sure there's an easy way to do it in Python. A: Use the regex (\d+)...
Regex to separate Numeric from Alpha
I have a bunch of strings: "10people" "5cars" .. How would I split this to? ['10','people'] ['5','cars'] It can be any amount of numbers and text. I'm thinking about writing some sort of regex - however I'm sure there's an easy way to do it in Python.
[ "Use the regex (\\d+)([a-zA-Z]+).\nimport re\na = [\"10people\", \"5cars\"]\n[re.match('^(\\\\d+)([a-zA-Z]+)$', x).groups() for x in a]\n\nResult: \n[('10', 'people'), ('5', 'cars')]\n\n", ">>> re.findall('(\\d+|[a-zA-Z]+)', '12fgsdfg234jhfq35rjg')\n['12', 'fgsdfg', '234', 'jhfq', '35', 'rjg']\n\n", ">>> re.fin...
[ 8, 8, 3, 2, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002161519_python_regex.txt
Q: Removing html tags from a text using Regular Expression in python I'm trying to look at a html file and remove all the tags from it so that only the text is left but I'm having a problem with my regex. This is what I have so far. import urllib.request, re def test(url): html = str(urllib.request.urlopen(url).read(...
Removing html tags from a text using Regular Expression in python
I'm trying to look at a html file and remove all the tags from it so that only the text is left but I'm having a problem with my regex. This is what I have so far. import urllib.request, re def test(url): html = str(urllib.request.urlopen(url).read()) print(re.findall('<[\w\/\.\w]*>',html)) The html is a simple page w...
[ "Use BeautifulSoup. Use lxml. Do not use regular expressions to parse HTML.\n\nEdit 2010-01-29: This would be a reasonable starting point for lxml:\nfrom lxml.html import fromstring\nfrom lxml.html.clean import Cleaner\nimport requests\n\nurl = \"https://stackoverflow.com/questions/2165943/removing-html-tags-from-a...
[ 15 ]
[ "import re\npatjunk = re.compile(\"<.*?>|&nbsp;|&amp;\",re.DOTALL|re.M)\nurl=\"http://www.yahoo.com\"\ndef test(url,pat):\n html = urllib2.urlopen(url).read()\n return pat.sub(\"\",html)\n\nprint test(url,patjunk)\n\n" ]
[ -1 ]
[ "html", "python", "regex", "tags" ]
stackoverflow_0002165943_html_python_regex_tags.txt
Q: Casting from a list of lists of strings to list of lists of ints in Python I'm reading some numbers from a data source that represent x- and y-coordinates that I'll be using for a TSP-esque problem. I'm new to Python, so I'm trying to make the most of lists. After reading and parsing through the data, I'm left w...
Casting from a list of lists of strings to list of lists of ints in Python
I'm reading some numbers from a data source that represent x- and y-coordinates that I'll be using for a TSP-esque problem. I'm new to Python, so I'm trying to make the most of lists. After reading and parsing through the data, I'm left with a list of string lists that looks like this: [['565.0', '575.0'], ['1215.0'...
[ "x = [['565.0', '575.0'], ['1215.0', '245.0'], ['1740.0', '245.0']]\nx = [[int(float(j)) for j in i] for i in x]\n\n" ]
[ 21 ]
[]
[]
[ "python" ]
stackoverflow_0002166577_python.txt
Q: Integer Field Math in Django from django.db import models from django.contrib.auth.models import User class Product(models.Model): name = models.CharField(max_length = 127) description = models.TextField() code = models.CharField(max_length = 30) lot_no = models.CharField(max_length = 30) inventory = models.Integ...
Integer Field Math in Django
from django.db import models from django.contrib.auth.models import User class Product(models.Model): name = models.CharField(max_length = 127) description = models.TextField() code = models.CharField(max_length = 30) lot_no = models.CharField(max_length = 30) inventory = models.IntegerField() commited = models.Intege...
[ "Try overriding the save method on the model: \ndef save(self, *args, **kwargs):\n \"update number available on save\"\n self.available = self.inventory - self.committed\n\n super(Product, self).save(*args, **kwargs)\n\nYou could also put logic in there that would do something if self.available became nega...
[ 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002136928_django_python.txt
Q: How would you further lock down a Google App Engine app executing untrusted code? We are currently using Google App Engine to evaluate solutions to Python problems submitted by students. We have moved all of the untrusted code execution off to a separate GAE application that doesn't use the datastore. Everything s...
How would you further lock down a Google App Engine app executing untrusted code?
We are currently using Google App Engine to evaluate solutions to Python problems submitted by students. We have moved all of the untrusted code execution off to a separate GAE application that doesn't use the datastore. Everything seems to be working fine for the 50+ problems we have uploaded, but I'm curious what sec...
[ "Look at shell.appspot.com's source -- it actually even uses the datastore (for session persistence). At the core it's basically just doing a simple exec just like you are -- there are other refinements, but nothing special relative to \"lockdown\" of the untrusted code. Presumably the Google engineers (in the Ap...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002166650_google_app_engine_python.txt
Q: In Python, how do you programmatically execute unit tests stored in a string? The following code is used to execute doctests in a Google App Engine app. How would you do this for tests written as unit test asserts rather than as doctests? #The solution and tests are untrusted code passed in to the GAE app. solut...
In Python, how do you programmatically execute unit tests stored in a string?
The following code is used to execute doctests in a Google App Engine app. How would you do this for tests written as unit test asserts rather than as doctests? #The solution and tests are untrusted code passed in to the GAE app. solution = 'b=5' unittest = 'assertEqual(b, 5)' #Here is the doctest version as a refer...
[ "Methods of a class, such as unittest.TestCase.assertEqual, don't execute outside of the context provided by an instance of that class. So, a string like your 'assertEqual(b, 5)' is really a very, VERY bad case -- note that the string as written will never execute properly (you need to prepend, at the very least, ...
[ 3 ]
[]
[]
[ "python", "testing" ]
stackoverflow_0002166761_python_testing.txt
Q: pygame saving audio files How can I convert a .wav file to some other format such as .mp3 in pygame? Update: Why not Gstreamer or Pygame: I want to use native Windows environment to install a package that can do this (i.e. don't want to install cygwin). I am searching for a package which has a binary installer a...
pygame saving audio files
How can I convert a .wav file to some other format such as .mp3 in pygame? Update: Why not Gstreamer or Pygame: I want to use native Windows environment to install a package that can do this (i.e. don't want to install cygwin). I am searching for a package which has a binary installer available for windows (with Pyth...
[ "The answer is you can not do this using PyGame. \nI found out GStreamer installer for windows from GStreamer-Winbuild project: http://www.gstreamer-winbuild.ylatuya.es/doku.php So, I will be using Gstreamer framework for audio handling.\n" ]
[ 0 ]
[ "Pygame is an SDL wrapper. Not a multimedia framework. Why do you want to do audio format conversions in Pygame? Can't you use something else like maybe the gstreamer bindings for Python?\n" ]
[ -2 ]
[ "pygame", "python" ]
stackoverflow_0002141315_pygame_python.txt
Q: install python Mysql module I've just installed python 2.6 on my win7 machine. Now I tried to install mysqldb. But when run "python setup.py install" C:\MySQL-python-1.2.3c1>python setup.py install Traceback (most recent call last): File "setup.py", line 15, in <module> metadata, options = get_config() ...
install python Mysql module
I've just installed python 2.6 on my win7 machine. Now I tried to install mysqldb. But when run "python setup.py install" C:\MySQL-python-1.2.3c1>python setup.py install Traceback (most recent call last): File "setup.py", line 15, in <module> metadata, options = get_config() File "C:\MySQL-python-1.2.3c1\s...
[ "I have compiled MySQLdb 1.2.3c1 once with python26, you could find it here\n", "Are you running from an Administrator Mode command prompt? Also, do you have the MySQL headers available for the compiler to link against?\nIf you are just an end-user, you will probably find it easier to use a pre-built MySQLdb bina...
[ 4, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002081240_mysql_python.txt
Q: After handshake of websocket, chrome disconnects. Is this due to domain mismatch? Or Chrome bug? I made my own simple WebSocket server in Python but Chrome 4.0.249.78 dev (36714) ALWAYS disconnects after the handshake. To make sure it wasn't my code I used the WebSocket server found at https://stackoverflow.com/qu...
After handshake of websocket, chrome disconnects. Is this due to domain mismatch? Or Chrome bug?
I made my own simple WebSocket server in Python but Chrome 4.0.249.78 dev (36714) ALWAYS disconnects after the handshake. To make sure it wasn't my code I used the WebSocket server found at https://stackoverflow.com/questions/2153294?tab=newest#tab-top to test it and got the same result (below). listening... connection...
[ "I upgraded Chrome to a new build (4.0.302.3 dev) and now I am getting proper javascript errors in the console. It was indeed a domain mismatch error.\nTo anyone else getting this same issue, make sure to update your browser first and then check your urls.\n" ]
[ 2 ]
[]
[]
[ "google_chrome", "javascript", "python", "websocket" ]
stackoverflow_0002165308_google_chrome_javascript_python_websocket.txt
Q: Can I get my instance of mechanize.Browser to stay on the same page after calling b.form.submit()? In Python's mechanize.Browser module, when you submit a form the browser instance goes to that page. For this one request, I don't want that; I want it just to stay on the page it's currently on and give me the respo...
Can I get my instance of mechanize.Browser to stay on the same page after calling b.form.submit()?
In Python's mechanize.Browser module, when you submit a form the browser instance goes to that page. For this one request, I don't want that; I want it just to stay on the page it's currently on and give me the response in another object (for looping purposes). Anyone know a quick to do this? EDIT: Hmm, so I have this ...
[ "The answer to my immediate question in the headline is yes, with mechanize.Browser.open_novisit(). It works just like open(), but it doesn't change the state of the Browser instance -- that is, it will retrieve the page, and your Browser object will stay where it was.\n" ]
[ 7 ]
[]
[]
[ "mechanize", "python", "screen_scraping" ]
stackoverflow_0002152098_mechanize_python_screen_scraping.txt
Q: Alternative ways to browse the python api Is it just me, or the python standard library documentation is extremely difficult to browse through? http://docs.python.org/3.1/library/index.html http://docs.python.org/3.1/modindex.html Java has its brilliant Javadocs, Ruby has its helpful Ruby-Docs, only in python I ...
Alternative ways to browse the python api
Is it just me, or the python standard library documentation is extremely difficult to browse through? http://docs.python.org/3.1/library/index.html http://docs.python.org/3.1/modindex.html Java has its brilliant Javadocs, Ruby has its helpful Ruby-Docs, only in python I cannot find a good way to navigate through the ...
[ "I usually use the built-in pydoc, if you are on windows it should be called Module Docs if you are on linux use pydoc -p 8000 and connect through browser.\n", "pydoc from the command line, help() from the interactive interpreter prompt.\n", "pydoc -p 8080\nThe python community is semi-hostile to automatically ...
[ 9, 3, 3, 2, 0, 0 ]
[]
[]
[ "documentation", "python", "standard_library" ]
stackoverflow_0002131419_documentation_python_standard_library.txt
Q: What is the use of the "-O" flag for running Python? Python can run scripts in optimized mode (python -O) which turns off debugs, removes assert statements, and IIRC it also removes docstrings. However, I have not seen it used. Is python -O actually used? If so, what for? A: python -O does the following currentl...
What is the use of the "-O" flag for running Python?
Python can run scripts in optimized mode (python -O) which turns off debugs, removes assert statements, and IIRC it also removes docstrings. However, I have not seen it used. Is python -O actually used? If so, what for?
[ "python -O does the following currently:\n\ncompletely ignores asserts\nsets the special builtin name __debug__ to False (which by default is True)\n\nand when called as python -OO\n\nremoves docstrings from the code\n\nI don't know why everyone forgets to mention the __debug__ issue; perhaps it is because I'm the ...
[ 62, 52, 7, 3 ]
[]
[]
[ "assert", "assertion", "python" ]
stackoverflow_0002055557_assert_assertion_python.txt
Q: pubDate RSS parsing weirdness with Beautifulsoup/Python I'm trying to parse an RSS/Podcast feed using Beautifulsoup and everything is working nicely except I can't seem to parse the 'pubDate' field. data = urllib2.urlopen("http://www.democracynow.org/podcast.xml") dom = BeautifulStoneSoup(data, fromEncoding='utf-8...
pubDate RSS parsing weirdness with Beautifulsoup/Python
I'm trying to parse an RSS/Podcast feed using Beautifulsoup and everything is working nicely except I can't seem to parse the 'pubDate' field. data = urllib2.urlopen("http://www.democracynow.org/podcast.xml") dom = BeautifulStoneSoup(data, fromEncoding='utf-8') items = dom.findAll('item'); for item in items: title...
[ "It works with item.find('pubdate').string.strip().\nWhy don't you use feedparser ?\n" ]
[ 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002168516_beautifulsoup_python.txt
Q: python string split I am trying to recognise user typed strings such as "exit" or "add number" using this: command, data = input('>').split(" ", 1) It works for two word input, but not one word of input ("need more than 1 value to unpack"). What is the best way of accepting both one/two word inputs? A: This is...
python string split
I am trying to recognise user typed strings such as "exit" or "add number" using this: command, data = input('>').split(" ", 1) It works for two word input, but not one word of input ("need more than 1 value to unpack"). What is the best way of accepting both one/two word inputs?
[ "This is what partition is for:\ncommand, _, data = raw_input('>').partition(\" \")\n\nIf only one word was specified, data will be assigned an empty string.\n", "I am certain that someone is going to come up with a \"Pythonic\" solution, but what ever happened to just accepting it as a list and checking it after...
[ 3, 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002168522_python.txt
Q: How can I pickle suds results? To avoid repeatedly accessing a SOAP server during development, I'm trying to cache the results so I can run the rest of my code without querying the server each time. With the code below I get a PicklingError: Can't pickle <class suds.sudsobject.AdvertiserSearchResponse at 0x0342406...
How can I pickle suds results?
To avoid repeatedly accessing a SOAP server during development, I'm trying to cache the results so I can run the rest of my code without querying the server each time. With the code below I get a PicklingError: Can't pickle <class suds.sudsobject.AdvertiserSearchResponse at 0x03424060>: it's not found as suds.sudsobjec...
[ "As the error message you're currently getting is trying to tell you, you're trying to pickle instances that are not picklable (in the ancient legacy pickle protocol you're now using) because their class defines __slots__ but not a __getstate__ method.\nHowever, even altering their class would not help because then...
[ 9, 3 ]
[]
[]
[ "pickle", "python", "soap", "suds" ]
stackoverflow_0002167894_pickle_python_soap_suds.txt
Q: What vim plugins mix results in this interface I saw this VIM UI and thought it was awesome and now I want it. Anyone know what plugins the author is using? http://werkzeug.pocoo.org/wiki30/files/wiki30.mp4 A: A bit dated, but this is his blog post that I was referring to: Vim as Development Environment
What vim plugins mix results in this interface
I saw this VIM UI and thought it was awesome and now I want it. Anyone know what plugins the author is using? http://werkzeug.pocoo.org/wiki30/files/wiki30.mp4
[ "A bit dated, but this is his blog post that I was referring to: Vim as Development Environment\n" ]
[ 0 ]
[]
[]
[ "ide", "plugins", "python", "vim" ]
stackoverflow_0002166201_ide_plugins_python_vim.txt
Q: How can I add a cookie to an existing cookielib CookieJar instance in Python? I have a CookieJar that's being used with Mechanize that I want to add a cookie to. How can I go about doing this? make_cookie() and set_cookie() weren't clear enough for me. br = mechanize.Browser() cj = cookielib.LWPCookieJar() br.set_...
How can I add a cookie to an existing cookielib CookieJar instance in Python?
I have a CookieJar that's being used with Mechanize that I want to add a cookie to. How can I go about doing this? make_cookie() and set_cookie() weren't clear enough for me. br = mechanize.Browser() cj = cookielib.LWPCookieJar() br.set_cookiejar(cj)
[ "I managed to figure this out:\nimport mechanize\nimport cookielib\n\nbr = mechanize.Browser()\ncj = cookielib.LWPCookieJar()\nbr.set_cookiejar(cj)\nck = cookielib.Cookie(version=0, name='Name', value='1', port=None, port_specified=False, domain='www.example.com', domain_specified=False, domain_initial_dot=False, p...
[ 37 ]
[]
[]
[ "cookiejar", "cookielib", "cookies", "mechanize", "python" ]
stackoverflow_0002169281_cookiejar_cookielib_cookies_mechanize_python.txt
Q: Ignoring case, punctuation, and whitespace in Strings What is the most efficient way of ignoring case, punctuation, and whitespace in strings? These strings should be divided into words instead of characters should ignore the aforementioned details on comparisons, and slices of these word-strings should be as effi...
Ignoring case, punctuation, and whitespace in Strings
What is the most efficient way of ignoring case, punctuation, and whitespace in strings? These strings should be divided into words instead of characters should ignore the aforementioned details on comparisons, and slices of these word-strings should be as efficient as possible with speed in mind. I was going to use ca...
[ "If you want iteration on a String instance to iterate on its self.__string, as your __iter__ method indicates, the only sensible choice for length is also to return the length of __string -- it would be truly peculiar if len(x) and sum(1 for _ in x) resulted in different values.\nI have to admit I don't understand...
[ 2, 2 ]
[]
[]
[ "filter", "python", "slice", "state" ]
stackoverflow_0002169170_filter_python_slice_state.txt
Q: Importing _mysql in MySQLdb Why is _mysql in the MySQLdb module a C file? When the module tries to import it, I get an import error. What should I do? A: It's the adaptor that sits between the Python MySQLdb module and the C libmysqlclient library. One of the most common reasons for it not loading is that the ap...
Importing _mysql in MySQLdb
Why is _mysql in the MySQLdb module a C file? When the module tries to import it, I get an import error. What should I do?
[ "It's the adaptor that sits between the Python MySQLdb module and the C libmysqlclient library. One of the most common reasons for it not loading is that the appropriate libmysqlclient library is not in place.\n", "Edit: This might be the answer to your question.\nWhen I try to import _mysql, I get no error:\nimp...
[ 0, 0 ]
[]
[]
[ "c", "mysql", "python" ]
stackoverflow_0002169449_c_mysql_python.txt
Q: how to write a file correctly after editing say i encrypt a .doc (or any other type) file and i decrypt it later. however, i cant open it because during the decryption process, [null]s and [DC1] and other highlighted chars were not put back into the file since they are not part of the ASCII characters. how are the...
how to write a file correctly after editing
say i encrypt a .doc (or any other type) file and i decrypt it later. however, i cant open it because during the decryption process, [null]s and [DC1] and other highlighted chars were not put back into the file since they are not part of the ASCII characters. how are they written in other programs that compress/encrypt...
[ "Nulls and DC1's and so on are definitely part of the ASCII character set, so I don't know what you're talking about. So, for example, consider...:\n>>> import pyDes\n>>> f = open('afile', 'w')\n>>> f.write('Nel mezzo del cammin di nostra vita\\n')\n>>> f.close()\n>>> data = open('afile').read()\n>>> encrypted = py...
[ 4, 1 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0002169445_encryption_python.txt
Q: Polymorphism - adding to existing methods while overwriting them I want to be able to subclass a class, and define __init__ but still run the old __init__ as well. To illustrate, say I have the following classes: class A(object): def __init__(self): self.var1 = 1 class B(A): def __init__(self) ...
Polymorphism - adding to existing methods while overwriting them
I want to be able to subclass a class, and define __init__ but still run the old __init__ as well. To illustrate, say I have the following classes: class A(object): def __init__(self): self.var1 = 1 class B(A): def __init__(self) self.var2 = 2 doInitForA() And I want to be able to do t...
[ "replace \ndoInitForA()\n\nwith\nsuper(b, self).__init__()\n\n", "You might want to look at this question: Chain-calling parent constructors in python, specifically use the super(b, self).__init__() method.\n", "Either call a.__init__(self) or derive a from object and use super().\n", "class a:\n def __ini...
[ 6, 3, 0, 0, 0 ]
[]
[]
[ "methods", "polymorphism", "python" ]
stackoverflow_0002169947_methods_polymorphism_python.txt
Q: assigning points to bins What is a good way to bin numerical values into a certain range? For example, suppose I have a list of values and I want to bin them into N bins by their range. Right now, I do something like this: from scipy import * num_bins = 3 # number of bins to use values = # some array of integers....
assigning points to bins
What is a good way to bin numerical values into a certain range? For example, suppose I have a list of values and I want to bin them into N bins by their range. Right now, I do something like this: from scipy import * num_bins = 3 # number of bins to use values = # some array of integers... min_val = min(values) - 1 m...
[ "numpy.histogram() does exactly what you want.\nThe function signature is:\nnumpy.histogram(a, bins=10, range=None, normed=False, weights=None, new=None)\n\nWe're mostly interested in a and bins. a is the input data that needs to be binned. bins can be a number of bins (your num_bins), or it can be a sequence of ...
[ 27, 1 ]
[]
[]
[ "binning", "numpy", "python", "scipy" ]
stackoverflow_0002144443_binning_numpy_python_scipy.txt
Q: Python2.6 and Snow Leopard. Problem installing appscript (and MANY other packages) I've been having nothing but trouble with python2.6 and Snow Leopard. One major problem is 32 vs 64-bit libraries. The other manifests itself like this: tppllc-mbp15$ sudo easy_install-2.6 appscript Searching for appscript Reading h...
Python2.6 and Snow Leopard. Problem installing appscript (and MANY other packages)
I've been having nothing but trouble with python2.6 and Snow Leopard. One major problem is 32 vs 64-bit libraries. The other manifests itself like this: tppllc-mbp15$ sudo easy_install-2.6 appscript Searching for appscript Reading http://pypi.python.org/simple/appscript/ Reading http://appscript.sourceforge.net Best ma...
[ "It appears you have likely installed a python 2.6 from python.org or some other 3rd-party installer. The python.org python's are currently built only as 32-bit (i386 and ppc) and are compatible with OS X 10.3 through 10.6. To do that, they are built with the 10.4u SDK which is available via the 10.6 Xcode instal...
[ 1 ]
[]
[]
[ "macos", "osx_snow_leopard", "python" ]
stackoverflow_0002169987_macos_osx_snow_leopard_python.txt
Q: OpenGL frame buffer slow and spontaneously stalls. Can even cause a system crash when used extensively Apparently frame buffers are fast and the best way to render offscreen to textures or to simply pre-create things. My game however is not liking them at all. In the current code frame buffers are used often, some...
OpenGL frame buffer slow and spontaneously stalls. Can even cause a system crash when used extensively
Apparently frame buffers are fast and the best way to render offscreen to textures or to simply pre-create things. My game however is not liking them at all. In the current code frame buffers are used often, sometimes each frame, several times. When used the game begins to slow down but not instantly. It seems to take ...
[ "I haven't worked with OpenGL for about 14 years so I'm not much help with that. I'm just looking at the Python code. There's a few things you can do to clean the code up, like use \".width\" instead of \".surface_size[0]\". You do have a get_width(), but descriptors are your friends. You also have checks for \"if ...
[ 0 ]
[]
[]
[ "fbo", "framebuffer", "opengl", "performance", "python" ]
stackoverflow_0002169868_fbo_framebuffer_opengl_performance_python.txt
Q: Python: Analysis on CSV files 100,000 lines x 40 columns I have about a 100 csv files each 100,000 x 40 rows columns. I'd like to do some statistical analysis on it, pull out some sample data, plot general trends, do variance and R-square analysis, and plot some spectra diagrams. For now, I'm considering numpy for...
Python: Analysis on CSV files 100,000 lines x 40 columns
I have about a 100 csv files each 100,000 x 40 rows columns. I'd like to do some statistical analysis on it, pull out some sample data, plot general trends, do variance and R-square analysis, and plot some spectra diagrams. For now, I'm considering numpy for the analysis. I was wondering what issues should I expect wit...
[ "I've found that Python + CSV is probably the fastest, and simplest way to do some kinds of statistical processing. \nWe do a fair amount of reformatting and correcting for odd data errors, so Python helps us.\nThe availability of Python's functional programming features makes this particularly simple. You can do...
[ 13, 2, 1, 1, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002142415_numpy_python.txt
Q: List multiplication I have a list L = [a, b, c] and I want to generate a list of tuples : [(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...] I tried doing L * L but it didn't work. Can someone tell me how to get this in python. A: You can do it with a list comprehension: [ (x,y) for x in L for y in L] edit You can...
List multiplication
I have a list L = [a, b, c] and I want to generate a list of tuples : [(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...] I tried doing L * L but it didn't work. Can someone tell me how to get this in python.
[ "You can do it with a list comprehension:\n[ (x,y) for x in L for y in L]\n\nedit\nYou can also use itertools.product as others have suggested, but only if you are using 2.6 onwards. The list comprehension will work will all versions of Python from 2.0. If you do use itertools.product bear in mind that it returns...
[ 22, 15, 7, 3, 0, 0, 0 ]
[]
[]
[ "cartesian_product", "list", "python" ]
stackoverflow_0002169838_cartesian_product_list_python.txt
Q: Getting Django comments to be able to use bold and italic style So I'm trying to get rich text to work for the cheeserater program where I added a commenting system using the tinyMCE editor in the textarea. This is what it looks like: <table><td align=left> {% get_comment_list for package as comment_list %} {% f...
Getting Django comments to be able to use bold and italic style
So I'm trying to get rich text to work for the cheeserater program where I added a commenting system using the tinyMCE editor in the textarea. This is what it looks like: <table><td align=left> {% get_comment_list for package as comment_list %} {% for comment in comment_list %} {{ comment.comment|safe }}<br> {% en...
[ "Those tags work fine here. Check that you don't have a stylesheet causing those tags to use an unadorned style.\n" ]
[ 1 ]
[]
[]
[ "django", "html", "python", "tinymce" ]
stackoverflow_0002170111_django_html_python_tinymce.txt
Q: Python: Optimizing a tree evaluator I know tree is a well studied structure. I'm writing a program that randomly generates many expression trees and then sorts and selects by a fitness attribute. I have a class MakeTreeInOrder() that turns the tree into a string that 'eval' can evaluate. but it gets called many ...
Python: Optimizing a tree evaluator
I know tree is a well studied structure. I'm writing a program that randomly generates many expression trees and then sorts and selects by a fitness attribute. I have a class MakeTreeInOrder() that turns the tree into a string that 'eval' can evaluate. but it gets called many many times, and should be optimized for t...
[ "Adding a touch of object orientation here makes things simpler. Have subclasses of Node for each thing in your tree, and use an 'eval' method to evaluate them.\nimport random\n\nclass ArithmeticOperatorNode(object):\n def __init__(self, operator, *args):\n self.operator = operator\n self.children ...
[ 3, 1 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0002169682_optimization_python.txt
Q: Why (dictionary.keys()).sort() is not working in python? I'm new to Python and can't understand why a thing like this does not work. I can't find the issue raised elsewhere either. toto = {'a':1, 'c':2 , 'b':3} toto.keys().sort() #does not work (yields none) (toto.keys()).sort() #does not work (y...
Why (dictionary.keys()).sort() is not working in python?
I'm new to Python and can't understand why a thing like this does not work. I can't find the issue raised elsewhere either. toto = {'a':1, 'c':2 , 'b':3} toto.keys().sort() #does not work (yields none) (toto.keys()).sort() #does not work (yields none) eval('toto.keys()').sort() #does not work (yield...
[ "sort() sorts the list in place. It returns None to prevent you from thinking that it's leaving the original list alone and returning a sorted copy of it.\n", "sorted(toto.keys())\n\nShould do what you want. The sort method you're using sorts in place and returns None.\n", "sort() method sort in place, returni...
[ 6, 6, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0002170632_python_sorting.txt
Q: Pylons and AuthKit OpenID problem I have troubles setting up the support for openID authentication, using authkit and pylons. I set up everything as described in the cookbook, but still get the following error: File "/usr/lib/python2.6/dist-packages/authkit/authenticate/open_id.py", line 480, in __call__ ret...
Pylons and AuthKit OpenID problem
I have troubles setting up the support for openID authentication, using authkit and pylons. I set up everything as described in the cookbook, but still get the following error: File "/usr/lib/python2.6/dist-packages/authkit/authenticate/open_id.py", line 480, in __call__ return self.app(environ, start_response) ...
[ "Take this line in your middleware.py:\napp = authkit.authenticate.middleware(app, app_conf)\n\nAnd move it immediately below this line:\napp = PylonsApp()\n\n" ]
[ 4 ]
[]
[]
[ "authkit", "openid", "pylons", "python" ]
stackoverflow_0002095120_authkit_openid_pylons_python.txt
Q: Python __init__ argument problem I have some trouble understanding what happens with class init arguments that are lists like: class A(object): def __init__(self, argument=[]): self.argument = argument[:] or: def __init__(self,argument=None): self.arguments = arguments or [] or: def __ini...
Python __init__ argument problem
I have some trouble understanding what happens with class init arguments that are lists like: class A(object): def __init__(self, argument=[]): self.argument = argument[:] or: def __init__(self,argument=None): self.arguments = arguments or [] or: def __init__(self, argument=[]): self.arg...
[ "This is a well known python gotcha.\nBasically, the default for that argument is created when the method is first defined, and since it is a mutable object (in this case, a list), it just referes to the same object even after it has changed, and even in subsequent calls to the method.\nThe usual way to deal with c...
[ 6, 4, 1 ]
[]
[]
[ "class", "equality", "identity", "list", "python" ]
stackoverflow_0002170684_class_equality_identity_list_python.txt
Q: Using Python Reg Exp to read data from file I'm having trouble using python reg exp to read data from a file. The file has data I want and some info I'm not interested in. An example of the info I'm interested in is below. The number of rows will vary FREQ VM(VOUT) 1.000E+00 4.760E+01 1.002E+00 4.749...
Using Python Reg Exp to read data from file
I'm having trouble using python reg exp to read data from a file. The file has data I want and some info I'm not interested in. An example of the info I'm interested in is below. The number of rows will vary FREQ VM(VOUT) 1.000E+00 4.760E+01 1.002E+00 4.749E+01 Y I want to create a list of tuples like: [...
[ "I think this will get you what you want. As long as the file is consistent.\nfrom csv import reader\nwith open('file') as f:\n listoftuples = [(float(row[0]), float(row[1])) \n for row in reader(f, delimiter=' ') \n if row and row[0] != 'FREQ']\n\nIf you want it to break at 'Y',...
[ 3, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002170461_python_regex.txt
Q: Trouble with MySQL UPDATE syntax with the module mysqldb in Python I am attempting to execute the following query via the mysqldb module in python: for i in self.p.parameter_type: cursor.execute("""UPDATE parameters SET %s = %s WHERE parameter_set_name = %s""" % (i, float(getattr(self.p, i)), se...
Trouble with MySQL UPDATE syntax with the module mysqldb in Python
I am attempting to execute the following query via the mysqldb module in python: for i in self.p.parameter_type: cursor.execute("""UPDATE parameters SET %s = %s WHERE parameter_set_name = %s""" % (i, float(getattr(self.p, i)), self.list_box_parameter.GetStringSelection())) I keep getting the error: "...
[ "i see now, i think you need to enclose parameter_set_name = %s in quotes such as:\nparameter_set_name = \"%s\"\n\notherwise it's trying to acces column M1\nso:\ncursor.execute(\"\"\"UPDATE parameters SET %s = %s WHERE parameter_set_name = \\\"%s\\\" \"\"\" % (i, float(getattr(self.p, i)), self.list_box_parameter.G...
[ 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002171072_mysql_python.txt
Q: no module names _mysql; where is _mysql import MySQLdb and traceback: Traceback (most recent call last): File "D:\zjm_code\sphinx_test\a.py", line 1, in <module> import MySQLdb File "D:\zjm_code\sphinx_test\MySQLdb\__init__.py", line 19, in <module> import _mysql ImportError: No module named _mysql ...
no module names _mysql; where is _mysql
import MySQLdb and traceback: Traceback (most recent call last): File "D:\zjm_code\sphinx_test\a.py", line 1, in <module> import MySQLdb File "D:\zjm_code\sphinx_test\MySQLdb\__init__.py", line 19, in <module> import _mysql ImportError: No module named _mysql
[ "You need to install MySQLdb correctly. It consists of the python module and platform-dependent library (_mysql.dll in your case). Use the win32 installer from the project page instead of installing just by unpacking sources.\n" ]
[ 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0002171078_mysql_python.txt
Q: Python - Display string containing entity references as normal text I have a Python string "&#039;&#039;Grassmere&#039;&#039;" as retrieved from a website. I would like to have the &#039; displayed as the correct ascii symbol (') but for some reason python insists on just printing the ascii code. A: Batteries ar...
Python - Display string containing entity references as normal text
I have a Python string "&#039;&#039;Grassmere&#039;&#039;" as retrieved from a website. I would like to have the &#039; displayed as the correct ascii symbol (') but for some reason python insists on just printing the ascii code.
[ "Batteries are included for this one\n>>> import xmllib\n>>> X=xmllib.XMLParser()\n>>> X.translate_references(\"&#039;&#039;Grassmere&#039;&#039;\")\n\"''Grassmere''\"\n\n", "Or without additional modules:\nre.sub(\"&#(\\d+);\", lambda m: chr(int(m.group(1))), \"&#039;&#039;Grassmere&#039;&#039;\")\n\n" ]
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002171084_python.txt
Q: Django and NoneType object is not callable I have such model: class Body(models.Model): point = models.TextField() description = models.TextField(blank = True) order = models.IntegerField(default = 0, blank = True) When I am adding in django admin interface a new record I am getting 'NoneType' object...
Django and NoneType object is not callable
I have such model: class Body(models.Model): point = models.TextField() description = models.TextField(blank = True) order = models.IntegerField(default = 0, blank = True) When I am adding in django admin interface a new record I am getting 'NoneType' object is not callable with TemplateSyntaxError messag...
[ "I've found that \norder = models.IntegerField(default = 0, blank = True)\n\nwas the reason of my problem. When I've changed 'order' name to something else I've got my problem fixed. :)\n" ]
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002170303_django_python.txt
Q: where is SeparatedValuesField in my code, i used sphinx from django.db import models from djangosphinx import SphinxSearch # A sample model from iBegin class City(models.Model): name = models.CharField(max_length=32) aliases = SeparatedValuesField(blank=True, null=True)#<-------this ...
where is SeparatedValuesField in my code, i used sphinx
from django.db import models from djangosphinx import SphinxSearch # A sample model from iBegin class City(models.Model): name = models.CharField(max_length=32) aliases = SeparatedValuesField(blank=True, null=True)#<-------this slug = models.SlugField(blank=True) country ...
[ "Google finds this page, from the same (non-responsive here) blog.\n", "It seems to be a user-defined custom form field, one possible definition is on Django Snippets: http://www.djangosnippets.org/snippets/497/\nThe blog doesn't seem to be available right now, but perhaps the author has mentioned or used this sn...
[ 0, 0 ]
[]
[]
[ "django", "django_sphinx", "python" ]
stackoverflow_0002171314_django_django_sphinx_python.txt
Q: What Is The Best Way To Play Audio Through Qt? I am building an application in pyQt4 and I want it to be able to play audio files. I was considering doing this through pyMedia as I could not get anywhere with the documentation, although the QAudio classes did initially look promising. It is important that the solu...
What Is The Best Way To Play Audio Through Qt?
I am building an application in pyQt4 and I want it to be able to play audio files. I was considering doing this through pyMedia as I could not get anywhere with the documentation, although the QAudio classes did initially look promising. It is important that the solution be cross-platform. Does anyone have any suggest...
[ "As alex said, Phonon looks like your best bet because you can use it with Pyqt. You can find lots of examples of using phonon using google. This one, http://forum.kde.org/viewtopic.php?f=14&t=84275, for example is a command line tool to play audio using phonon. You might also want to take a look at the QSound clas...
[ 2, 1 ]
[]
[]
[ "audio", "pyqt4", "python" ]
stackoverflow_0002171232_audio_pyqt4_python.txt
Q: How to change caps lock status without key press I am using a python program that is activate when pressing Caps Lock key and I want to be able to turn on/off the caps lock status when the program is active. I tried to send keys with virtkey but it obviously don't work since the keys just activate the app and don'...
How to change caps lock status without key press
I am using a python program that is activate when pressing Caps Lock key and I want to be able to turn on/off the caps lock status when the program is active. I tried to send keys with virtkey but it obviously don't work since the keys just activate the app and don't change the caps lock status. So what is the best way...
[ "On Linux:\nimport fcntl\nimport os\n\nKDSETLED = 0x4B32\n\nconsole_fd = os.open('/dev/console', os.O_NOCTTY)\n\n# Turn on caps lock\nfcntl.ioctl(console_fd, KDSETLED, 0x04)\n\n# Turn off caps lock\nfcntl.ioctl(console_fd, KDSETLED, 0)\n\nSource: Benji York - Stack Overflow: Change keyboard locks in Python\n\nOn Wi...
[ 6, 2 ]
[]
[]
[ "capslock", "keyboard", "python" ]
stackoverflow_0002171408_capslock_keyboard_python.txt