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: Redirect realtime common line output to Django HttpResponse In a long run command line execution, like uncompressing a large .zip archive, how to redirect the realtime output of unzip command to browser via Django's HttpResponse? EDIT: According to paul's suggestion, I did a search and found this question has ans...
Redirect realtime common line output to Django HttpResponse
In a long run command line execution, like uncompressing a large .zip archive, how to redirect the realtime output of unzip command to browser via Django's HttpResponse? EDIT: According to paul's suggestion, I did a search and found this question has answers to how to return a HttpResponse by using a generator. Update...
[ "The HttpResponse constructor takes either a string or an iterable.\nTo trickle content down, you can make the iterable a generator.\nProvided, of course, your middleware isn't interfering.\n" ]
[ 1 ]
[]
[]
[ "django", "httpresponse", "python" ]
stackoverflow_0001767675_django_httpresponse_python.txt
Q: Separating Business Layer Errors from API errors The title is horrible, i know; I'm terrible at titles on SO here. I'm wondering what would be the best way to present unified error responses in a webapi when errors could be raised deep inside the application. The errors deep down in the app don't know anything abo...
Separating Business Layer Errors from API errors
The title is horrible, i know; I'm terrible at titles on SO here. I'm wondering what would be the best way to present unified error responses in a webapi when errors could be raised deep inside the application. The errors deep down in the app don't know anything about the web layer (nor should they), so how can the web...
[ "I like option 1. It may be a little more verbose, but it's also very clear. \nOption 2 separates the point at which the exception is thrown from where the decision about what to do with it is made. In reality, that likely wouldn't be too much of an issue, but why split it up if you don't have to? \nI agree that ...
[ 1 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0001767504_error_handling_python.txt
Q: To understand Python's optparse Thank you for quack in pointing out the off-by-one! The following code is my first attempt in writing code with Optparse. How can you fix the following bug in getting the help by Optparse? #!/usr/bin/env python import sys import os from optparse import OptionParser e = sys.argv[1] ...
To understand Python's optparse
Thank you for quack in pointing out the off-by-one! The following code is my first attempt in writing code with Optparse. How can you fix the following bug in getting the help by Optparse? #!/usr/bin/env python import sys import os from optparse import OptionParser e = sys.argv[1] b = sys.argv[2] no = sys.argv[3] de...
[ "Constructor for class optparse.OptionParser(...) has optional named parameter 'add_help_option', which defaults to 'True'. You will have to explicitly reject default help option and message, if you want to provide your own.\n\n\nparser = OptionParser(usage, add_help_option=False)\n", "The bug is that your argume...
[ 8, 6, 1, 1 ]
[]
[]
[ "arguments", "debugging", "python" ]
stackoverflow_0001767210_arguments_debugging_python.txt
Q: BWSplitView and PyObjc I'm trying to use Brandon Walkin's BWSplitView from BWToolkit in a Cocoa PyObjc project. When I run the project I get the following error message: NSInvalidUnarchiveOperationException - *** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (BWSplitView) Does this mean ...
BWSplitView and PyObjc
I'm trying to use Brandon Walkin's BWSplitView from BWToolkit in a Cocoa PyObjc project. When I run the project I get the following error message: NSInvalidUnarchiveOperationException - *** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (BWSplitView) Does this mean his toolkit is incompatible ...
[ "I suspect that you got that error because you had a BWSplitView in a nib/xib file that you were attempting to load. In order to unarchive the objects in a nib file, the runtime needs to be able to create instances of the archived classes (e.g. BWSplitView). The exception that's being thrown is because BWSplitView ...
[ 5, 0, 0 ]
[]
[]
[ "bwtoolkit", "cocoa", "pyobjc", "python" ]
stackoverflow_0000869912_bwtoolkit_cocoa_pyobjc_python.txt
Q: How do I move data from local appengine datastore to remote datastore? I can see how to download the remote datastore to local, and how to upload a CSV to the remote app engine server as outlined here: Uploading and Downloading Data But is there a way to export my local data to a CSV that is ready for the remote u...
How do I move data from local appengine datastore to remote datastore?
I can see how to download the remote datastore to local, and how to upload a CSV to the remote app engine server as outlined here: Uploading and Downloading Data But is there a way to export my local data to a CSV that is ready for the remote upload script? Of course I could write a custom exporter, but is there no way...
[ "The answer is to use the bulkloader.py pointing at your local box:\nbulkloader.py --dump --url=http://localhost:8080/remote_api --filename=test.csv --kind=KindHere --app_id=app-id-here\nThen you can use the bulkloader.py --restore command to send it to production\n", "Look at the Python Standard Library's csv mo...
[ 5, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0001768011_google_app_engine_google_cloud_datastore_python.txt
Q: Different response by screen solutions using Django and jQuery In a thumbnail website, if I want to display 100x100 thumbs on screnn resolutions lower than 1280x1024 while display 150x150 thumbs for screens higher than 1280x1024, is the following procedure correct? Render a page frame with no thumbs by view1() On...
Different response by screen solutions using Django and jQuery
In a thumbnail website, if I want to display 100x100 thumbs on screnn resolutions lower than 1280x1024 while display 150x150 thumbs for screens higher than 1280x1024, is the following procedure correct? Render a page frame with no thumbs by view1() On page frame loaded, it detects client's screen resolution and pass i...
[ "i think you have few options\n\nJust change thumbnail at runtime based on $(window).width(); using jquery\nPass on screen resolution to django first time from client side, and later store it in session and render templates accordingly\nSometime you may get screen resolution in request headers, i am not sure though...
[ 2 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0001768179_django_jquery_python.txt
Q: Web timer using Python I would like to create web page which will print simple message x minutes to shutdown where 'x' would decrease once a minute automatically without clicking 'refresh' in web browser. The value will be counted from data downloaded from SNMP source (that is why I wanted to use Python). AFAIK I...
Web timer using Python
I would like to create web page which will print simple message x minutes to shutdown where 'x' would decrease once a minute automatically without clicking 'refresh' in web browser. The value will be counted from data downloaded from SNMP source (that is why I wanted to use Python). AFAIK I should use Javascript (am I...
[ "You could use a scripting language of your choice to load the initial time on the server side, and just serve your page with a Javascript timer that modifies the time every minute. \nYou would need to look into the setTimeout() Javascript function to manage the timer.\nSomething like this:\n<script type=\"text/jav...
[ 3, 1, 1 ]
[]
[]
[ "python", "timer" ]
stackoverflow_0001769028_python_timer.txt
Q: Python Programming Help #!/usr/bin/env python import math def primeTest(isPrime): print(' {0}=testnum'.format(testnum)) if testnum%2 == 0 and testnum != 2: #if divisible by 2 and not 2 isPrime = False print('{0} a'.format(isPrime)) print('a') else: numroot = round(math.sqrt(testnum)) i = ...
Python Programming Help
#!/usr/bin/env python import math def primeTest(isPrime): print(' {0}=testnum'.format(testnum)) if testnum%2 == 0 and testnum != 2: #if divisible by 2 and not 2 isPrime = False print('{0} a'.format(isPrime)) print('a') else: numroot = round(math.sqrt(testnum)) i = 2 while i <= numroot: ...
[ "global isPrime needs to be inside the function where you assign to isPrime.\n", "I think that, since you are declaring the isPrime global variable after the definition of primeTest(), the Python interpreter treats the isPrime within the function as a local variable.\nI was mistaken.. you have to declare it as gl...
[ 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001769278_python.txt
Q: django.utils.encoding.DjangoUnicodeDecodeError I got the following error when tried to add an entry to a Django model via generic relations. django.utils.encoding.DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 24: unexpected code byte. You passed in 'ASL/60Styles_Timeless-3_\xb8 CaLe.asl...
django.utils.encoding.DjangoUnicodeDecodeError
I got the following error when tried to add an entry to a Django model via generic relations. django.utils.encoding.DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 24: unexpected code byte. You passed in 'ASL/60Styles_Timeless-3_\xb8 CaLe.asl' (<type 'str'>) The model is like this: class MD5(...
[ "Your file system is apparently not using UTF-8 encoding:\n>>> a = 'ASL/60Styles_Timeless-3_\\xb8 CaLe.asl'\n>>> print a.decode('utf-8')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python2.5/encodings/utf_8.py\", line 16, in decode\n return codecs.utf_8_decode(...
[ 4 ]
[]
[]
[ "django", "python", "utf_8" ]
stackoverflow_0001767848_django_python_utf_8.txt
Q: Using Numpy to find average value across data sets, with some missing data I have several (10 or so) CSV-formatted data sets. Each column of a data set represents one aspect of a running system (available RAM, CPU usage, open TCP connections, and so forth). Each row contains the values for these columns at one mom...
Using Numpy to find average value across data sets, with some missing data
I have several (10 or so) CSV-formatted data sets. Each column of a data set represents one aspect of a running system (available RAM, CPU usage, open TCP connections, and so forth). Each row contains the values for these columns at one moment in time. The data sets were captured during individual runs of the same tes...
[ "Why not just us numpy's ma (masked array) module?\nmaxLen = reduce(lambda a,b : max(a, b.shape[0]),\n dSets, 0)\nall = N.ma.zeros((maxLen,)+ dSets[0].shape[1:] + (len(dSets),),\n dtype=float) # set the dtype to whatever\nall.mask = True\nfor i, set in enumerate(dSets):\n ...
[ 3, 2, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0001767865_numpy_python.txt
Q: __unicode__(self) doesn't get called by logging Long story short: # this works as expected: logging.error(my_object.__unicode__()) # this doesn't: logging.error(my_object) Same result with __str__(self). Why? EDIT: __str__ actually works. A: >>> class MyClass(object): ... def __str__(self): ... ret...
__unicode__(self) doesn't get called by logging
Long story short: # this works as expected: logging.error(my_object.__unicode__()) # this doesn't: logging.error(my_object) Same result with __str__(self). Why? EDIT: __str__ actually works.
[ ">>> class MyClass(object):\n... def __str__(self):\n... return \"foobar\"\n...\n>>> import logging\n>>> logging.error(MyClass())\nERROR:root:foobar\n\nWorks as expected?!\n", "Logging will call str() (which uses __str__() which falls back to __repr__() when it's not defined). This is because the logg...
[ 1, 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0001769759_logging_python.txt
Q: What is the best way to crawl a login based sites? I've to automate a file download activity from a website (similar to, let's say, yahoomail.com). To reach a page which has this file download link, i've to login, jump from page to page to provide some parameters like dates etc., and finally click on download link...
What is the best way to crawl a login based sites?
I've to automate a file download activity from a website (similar to, let's say, yahoomail.com). To reach a page which has this file download link, i've to login, jump from page to page to provide some parameters like dates etc., and finally click on download link. I am thinking of three approaches: Using WatIN and de...
[ "I use scrapy.org, it's a python library. It's quiet good actually. Easy to write spiders and it's very extensive in it's functionality. Scraping sites after login is available in the package.\nHere is an example of a spider that would crawl a site after authentication.\nclass LoginSpider(BaseSpider):\n domain_n...
[ 5, 3, 0, 0 ]
[]
[]
[ "c#", "html_parsing", "python", "watin", "web_crawler" ]
stackoverflow_0001768373_c#_html_parsing_python_watin_web_crawler.txt
Q: General Purpose Progressbar in Django I want to make a little web-frontend for copying (rsync) and encoding (ffmpeg) files for my Server using Django. And I want to keep track of the progress of the processes. I saw a few jquery-scripts, but they are designed to be used with uploads, and I don't know enough javasc...
General Purpose Progressbar in Django
I want to make a little web-frontend for copying (rsync) and encoding (ffmpeg) files for my Server using Django. And I want to keep track of the progress of the processes. I saw a few jquery-scripts, but they are designed to be used with uploads, and I don't know enough javascript to modify these scripts for my needs. ...
[ "See the code here http://www.djangosnippets.org/snippets/679/, it says \"upload progress for multipart forms\" but there is nothing specific to forms, you can use it anywhere with few tweaks.\nGeneral concept is:\n\nWrite a web-service which can return data(e.g. JSON) about the progress.\nOn client side use JavaSc...
[ 9 ]
[]
[]
[ "django", "javascript", "jquery", "progress_bar", "python" ]
stackoverflow_0001770205_django_javascript_jquery_progress_bar_python.txt
Q: Regex to Split 1st Colon I have a time in ISO 8601 ( 2009-11-19T19:55:00 ) which is also paired with a name commence. I'm trying to parse this into two. I'm currently up to here: import re sColon = re.compile('[:]') aString = sColon.split("commence:2009-11-19T19:55:00") Obviously this returns: >>> aString ['comm...
Regex to Split 1st Colon
I have a time in ISO 8601 ( 2009-11-19T19:55:00 ) which is also paired with a name commence. I'm trying to parse this into two. I'm currently up to here: import re sColon = re.compile('[:]') aString = sColon.split("commence:2009-11-19T19:55:00") Obviously this returns: >>> aString ['commence','2009-11-19T19','55','00...
[ ">>> first, colon, rest = \"commence:2009-11-19T19:55:00\".partition(':')\n\n>>> print (first, colon, rest)\n('commence', ':', '2009-11-19T19:55:00')\n\n", "You could put maximum split parameter in split function\n>>> \"commence:2009-11-19T19:55:00\".split(\":\",1)\n['commence', '2009-11-19T19:55:00']\n\nOfficial...
[ 5, 5, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001770569_python_regex.txt
Q: How to insert repeated message in google protocol buffer _pb2.py file How to insert repeated message in google protocol buffer _pb2.py file A: make changes to your .proto file. Look at the example : http://code.google.com/apis/protocolbuffers/docs/pythontutorial.html
How to insert repeated message in google protocol buffer _pb2.py file
How to insert repeated message in google protocol buffer _pb2.py file
[ "make changes to your .proto file. Look at the example : http://code.google.com/apis/protocolbuffers/docs/pythontutorial.html\n" ]
[ 0 ]
[]
[]
[ "buffer", "protocols", "python" ]
stackoverflow_0001543904_buffer_protocols_python.txt
Q: Metaclass not being called in subclasses Here is a python session. >>> class Z(type): def __new__(cls, name, bases, attrs): print cls print name return type(name, bases, attrs) ... >>> class Y(object): __metaclass__ = Z ... <class '__main__.Z'> Y >>> class X(Y): ... pa...
Metaclass not being called in subclasses
Here is a python session. >>> class Z(type): def __new__(cls, name, bases, attrs): print cls print name return type(name, bases, attrs) ... >>> class Y(object): __metaclass__ = Z ... <class '__main__.Z'> Y >>> class X(Y): ... pass ... >>> class W(Y): ... __metaclass__ ...
[ "The problem is that the cls argument (which is the metaclass object) is not passed on when you call type, therefore the class object Y that is created and returned does not have any reference to the metaclass Z.\nIf you replace the last line in __new__ with\nreturn super(Z, cls).__new__(cls, name, bases, attrs)\n\...
[ 14 ]
[]
[]
[ "metaclass", "python" ]
stackoverflow_0001770712_metaclass_python.txt
Q: reactor.iterate seems to block a program with Py2exe I'm currently using an application in python which works quite well but when I'm converting it with py2exe, the application seems to be suspended at the first "reactor.iterate" Each time I press Ctrl+C to stop the application, the error is always the same and th...
reactor.iterate seems to block a program with Py2exe
I'm currently using an application in python which works quite well but when I'm converting it with py2exe, the application seems to be suspended at the first "reactor.iterate" Each time I press Ctrl+C to stop the application, the error is always the same and the application seems to be bloqued on a "reactor.iterate(4)...
[ "The typical use of the reactor is not to call reactor.iterate. It's hard to say why exactly you're getting the behavior you are without seeing your program, but for a wild guess, I'd say switching to reactor.run might help.\n" ]
[ 1 ]
[]
[]
[ "py2exe", "python", "twisted" ]
stackoverflow_0001770754_py2exe_python_twisted.txt
Q: Is there a more pythonic way to open a file if given one as an argument or stdin if not? I'm trying to write a python script which follows the common unix command line pattern of accepting input from stdin if no file name is given. This is what I've been using: if __name__ == "__main__": if len(sys.argv) > 1:...
Is there a more pythonic way to open a file if given one as an argument or stdin if not?
I'm trying to write a python script which follows the common unix command line pattern of accepting input from stdin if no file name is given. This is what I've been using: if __name__ == "__main__": if len(sys.argv) > 1: stream = open(sys.argv[1]) else: stream = sys.stdin Is there a more pyth...
[ "The fileinput module is perfect for this.\n", "similar but one-line solution\nstream = sys.argv[1] if len(sys.argv)>1 else sys.stdin\n\n", "how about this one?\nstream=sys.argv[1:] and open(sys.argv[1]) or sys.stdin\n\n", "I would suggest you make it more unixy instead:\nif len(sys.argv) > 1:\n sys.stdin ...
[ 10, 5, 2, 0 ]
[]
[]
[ "command_line", "python", "unix" ]
stackoverflow_0001770789_command_line_python_unix.txt
Q: Reading a csv file in Python with different line terminator I have a file in CSV format where the delimiter is the ASCII unit separator ^_ and the line terminator is the ASCII record separator ^^ (obviously, since these are nonprinting characters, I've just used one of the standard ways of writing them here). I'v...
Reading a csv file in Python with different line terminator
I have a file in CSV format where the delimiter is the ASCII unit separator ^_ and the line terminator is the ASCII record separator ^^ (obviously, since these are nonprinting characters, I've just used one of the standard ways of writing them here). I've written plenty of code that reads and writes CSV files, so my i...
[ "Why not supply a custom iterable to the csv.reader function? Here is a naive implementation which reads the entire contents of the CSV file into memory at once (which may or may not be desirable, depending on the size of the file):\ndef records(path):\n with open(path) as f:\n contents = f.read()\n ...
[ 3 ]
[]
[]
[ "csv", "delimiter", "python" ]
stackoverflow_0001770934_csv_delimiter_python.txt
Q: Using Python/Selenium/Best Tool For The Job to get URI of image requests generated through JavaScript? I have some JavaScript from a 3rd party vendor that is initiating an image request. I would like to figure out the URI of this image request. I can load the page in my browser, and then monitor "Live HTTP Headers...
Using Python/Selenium/Best Tool For The Job to get URI of image requests generated through JavaScript?
I have some JavaScript from a 3rd party vendor that is initiating an image request. I would like to figure out the URI of this image request. I can load the page in my browser, and then monitor "Live HTTP Headers" or "Tamper Data" in order to figure out the image request URI, but I would prefer to create a command line...
[ "The simplest thing to do might be to use something like HtmlUnit and skip a real browser entirely. By using Rhino, it can evaluate JavaScript and likely be used to extract that URL out.\nThat said, if you can't get that working, try out Selenium RC and use the captureNetworkTraffic command (which requires the Sele...
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "analytics", "http_headers", "python", "selenium" ]
stackoverflow_0001709711_analytics_http_headers_python_selenium.txt
Q: Fixing a type-error in Python's Pg Thank you for bobince in solving the first bugs! How can you use pg.escape_bytea or pg.escape_string in the following? #1 With both pg.escape_string and pg.escape_bytea con1.query( "INSERT INTO files (file, file_name) VALUES ('%s', '%s')" % (pg.escape_...
Fixing a type-error in Python's Pg
Thank you for bobince in solving the first bugs! How can you use pg.escape_bytea or pg.escape_string in the following? #1 With both pg.escape_string and pg.escape_bytea con1.query( "INSERT INTO files (file, file_name) VALUES ('%s', '%s')" % (pg.escape_bytea(pg.espace_string(f.read())), pg.es...
[ "\nINSERT INTO files('binf','file_name') VALUES(file,file_name)\n\nYou've got the (...) sections the wrong way round, you're trying to insert the columns (file, filename) into the string literals ('binf', 'file_name'). You're also not actually inserting the contents of the variables binf and file_name into the quer...
[ 4 ]
[]
[]
[ "postgresql", "python", "types" ]
stackoverflow_0001770786_postgresql_python_types.txt
Q: Compare string and floats in python I have a two lists with values that I want to compare. If the value can be converted to a float, I want to compare the floats else I just want to compare the values as strings. How can I make that distinction to check whether a value can be converted to float or not? A: The ea...
Compare string and floats in python
I have a two lists with values that I want to compare. If the value can be converted to a float, I want to compare the floats else I just want to compare the values as strings. How can I make that distinction to check whether a value can be converted to float or not?
[ "The easiest way should be to just try to convert them to floats, and if that fails, fall back to a compare on strings:\ndef floatstrcmp(left, right):\n try:\n return cmp(float(left), float(right))\n except ValueError:\n return cmp(left, right)\n\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0001771374_python.txt
Q: Template system for RDF? RDF is a schema-free system to represent data. However, most of the time I find myself writing a sort of well-known graph structure, and I have to build triple by triple. In the more general case, this well known graph structure is of course not guaranteed to be complete nor fixed (e.g. s...
Template system for RDF?
RDF is a schema-free system to represent data. However, most of the time I find myself writing a sort of well-known graph structure, and I have to build triple by triple. In the more general case, this well known graph structure is of course not guaranteed to be complete nor fixed (e.g. something else can be added). H...
[ "Sounds a little like using a SPARQL CONSTRUCT query to make the final graph. Run a regular query (WHERE {} ) against a graph to form some variable bindings and then use the CONSTRUCT {} block to make the templated graph into your final answer. Any modern rdf library should have support for SPARQL.\n" ]
[ 3 ]
[]
[]
[ "python", "rdf" ]
stackoverflow_0001768921_python_rdf.txt
Q: Choosing a Path for Python File Access One of the features of my project is to allow users to create their own little .txt file, put it somewhere on their HDD, which can then be used as criteria for a part of my application. Is there a Fixed, 'generic'(?) path for most OSs that I could use? Or does anyone have any...
Choosing a Path for Python File Access
One of the features of my project is to allow users to create their own little .txt file, put it somewhere on their HDD, which can then be used as criteria for a part of my application. Is there a Fixed, 'generic'(?) path for most OSs that I could use? Or does anyone have any kind of advice or guidance that could help ...
[ "os.path.expanduser is a good start -- a leading ~/ expands to \"the user's home directory\", which is computer by reasonable heuristics on both Unix-y and Windows systems. Of course, you don't want to put your file in the home directly, but a subdirectory of that (which you'll have to make if not already there) i...
[ 7, 3, 0 ]
[]
[]
[ "path", "python" ]
stackoverflow_0001771099_path_python.txt
Q: Effective Interpreted Programming Language for File/Image manipulation I need to make a script to read images from a directory, rename them, resize them to a MAX_HEIGHT, MAX_WIDTH, put a watermark logo and save them in JPG. I was thinking on doing this with an interpreted language, like Ruby, PHP, Perl, Python, or...
Effective Interpreted Programming Language for File/Image manipulation
I need to make a script to read images from a directory, rename them, resize them to a MAX_HEIGHT, MAX_WIDTH, put a watermark logo and save them in JPG. I was thinking on doing this with an interpreted language, like Ruby, PHP, Perl, Python, or any with the image manipulation capabilities. Which language would you reco...
[ "It seems, ImageMagick with PerlMagick fits your task nicely.\n", "Any language + ImageMagick set of programs. Using them via libraries (like PerlMagick) proved to be less than optimal, but doing it via system() calls worked incredibly well. You can find a set of scripts that:\n\nperform several useful tasks\nsho...
[ 10, 9, 6, 5, 2, 2 ]
[]
[]
[ "image_manipulation", "perl", "php", "python", "ruby" ]
stackoverflow_0001768749_image_manipulation_perl_php_python_ruby.txt
Q: List of specific class names in Python Is there a way to flag class declarations so that later you can get a list of them flagged? Or a way to get all classes starting with a certain string ? Or all classes that are a subclass of a specific class? A: Note: in the following I assume Python 3.x. For Python 2.x, us...
List of specific class names in Python
Is there a way to flag class declarations so that later you can get a list of them flagged? Or a way to get all classes starting with a certain string ? Or all classes that are a subclass of a specific class?
[ "Note: in the following I assume Python 3.x. For Python 2.x, use new style classes, i.e. write class T(object): pass instead of class T: pass.\n\nFirst, define some classes:\n>>> class T: pass\n... \n>>> class S: pass\n... \n>>> class U(T): pass\n...\n\nTo get a list of classes defined in the current scope, iterate...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001770701_python.txt
Q: Collecting usage data for a desktop application I'm going to be running some large scale usability tests of my software for a science project. We have a lab of about 30 computers running Windows XP. Our application is written in Python and PyGTK. We want to be able to collect the following without staff intervent...
Collecting usage data for a desktop application
I'm going to be running some large scale usability tests of my software for a science project. We have a lab of about 30 computers running Windows XP. Our application is written in Python and PyGTK. We want to be able to collect the following without staff intervention (automatically on our application start): A reco...
[ "For your first point, I believe you can drive recordMyDesktop directly from your Python code pretty easily -- I haven't done so, myself, but the docs make it look easy (and both existing frontends to it are in Python).\nFor your second point, set sys.excepthook to intercept the exceptions and prepare your report v...
[ 2 ]
[]
[]
[ "analytics", "metrics", "python", "usability", "windows" ]
stackoverflow_0001771765_analytics_metrics_python_usability_windows.txt
Q: How do I make text wrapping match current indentation level in vim? Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily. For instance, if I ...
How do I make text wrapping match current indentation level in vim?
Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily. For instance, if I set my settings so that the line: print 'ProcessorError(%r, %r, %r)' % (s...
[ "I asked the same question on SuperUser, eventually found this question, found the patch, and updated the patch to work with Vim 7.2.148 from Fedora 11.\nYou can use yumdownloader --source vim to get the source RPM. Then add a Patch3312: line and a %patch3012 -p1 line to the spec file, and build the rpm.\n", "Yo...
[ 7, 4, 1, 0 ]
[ "I think set textwidth=80 should do it.\n" ]
[ -2 ]
[ "python", "vim", "word_wrap" ]
stackoverflow_0000759577_python_vim_word_wrap.txt
Q: Is there a way to parse html with lxml, but manipulate it with minidom? I have an application where I've been using html5lib to liberally parse html. I use the minidom interface, because I need a real DOM API and ElementTree is not appropriate for what I'm doing. Here's how I do this: parser = html5lib.XHTMLParser...
Is there a way to parse html with lxml, but manipulate it with minidom?
I have an application where I've been using html5lib to liberally parse html. I use the minidom interface, because I need a real DOM API and ElementTree is not appropriate for what I'm doing. Here's how I do this: parser = html5lib.XHTMLParser(tree=html5lib.treebuilders.getTreeBuilder('dom')) parser.parse(html) Howeve...
[ "Think I found a solution:\nfrom xml.dom.pulldom import SAX2DOM\nimport lxml.sax\ndef parse_lxml_dom(html):\n tree = lxml.html.document_fromstring(html)\n handler = SAX2DOM()\n lxml.sax.saxify(tree, handler)\n return handler.document\n\nHowever, this is only about 7 times faster than html5lib. The saxif...
[ 4 ]
[]
[]
[ "dom", "html", "lxml", "parsing", "python" ]
stackoverflow_0001772031_dom_html_lxml_parsing_python.txt
Q: List in a dictionary, looping in Python I have the following code: TYPES = {'hotmail':{'type':'hotmail', 'lookup':'mixed', 'dkim': 'no', 'signatures':['|S|Return-Path: postmaster@hotmail.com','|R|^Return-Path:\s*[^@]+@(?:hot|msn)','^Received: from .*hotmail.com$']}, 'gmail':{'type':'gmail', 'looku...
List in a dictionary, looping in Python
I have the following code: TYPES = {'hotmail':{'type':'hotmail', 'lookup':'mixed', 'dkim': 'no', 'signatures':['|S|Return-Path: postmaster@hotmail.com','|R|^Return-Path:\s*[^@]+@(?:hot|msn)','^Received: from .*hotmail.com$']}, 'gmail':{'type':'gmail', 'lookup':'mixed', 'dkim': 'yes', 'signatures':['|S|...
[ "for type_key, type in TYPES.iteritems():\n for sub_type_key, sub_type in type.iteritems():\n for sig in sub_type['signatures']:\n\nshould be:\nfor type_key, type in TYPES.iteritems():\n for sig in type['signatures']:\n\nBut 'type' is a poor name choice in this case... you don't want to shadow a bu...
[ 7, 3 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0001772068_dictionary_list_python.txt
Q: Python equivalent of ruby's __method__? I want to be able to do this: def asdf(): print __method__ "asdf" Thanks, Noah A: You need to specify your usecase in order for us to give you a better answer. Why do you want to do this? You can get a string with the name of a function by using __name__: def asdf(): ...
Python equivalent of ruby's __method__?
I want to be able to do this: def asdf(): print __method__ "asdf" Thanks, Noah
[ "You need to specify your usecase in order for us to give you a better answer.\nWhy do you want to do this?\nYou can get a string with the name of a function by using __name__:\ndef asdf():\n print asdf.__name__\n\"asdf\"\n\nBut, what would be the point? You might aswell just print the name directly in that case...
[ 8, 4 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0001772070_python_ruby.txt
Q: IOError with Python and OpenCV I want to do some OpenCV Basic Operations using Python. My Problem is that the Pythoninterpreter says that the file I want to open with cv.LoadImage() dont exists. But as you can see in my code and the and the Interpreter Output this file exists and the Program should be able to read...
IOError with Python and OpenCV
I want to do some OpenCV Basic Operations using Python. My Problem is that the Pythoninterpreter says that the file I want to open with cv.LoadImage() dont exists. But as you can see in my code and the and the Interpreter Output this file exists and the Program should be able to read it. Likly the answer is simple (I a...
[ "I've tried both suggestions, but its the same like before. the os.access returns a TRUE but the function cv.LoadImage produce the same error.\nAny other solutions?\nanyhow thanks fpr answer...\n", "Try giving it the whole path instead of the name only, or maybe using .\\google-de02.jpg.\n", "Try using the rep...
[ 2, 1, 0 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0001772103_opencv_python.txt
Q: Python/MySQL fails under Windows I'm trying to get Python 2.6 to communicate with MySQL Server 5.1, under Windows XP, but I keep getting a strange error, "SystemError: NULL object passed to Py_BuildValue": >>> import MySQLdb as mysql >>> db = mysql.connect(user = "root", passwd="whatever", db="mysql", host="localh...
Python/MySQL fails under Windows
I'm trying to get Python 2.6 to communicate with MySQL Server 5.1, under Windows XP, but I keep getting a strange error, "SystemError: NULL object passed to Py_BuildValue": >>> import MySQLdb as mysql >>> db = mysql.connect(user = "root", passwd="whatever", db="mysql", host="localh ost") >>> cu = db.cursor() >>> cu.exe...
[ "Something wrong with MySQLdb part written in C. According to errors message it tries to pass NULL where pointer to object is expected. It's probably a bug in MySQLdb, unless you are using some broken build. What version are you using? Try to download latest stable version of MySQLdb for exactly your python version...
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001772001_mysql_python.txt
Q: How to click a link in win32com.client IE? I'm using win32com.client to control an IE instance in Python. How can I click a link on a certain page (e.g. using navigate to link href isn't acceptable since it won't trigger referrer sending)? Here is the base: import random import time from win32com.client import Dis...
How to click a link in win32com.client IE?
I'm using win32com.client to control an IE instance in Python. How can I click a link on a certain page (e.g. using navigate to link href isn't acceptable since it won't trigger referrer sending)? Here is the base: import random import time from win32com.client import Dispatch ie = Dispatch("InternetExplorer.Applicati...
[ "Turns out it has .click() method.\nhttp://msdn.microsoft.com/en-us/library/ms535173(VS.85).aspx\n", "Have you tried using the Headers parameter of the navigate method to manually set the Referrer header like:\n\nReferrer: http://example.com\n\n" ]
[ 2, 1 ]
[]
[]
[ "internet_explorer", "python" ]
stackoverflow_0001661107_internet_explorer_python.txt
Q: Using Jython From Eclipse Plugin I am having a tough time getting jython to work properly when run from an Eclipse plugin. I have a simple object factory that loads a python module conforming to a Java Interface. All of this works fine in standalone mode. However, when I package this as an eclipse plugin, I get...
Using Jython From Eclipse Plugin
I am having a tough time getting jython to work properly when run from an Eclipse plugin. I have a simple object factory that loads a python module conforming to a Java Interface. All of this works fine in standalone mode. However, when I package this as an eclipse plugin, I get a different error based on a few vari...
[ "Finally figure this one out. Here is what I had to do:\n1) I used the JSR223 ScriptEngine instead of PythonInterpreter:\nengine.get(module_name); //gets the class object of the module\ngetConstructors[0].newInstance(null) on the class to get an object\n//cast it to your interface!\n2) Make sure your Eclipse plug...
[ 5 ]
[]
[]
[ "java", "jython", "python" ]
stackoverflow_0001765802_java_jython_python.txt
Q: Find following tag with pyparsing I'm using pyparsing to parse HTML. I'm grabbing all embed tags, but in some cases there's an a tag directly following that I also want to grab if it's available. example: import pyparsing target = pyparsing.makeHTMLTags("embed")[0] target.setParseAction(pyparsing.withAttribute(src...
Find following tag with pyparsing
I'm using pyparsing to parse HTML. I'm grabbing all embed tags, but in some cases there's an a tag directly following that I also want to grab if it's available. example: import pyparsing target = pyparsing.makeHTMLTags("embed")[0] target.setParseAction(pyparsing.withAttribute(src=pyparsing.withAttribute.ANY_VALUE)) ta...
[ "If there is an optional <a> tag that would be interesting if it follows an <embed> tag, then add it to your search pattern:\nembedTag = pyparsing.makeHTMLTags(\"embed\")[0]\naTag = pyparsing.makeHTMLTags(\"a\")[0]\ntarget = embedTag + pyparsing.Optional(aTag)\nresult = target.searchString(\"\"\"..... \n <obje...
[ 5, 1, 1, 1 ]
[]
[]
[ "html", "parsing", "pyparsing", "python" ]
stackoverflow_0001767673_html_parsing_pyparsing_python.txt
Q: Are there any examples of a Python PyGTK Pango editor toolbar? I am looking for an example application written in Python and PyGTK. There should be an editor out there somewhere that already does this. Some app with a text editor row of buttons: - Font - Bold/italic/underline - etc I am hoping to avoid reinventing...
Are there any examples of a Python PyGTK Pango editor toolbar?
I am looking for an example application written in Python and PyGTK. There should be an editor out there somewhere that already does this. Some app with a text editor row of buttons: - Font - Bold/italic/underline - etc I am hoping to avoid reinventing the wheel on this one! thanks
[ "I couldn't find any pygtk programs that do what you want, but here is a good tutorial to using pango: http://zetcode.com/tutorials/pygtktutorial/pango/\n", "I found some related examples: KeepNote, which has a custom rich edit, and Rednotebook which implements KeepNote's richedit.\n" ]
[ 2, 2 ]
[]
[]
[ "pango", "pygtk", "python" ]
stackoverflow_0001665288_pango_pygtk_python.txt
Q: pysvn with svn+ssh I'm working with pysvn, and I'm trying to find a decent way to handle repositories that are only accessible via svn+ssh. Obviously SSH keys make this all incredibly easy, but I can't guarantee the end user will be using an SSH key. This also has to be able to run without user interaction, becaus...
pysvn with svn+ssh
I'm working with pysvn, and I'm trying to find a decent way to handle repositories that are only accessible via svn+ssh. Obviously SSH keys make this all incredibly easy, but I can't guarantee the end user will be using an SSH key. This also has to be able to run without user interaction, because it's going to be doing...
[ "Check out ssh configuration option PasswordAuthentication.\nI'm not sure how pysvn interacts with ssh, but if you set this to no in your ~/.ssh/config (or maybe global config?) then it shouldn't prompt for a password.\n" ]
[ 2 ]
[]
[]
[ "pysvn", "python", "ssh", "svn" ]
stackoverflow_0001772133_pysvn_python_ssh_svn.txt
Q: Linking Tcl/Tk to Python 2.5 I have an existing Python 2.4 and it is working properly with tkinter as I tested it using python import _tkinter import Tkinter Tkinter._test() Now, I have installed python 2.5.2 but when I try the same tests (with the newer version), it returns (but the same tests are worki...
Linking Tcl/Tk to Python 2.5
I have an existing Python 2.4 and it is working properly with tkinter as I tested it using python import _tkinter import Tkinter Tkinter._test() Now, I have installed python 2.5.2 but when I try the same tests (with the newer version), it returns (but the same tests are working for the previous version) I...
[ "The files you found are for linking directly to tcl/tk. Python depends on another library as well: _tkinter.so. It should be in /usr/lib/python2.5/lib-dynload/_tkinter.so.\nHow did you install python2.5? If you are using Debian or Ubuntu you need to install the python-tk package to get Tkinter support.\nIf the _tk...
[ 3 ]
[]
[]
[ "python", "tcl", "tk_toolkit", "tkinter" ]
stackoverflow_0001773222_python_tcl_tk_toolkit_tkinter.txt
Q: Importing python classes in the Google App Engine I am writing a GAE application and have run into an import problem. My app.yaml has the following lines: - url: /py/classes/ static_dir: py/classes - url: /py/lib static_dir: py/lib - url: /py/bin/signin script: py/bin/signin.py I am keeping a python...
Importing python classes in the Google App Engine
I am writing a GAE application and have run into an import problem. My app.yaml has the following lines: - url: /py/classes/ static_dir: py/classes - url: /py/lib static_dir: py/lib - url: /py/bin/signin script: py/bin/signin.py I am keeping a python file, titled employee.py, containing the class employe...
[ "The static_dir configuration option can not be used to extend PYTHONPATH. Using it you can serve static files like images, stylesheet, or Javascript files.\nIf you want to use normal Python modules just put them next to your main Python files.\nEdit:\nAre your directories Python packages that include the necessary...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001770037_google_app_engine_python.txt
Q: What is the best browser automation tool for Python? I want to write a following script: given a text file with the list of actions to be executed on a certain site it would use some browser's (IE probably, because I don't know anything about other drive-able ones) CSS rendering and JS executing capabilities to im...
What is the best browser automation tool for Python?
I want to write a following script: given a text file with the list of actions to be executed on a certain site it would use some browser's (IE probably, because I don't know anything about other drive-able ones) CSS rendering and JS executing capabilities to imitate a user doing those actions on a site. So I've found...
[ "I'd encourage you to look again at Selenium...that's really what you want to do. Do you need to actually render the page in a browser, or just emulate navigation and clicking? \nMechanize gives you stateful programmatic web browsing, and might be what you're looking for.\n", "You should try Win32Com as it give...
[ 3, 2, 2, 1, 1 ]
[]
[]
[ "browser_automation", "python" ]
stackoverflow_0001771898_browser_automation_python.txt
Q: Are there any libraries for Python to simulate keyboard action? The problem I have is that I have this Python script to launch a application. After the application is launched (the GUI is shown on screen), I want to make it de-activated. It can be done manually by activating another window, or minimizing this app,...
Are there any libraries for Python to simulate keyboard action?
The problem I have is that I have this Python script to launch a application. After the application is launched (the GUI is shown on screen), I want to make it de-activated. It can be done manually by activating another window, or minimizing this app, or pressing the Show Desktop key for WindowsXP. So is there any way ...
[ "Take a look at SendKeys. It is in the pypi, so you can install it via easy_install.\n", "You can use pywin32 to send a minimize event.\n", "I've used AutoIt (via it's COM interface) a lot of times\n" ]
[ 4, 0, 0 ]
[]
[]
[ "keyboard", "python", "windows" ]
stackoverflow_0001767575_keyboard_python_windows.txt
Q: Class attribute evaluation and generators How exactly does Python evaluate class attributes? I've stumbled across an interesting quirk (in Python 2.5.2) that I'd like explained. I have a class with some attributes that are defined in terms of other, previously defined attributes. When I try using a generator obj...
Class attribute evaluation and generators
How exactly does Python evaluate class attributes? I've stumbled across an interesting quirk (in Python 2.5.2) that I'd like explained. I have a class with some attributes that are defined in terms of other, previously defined attributes. When I try using a generator object, Python throws an error, but if I use a pla...
[ "Yeah, it's a bit dodgy, this. A class doesn't really introduce a new scope, it just sort of looks a little bit like it does; constructs like this expose the difference.\nThe idea is that when you're using a generator expression it's equivalent to doing it with a lambda:\nclass Brie(object):\n base= 2\n power...
[ 15, 1 ]
[]
[]
[ "attributes", "class", "class_attributes", "python" ]
stackoverflow_0001773636_attributes_class_class_attributes_python.txt
Q: My python program executes faster than my java version of the same program. What gives? Update: 2009-05-29 Thanks for all the suggestions and advice. I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago. In the end I was able to make the ...
My python program executes faster than my java version of the same program. What gives?
Update: 2009-05-29 Thanks for all the suggestions and advice. I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago. In the end I was able to make the java code the fastest. Lessons: My example code below shows the insertion of primitive ints ...
[ "You're not really testing Java vs. Python, you're testing java.util.HashSet using autoboxed Integers vs. Python's native set and integer handling.\nApparently, the Python side in this particular microbenchmark is indeed faster.\nI tried replacing HashSet with TIntHashSet from GNU trove and achieved a speedup facto...
[ 21, 12, 7, 7, 6, 5, 4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "java", "microbenchmark", "python" ]
stackoverflow_0000918359_java_microbenchmark_python.txt
Q: What Python features will excite the interest of a C# developer? For someone who’s been happily programming in C# for quite some time now and planning to learn a new language I find the Python community more closely knit than many others. Personally dynamic typing puts me off, but I am fascinated by the way the ...
What Python features will excite the interest of a C# developer?
For someone who’s been happily programming in C# for quite some time now and planning to learn a new language I find the Python community more closely knit than many others. Personally dynamic typing puts me off, but I am fascinated by the way the Python community rallies around it. There are a lot of other things I ...
[ "For me its the flexibility and elegance, but there are a handful of things I wish could be pulled in from other languages though (better threading, more robust expressions).\nIn typical I can write a little bit of code in python and do a lot more than the same amount of lines in many other languages. Also, in pyt...
[ 18, 15, 11, 11, 10, 4, 2, 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "c#", "programming_languages", "python" ]
stackoverflow_0001773063_c#_programming_languages_python.txt
Q: Sort a CSV by date in Python I'm trying to sort a CSV file and I want the items sorted by date in reverse order: newest first. def SortCsvByField( filename, fieldNo, sep = ',' ): records = [line.split(sep) for line in file(filename)] As far as that it's pretty easy, but how do I compare dates? A: I'd recomme...
Sort a CSV by date in Python
I'm trying to sort a CSV file and I want the items sorted by date in reverse order: newest first. def SortCsvByField( filename, fieldNo, sep = ',' ): records = [line.split(sep) for line in file(filename)] As far as that it's pretty easy, but how do I compare dates?
[ "I'd recommend installing the excellent dateutil module. (In Ubuntu/Debian, it is provided by the python-dateutil package).\ndateutil can parse date strings into datetime objects: It can handle many different date formats without you having to lift a finger(*):\nimport dateutil.parser as dparser\ndate=dparser.parse...
[ 5, 2, 2 ]
[]
[]
[ "csv", "python", "sorting" ]
stackoverflow_0001773909_csv_python_sorting.txt
Q: Emacs customization I'm new to the whole Emacs thing, and one of the things that gets me is that out-of-the-box Emacs doesn't keep you within blocks when programming. I program in mostly Python and C++ and hitting enter sends the cursor back to column 1 on a new line rather than keeping you in the block you're wor...
Emacs customization
I'm new to the whole Emacs thing, and one of the things that gets me is that out-of-the-box Emacs doesn't keep you within blocks when programming. I program in mostly Python and C++ and hitting enter sends the cursor back to column 1 on a new line rather than keeping you in the block you're working in. I managed to fin...
[ "The following is from my init.el for xemacs, it might or might not work for emacs:\n(add-hook 'c-mode-common-hook\n '(lambda () \n (define-key c-mode-base-map (kbd \"RET\") 'newline-and-indent)))\n\n" ]
[ 5 ]
[]
[]
[ "c++", "customization", "emacs", "python" ]
stackoverflow_0001774320_c++_customization_emacs_python.txt
Q: How to resize just uploaded image? In VIEW I want to resize uploaded image and save 2 copies of it in model real and changed A: Sorl has great thumbnailing capabilities that can also be used in templates ... it will also check to see if an image is already in the filesystem if not it will create the new resize...
How to resize just uploaded image?
In VIEW I want to resize uploaded image and save 2 copies of it in model real and changed
[ "Sorl has great thumbnailing capabilities that can also be used in templates ... it will also check to see if an image is already in the filesystem if not it will create the new resized file.\nDepends really where your trying to call the image from.\nhttp://thumbnail.sorl.net/docs\ndef image_thumb(self):\n thum...
[ 8, 3, 3, 2, 1 ]
[]
[]
[ "django", "python", "python_imaging_library" ]
stackoverflow_0001769683_django_python_python_imaging_library.txt
Q: How can I program software using Python for Linux/Windows? For example, using C# I can make software fairly easily for Windows. I downloaded Python but all I get is a terminal like window for executing single lines of code. Is there a free IDE/Visual editor for designing GUI's in conjunction with Python? Thank SO....
How can I program software using Python for Linux/Windows?
For example, using C# I can make software fairly easily for Windows. I downloaded Python but all I get is a terminal like window for executing single lines of code. Is there a free IDE/Visual editor for designing GUI's in conjunction with Python? Thank SO. :D
[ "The character-based terminal (console) interface isn't the only one Python affords. It is often the most visible because it is\n\n\"built-in\"\noften used in the early stages of learning the language, allowing one to focus on various idioms of the language, without the added complexity of the object model and API...
[ 2, 1, 0 ]
[]
[]
[ "ide", "linux", "python", "user_interface", "windows" ]
stackoverflow_0001774384_ide_linux_python_user_interface_windows.txt
Q: Module import error using IDLE I'm an absolute beginner using IDLE (Python 2.6.4) to learn the basics. I recently found a Python program that I want to run but it throws an error although the code looks fine (i.e all modules exist): from css.parse import parse data = """ em { padding: 2px; margin: 1e...
Module import error using IDLE
I'm an absolute beginner using IDLE (Python 2.6.4) to learn the basics. I recently found a Python program that I want to run but it throws an error although the code looks fine (i.e all modules exist): from css.parse import parse data = """ em { padding: 2px; margin: 1em; border-width: medium; bor...
[ "You should have your test.py script in the same folder as the folder, not in the folder.\nSo it should look like this:\n../\n test.py\n css/\n\n", "A generic but useful reference regarding the way Python module search path is\nthis brief but informative section of Python Documentation\nThe default paths and the ...
[ 1, 1 ]
[]
[]
[ "path", "python", "python_idle" ]
stackoverflow_0001774453_path_python_python_idle.txt
Q: Call from Objective-C into Python bbum posted an outline of how to do this, but I'm unable to complete the details. Where does the Python code go, and how will my Objective-C code know about it? How would I do it compiling on the command line? A: Source here: Calling Python From Objective-C I have posted a ful...
Call from Objective-C into Python
bbum posted an outline of how to do this, but I'm unable to complete the details. Where does the Python code go, and how will my Objective-C code know about it? How would I do it compiling on the command line?
[ "Source here:\nCalling Python From Objective-C\nI have posted a full explanation of how to do this to my weblog as it is quite a bit longer than something I would post here.\nThe abstract summary remains the same: use an abstract class to provide the type information necessary to make the C compiler happy and the ...
[ 12, 3, 0 ]
[]
[]
[ "objective_c", "python" ]
stackoverflow_0001772491_objective_c_python.txt
Q: Fixtures for Google App Engine Are there any Python tools to create fixtures on Google App Engine? I tried Fixture(http://farmdev.com/projects/fixture/). It is the most awesome tool I have come across. I love the clean approach and the consistency of the APIs. But it is LGPL licensed. Our project is licensed under...
Fixtures for Google App Engine
Are there any Python tools to create fixtures on Google App Engine? I tried Fixture(http://farmdev.com/projects/fixture/). It is the most awesome tool I have come across. I love the clean approach and the consistency of the APIs. But it is LGPL licensed. Our project is licensed under Apache License 2.0 and AFAIK LGPL i...
[ "Are you using the fixtures just for testing your app? If so, I don't think the license of your app matters at all. It would only be important if you were redistributing the fixtures functionality.\n" ]
[ 1 ]
[]
[]
[ "fixture", "google_app_engine", "python", "testing" ]
stackoverflow_0001770755_fixture_google_app_engine_python_testing.txt
Q: Appending to a List L = ['abc', 'ADB', 'aBe'] L[len(L):]=['a1', 'a2'] # append items at the end... L[-1:]=['a3', 'a4'] # append more items at the end... ... works, but 'a2' is missing in the output: ['abc', 'ADB', 'aBe', 'append', 'a1', 'a3', 'a4'] A: I think that the -1 is pointing at the last element of the ...
Appending to a List
L = ['abc', 'ADB', 'aBe'] L[len(L):]=['a1', 'a2'] # append items at the end... L[-1:]=['a3', 'a4'] # append more items at the end... ... works, but 'a2' is missing in the output: ['abc', 'ADB', 'aBe', 'append', 'a1', 'a3', 'a4']
[ "I think that the -1 is pointing at the last element of the list, which gets overwritten by 'a3'. As described here, you can do a \nlist.extend(['a3', 'a4'])\n\n", "Use L.append (for a single element) or L.extend (for a sequence) -- there's absolutely no call for playing fancy \"assign-to-slice\" tricks (especia...
[ 3, 3, 1, 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001774616_list_python.txt
Q: Subversion post-commit hook I have created a subversion post-commit hook to send out an email everytime a commit is made.Im calling a python script from the file post-commit in /var/svn/repos/hooks . REPOS="$1" REV="$2" ~/svnnotify.py $REV But the problem is that the svn commit command is taking a longer time t...
Subversion post-commit hook
I have created a subversion post-commit hook to send out an email everytime a commit is made.Im calling a python script from the file post-commit in /var/svn/repos/hooks . REPOS="$1" REV="$2" ~/svnnotify.py $REV But the problem is that the svn commit command is taking a longer time to terminate as it waits for the ...
[ "Try adding an ampersand (&) after the line that calls your script to put it in the background and return immediately.\n", "Call a batch file and in that batch file execute python script to run in the background by adding ampersand at end of command in batch file( & ).\n", "Maybe put the update in a simple queu...
[ 4, 0, 0 ]
[]
[]
[ "python", "svn", "svn_hooks", "unix" ]
stackoverflow_0001774646_python_svn_svn_hooks_unix.txt
Q: Python ctypes & libspeex.dll/libspeex.so; what are the equivilents to #define, typedef, and structs? I have a reference of the dll file here: http://speex.org/docs/api/speex-api-reference/group__Codec.html What I'm wondering is, in that list, there are a lot of defines. What is the python equivalent, same for th...
Python ctypes & libspeex.dll/libspeex.so; what are the equivilents to #define, typedef, and structs?
I have a reference of the dll file here: http://speex.org/docs/api/speex-api-reference/group__Codec.html What I'm wondering is, in that list, there are a lot of defines. What is the python equivalent, same for the struct class, what are my options for implementing all of this with ctypes? Typedefs? I'm relatively i...
[ "To use structs, you indeed should declare them with ctypes.Structure to let Python know about them. \n>>> from ctypes import *\n>>> class POINT(Structure):\n... _fields_ = [(\"x\", c_int),\n... (\"y\", c_int)]\n...\n>>> point = POINT(10, 20)\n>>> print point.x, point.y\n10 20\n>>> point = POINT...
[ 2, 0 ]
[]
[]
[ "api", "c", "ctypes", "python", "speex" ]
stackoverflow_0001774383_api_c_ctypes_python_speex.txt
Q: Python 2.6 DB error I'm trying to get the Yahoo! BOSS package working, but when I try to run the example file I get the following error: $ python examples/ex5.py File "examples/ex5.py", line 28 tb = db.group(by=["yn$title"], key="rank", reducer=lambda d1,d2: d1+d2, as="total", table=tb, norm=text.norm) ...
Python 2.6 DB error
I'm trying to get the Yahoo! BOSS package working, but when I try to run the example file I get the following error: $ python examples/ex5.py File "examples/ex5.py", line 28 tb = db.group(by=["yn$title"], key="rank", reducer=lambda d1,d2: d1+d2, as="total", table=tb, norm=text.norm) ...
[ "as was a pseudo-keyword in 2.5, it's become a full-fledged keyword in 2.6 -- that's definitely the cause of your problem!\nAs for the workaround, try adding a **{'as': 'total'} at the end of your call and remove the plain as='total' -- that should work.\n" ]
[ 1 ]
[]
[]
[ "python", "python_2.6", "yahoo_boss_api" ]
stackoverflow_0001774752_python_python_2.6_yahoo_boss_api.txt
Q: Does a exception with just a raise have any use? For example, here is some code from django.templates.loader.app_directories.py.[1] try: yield safe_join(template_dir, template_name) except UnicodeDecodeError: # The template dir name was a bytestring that wasn't valid UTF-8. raise If you catch an excep...
Does a exception with just a raise have any use?
For example, here is some code from django.templates.loader.app_directories.py.[1] try: yield safe_join(template_dir, template_name) except UnicodeDecodeError: # The template dir name was a bytestring that wasn't valid UTF-8. raise If you catch an exception just to re raise it, what purpose does it serve? ...
[ "In the code you linked to is another additional exception handler:\ntry:\n yield safe_join(template_dir, template_name)\nexcept UnicodeDecodeError:\n # The template dir name was a bytestring that wasn't valid UTF-8.\n raise\nexcept ValueError:\n # The joined path was located outside of template_dir.\n ...
[ 17, 3, 2, 1 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0001774792_exception_handling_python.txt
Q: Unable to use PIL after installing using pythononmac.org package (Mac OS Leopard) I'm trying to use PIL for a Google App Engine project. I've installed PIL using the installer from pythononmac.org but it doesn't seem to do anything, or at least neither I nor Python can find the files. I'm running Python 2.5.1. A:...
Unable to use PIL after installing using pythononmac.org package (Mac OS Leopard)
I'm trying to use PIL for a Google App Engine project. I've installed PIL using the installer from pythononmac.org but it doesn't seem to do anything, or at least neither I nor Python can find the files. I'm running Python 2.5.1.
[ "The installers found on that page were designed to be used with the python 2.5 installer found there. Note that most of the packages are now out-of-date. The PIL installer uses the site-packages library in the framework used by the 2.5 Python on that page and by the more up-to-date python.org installer: /Library...
[ 3 ]
[]
[]
[ "installation", "macos", "osx_leopard", "python", "python_imaging_library" ]
stackoverflow_0001774825_installation_macos_osx_leopard_python_python_imaging_library.txt
Q: Python detect USB drive then assign drive letter? Here is the problem. We have 100s of external 500gb USB drives. Each drive will travel to a new location through the year. What is the best way to automatically detect that a USB drive has been plugged into a Windows system, then assign a Z:\ drive letter? These US...
Python detect USB drive then assign drive letter?
Here is the problem. We have 100s of external 500gb USB drives. Each drive will travel to a new location through the year. What is the best way to automatically detect that a USB drive has been plugged into a Windows system, then assign a Z:\ drive letter? These USB drives will be plugged into lots of different compute...
[ "as terabytest said, you may run a script from an autorun.inf in the root of the drive. personally, i would do with a batch script:\n(echo select volume %~d0 && echo assign letter=Z) | diskpart\n\nthe %~d0 retrieves the drive letter of the currently executing batch file.\nif this is not sufficient, there is a way o...
[ 2, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0001771200_python_windows.txt
Q: Can this be made more pythonic? I came across this (really) simple program a while ago. It just outputs the first x primes. I'm embarrassed to ask, is there any way to make it more "pythonic" ie condense it while making it (more) readable? Switching functions is fine; I'm only interested in readability. Thanks fr...
Can this be made more pythonic?
I came across this (really) simple program a while ago. It just outputs the first x primes. I'm embarrassed to ask, is there any way to make it more "pythonic" ie condense it while making it (more) readable? Switching functions is fine; I'm only interested in readability. Thanks from math import sqrt def isprime(n):...
[ "Your algorithm itself may be implemented pythonically, but it's often useful to re-write algorithms in a functional way - You might end up with a completely different but more readable solution at all (which is even more pythonic).\ndef primes(upper):\n n = 2; found = []\n while n < upper:\n # If a nu...
[ 7, 6, 5, 2, 2, 1, 1, 1 ]
[]
[]
[ "primes", "python" ]
stackoverflow_0001775459_primes_python.txt
Q: Continuously redraw wxPython element I have a chat client that continuously polls a server and fetches new messages. From my def __init__() I have: wx.CallAfter(self.pollServer) Which is defined: def pollServer(self): t = self.updateMessages() time.sleep(5) self.pollServer() Now printing the messages...
Continuously redraw wxPython element
I have a chat client that continuously polls a server and fetches new messages. From my def __init__() I have: wx.CallAfter(self.pollServer) Which is defined: def pollServer(self): t = self.updateMessages() time.sleep(5) self.pollServer() Now printing the messages into the Terminal shows that it works but...
[ "instead of \ntime.sleep(5)\nself.pollServer()\n\ntry with\nwx.CallLater(5,self.pollServer)\n\n" ]
[ 2 ]
[]
[]
[ "python", "refresh", "timer", "wxpython" ]
stackoverflow_0001775921_python_refresh_timer_wxpython.txt
Q: python reload function and syntactically incorrect module What happens when I reload a module in python and the new code for the module is syntactically incorrect? The reload(module) function doesn't seem to be throwing any exception. Is there any way to determine if the reload was successful or failed? A: The ...
python reload function and syntactically incorrect module
What happens when I reload a module in python and the new code for the module is syntactically incorrect? The reload(module) function doesn't seem to be throwing any exception. Is there any way to determine if the reload was successful or failed?
[ "The reload() command should raise a SyntaxError:\nIn [34]: import test\n# This works fine\n\nAfter making a syntax error in test.py: (changed import --> pimport)\nIn [35]: reload(test)\n------------------------------------------------------------\n File \"/home/unutbu/pybin/test.py\", line 2\n pimport itert...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0001776153_python.txt
Q: Select statement with SqlAlchemy Yes, very basic question. I've successfully created my db using declarative_base, and can perform inserts into the db too. I just have a few questions about SqlAlchemy sql statements. I've create a table called Location. A few issues/questions (see code below): For statement, "p...
Select statement with SqlAlchemy
Yes, very basic question. I've successfully created my db using declarative_base, and can perform inserts into the db too. I just have a few questions about SqlAlchemy sql statements. I've create a table called Location. A few issues/questions (see code below): For statement, "print row", I have to specify each colu...
[ "\nYou code in sample is incomplete and has errors. So it's impossible to say for sure what is Location here. I assume it's a mapped class, so you are requesting a list of all Location objects, not rows. When you print an object you get its string representation. String representation of objects can be changed by d...
[ 2, 1, 1 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0001761194_orm_python_sqlalchemy.txt
Q: Strategies for debugging numerical stability issues? I'm trying to write an implementation of Wilson's spectral density factorization algorithm [1] for Python. The algorithm iteratively factorizes a [QxQ] matrix function into its square root (it's sort of an extension of the Newton-Raphson square-root finder for s...
Strategies for debugging numerical stability issues?
I'm trying to write an implementation of Wilson's spectral density factorization algorithm [1] for Python. The algorithm iteratively factorizes a [QxQ] matrix function into its square root (it's sort of an extension of the Newton-Raphson square-root finder for spectral density matrices). The problem is that my implemen...
[ "I would recommend asking this question on the scipy-user mailing list, perhaps with an example of your code. Generally the people on the list seem to be highly experienced with numerical computation and are really helpful, just following the list is an education in itself.\nOtherwise, I'm afraid I don't have any i...
[ 4, 2 ]
[]
[]
[ "matrix", "numerical_stability", "python", "scipy", "spectral_density" ]
stackoverflow_0001776409_matrix_numerical_stability_python_scipy_spectral_density.txt
Q: Python plugin in netbeans manually Can install python plugin in netbeans 6.7 manually (without Tools/Plugin) ? if yes (with .nbi package ) which url can use ? A: find one Netbeans that downloaded python plug-in and go to Netbeans folder and copy python folder. In computer that need to install python plug-in co...
Python plugin in netbeans manually
Can install python plugin in netbeans 6.7 manually (without Tools/Plugin) ? if yes (with .nbi package ) which url can use ?
[ "find one Netbeans that downloaded python plug-in and go to Netbeans folder and copy python folder. In computer that need to install python plug-in copy that folder in Netbeans root folder and go to Tools/Plugin and activate python . \n" ]
[ 0 ]
[]
[]
[ "netbeans", "netbeans6.7", "netbeans_plugins", "python" ]
stackoverflow_0001163531_netbeans_netbeans6.7_netbeans_plugins_python.txt
Q: Accessing Facebook Connect FBML cookie via PyFacebook? Is it possible, having logged in via a Facebook Connect FBML button, to retrieve and use the session details via PyFacebook? Can i use auth.getSession() in the same way as if I'd fired the login via Python? Basically I'm trying to work out if it's possible to...
Accessing Facebook Connect FBML cookie via PyFacebook?
Is it possible, having logged in via a Facebook Connect FBML button, to retrieve and use the session details via PyFacebook? Can i use auth.getSession() in the same way as if I'd fired the login via Python? Basically I'm trying to work out if it's possible to replace the stages up to and including raw_input() in the e...
[ "Using the Verifying the Facebook User page on the developer wiki I tracked down the PyFacebook getSession, validate_signature and getLoggedInUser methods and along with the code found in PyFacebook's example.py for Django:\nif 'session_key' in request.session and 'uid' in request.session:\n fb.session_key = req...
[ 1, 0 ]
[]
[]
[ "cookies", "facebook", "python" ]
stackoverflow_0001613772_cookies_facebook_python.txt
Q: How can a python base class tell whether a sub class has overridden its methods? Here is my guess, which doesn't work: class BaseClass(object): def foo(self): return 'foo' def bar(self): return 'bar' def methods_implemented(self): """This doesn't work...""" overriden = [...
How can a python base class tell whether a sub class has overridden its methods?
Here is my guess, which doesn't work: class BaseClass(object): def foo(self): return 'foo' def bar(self): return 'bar' def methods_implemented(self): """This doesn't work...""" overriden = [] for method in ('foo', 'bar'): this_method = getattr(self, method...
[ "Perhaps this?\n>>> class BaseClass(object):\n... def foo(self):\n... return 'foo'\n... def bar(self):\n... return 'bar'\n... def methods_implemented(self):\n... \"\"\"This does work.\"\"\"\n... overriden = []\n... for method in ('foo', 'bar'):\n... th...
[ 11, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001776994_python.txt
Q: How to auto log into gmail atom feed with Python? Gmail has this sweet thing going on to get an atom feed: def gmail_url(user, pwd): return "https://"+str(user)+":"+str(pwd)+"@gmail.google.com/gmail/feed/atom" Now when you do this in a browser, it authenticates and forwards you. But in Python, at least what ...
How to auto log into gmail atom feed with Python?
Gmail has this sweet thing going on to get an atom feed: def gmail_url(user, pwd): return "https://"+str(user)+":"+str(pwd)+"@gmail.google.com/gmail/feed/atom" Now when you do this in a browser, it authenticates and forwards you. But in Python, at least what I'm trying, isn't working right. url = gmail_url(settin...
[ "You can use the HTTPBasicAuthHandler, I tried the following and it worked:\nimport urllib2\n\ndef get_unread_msgs(user, passwd):\n auth_handler = urllib2.HTTPBasicAuthHandler()\n auth_handler.add_password(\n realm='New mail feed',\n uri='https://mail.google.com',\n user='%s@gmail.com' % ...
[ 13 ]
[]
[]
[ "atom_feed", "gmail", "python", "rss", "urllib" ]
stackoverflow_0001777081_atom_feed_gmail_python_rss_urllib.txt
Q: Which programming language has very short context-free Grammar in its formal specification? What programming language has short and beautiful grammars (in EBNF)? Some languages are easer to be parsed. Some time ago I have created a simple VHDL parser, but it was very slow. Not because it is implemented completely ...
Which programming language has very short context-free Grammar in its formal specification?
What programming language has short and beautiful grammars (in EBNF)? Some languages are easer to be parsed. Some time ago I have created a simple VHDL parser, but it was very slow. Not because it is implemented completely in Python, but because VHDL grammar (in EBNF) is huge. The EBNF of Python is beautiful but it is ...
[ "I haven't compared, but Lua is a language renowned for its simple syntax. The BNF is at the very end of this reference manual: http://www.lua.org/manual/5.1/manual.html .\n", "Assembly languages!\n...in general, and particularly for CPUs which have a simple architecture (few instructions, few addressing modes, f...
[ 5, 4, 3, 1, 0 ]
[ "Lisp is probably pretty small.\nlisp ::= `(´ exp `)´\n\n" ]
[ -1 ]
[ "bash", "c", "python", "vhdl" ]
stackoverflow_0001777011_bash_c_python_vhdl.txt
Q: Why do I get this error in this Python code? I am trying to extract the first words in a file by Python. My code import re con1 = pg.DB('tk', 'localhost', 5432, None, None, 'masi', '123') f1="/home/masi/fy.txt" print re.findall(r"\w+", f1.read()) I get the error Traceback (most recent call last)...
Why do I get this error in this Python code?
I am trying to extract the first words in a file by Python. My code import re con1 = pg.DB('tk', 'localhost', 5432, None, None, 'masi', '123') f1="/home/masi/fy.txt" print re.findall(r"\w+", f1.read()) I get the error Traceback (most recent call last): ...
[ "f1.read() should be open(f1).read()\n", "I don't know Python but it looks like you need to open the file which is \nf=open('/tmp/workfile', 'r')\n\nAccording to this site\n", "When you assign f1 to the filepath, you are actually saying the f1 is the string referring to the filepath. Instead, if you were to ass...
[ 5, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001777592_python.txt
Q: Python importing & using cdll (with a linux .so file) After one of my last questions about python&c++ integration i was told to use dlls at windows. (Previous question) That worked ok doing: cl /LD A.cpp B.cpp C.pp in windows enviroment, after setting the include path for boost, cryptopp sources and cryptopp libra...
Python importing & using cdll (with a linux .so file)
After one of my last questions about python&c++ integration i was told to use dlls at windows. (Previous question) That worked ok doing: cl /LD A.cpp B.cpp C.pp in windows enviroment, after setting the include path for boost, cryptopp sources and cryptopp libraries. Now i'm tryting to do the same in linux, creating a ....
[ "C++ compiler mangles names of functions. To do what you are trying to do you must have the declaration prototype inside \nextern \"C\" {...}\n\nit's hard to tell from your samples what exactly you have in a source file.\nAs someone already mentioned, use nm utility to see what objects that are in your shared obje...
[ 3, 1 ]
[]
[]
[ "c++", "file", "linux", "python", "shared_libraries" ]
stackoverflow_0001777752_c++_file_linux_python_shared_libraries.txt
Q: postgresql and python I need to visualize spatial data (20 polygons) from "postgis" database (postgresql), with python. I know how to connect postgresql database with python only, but I don`t how to visualize those polygons. It is project for my university. We need to use for example matplotlib and create applicat...
postgresql and python
I need to visualize spatial data (20 polygons) from "postgis" database (postgresql), with python. I know how to connect postgresql database with python only, but I don`t how to visualize those polygons. It is project for my university. We need to use for example matplotlib and create application in python which will vi...
[ "I've had good luck using the Python Imaging Library when I've needed to create raster (bitmap) graphics. It's got a pretty simple interface and makes it pretty easy to overlay graphics on top of another image. Unfortunately, PIL isn't updated that often. Probably because it just works. Here's how to do a simpl...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0001776511_postgresql_python.txt
Q: Module import path I'm unable to test-run a cssparser that I'd like to use. test.py: from css.parse import parse data = """ em { padding: 2px; margin: 1em; border-width: medium; border-style: dashed; line-height: 2.4em; } p { color: red; font-size: 12pt } p:first-letter { colo...
Module import path
I'm unable to test-run a cssparser that I'd like to use. test.py: from css.parse import parse data = """ em { padding: 2px; margin: 1em; border-width: medium; border-style: dashed; line-height: 2.4em; } p { color: red; font-size: 12pt } p:first-letter { color: green; font-size: 200...
[ "Here is few steps I just tested.\n\nreadme says its python 2.5, so you need python 2.x series\nI have created a folder C:/TEST/\nI have downloaded all files from css-py svn to C:/TEST/, so C:/TEST/css/ and C:/TEST/uri/ folders exists now.\nI have downloaded ply's tar gz file and extract only ply folder into C:/TES...
[ 4, 2, 2, 0, 0 ]
[]
[]
[ "import", "module", "path", "python" ]
stackoverflow_0001777838_import_module_path_python.txt
Q: Automatically pick tags from context using Python How can I pick tags from an article or a user's post using Python? Is the following method ok? Build a list of word frequency from the text and sort them. Remove some common words and pick the top 10 words remained in the list as the tags. If the above method is ...
Automatically pick tags from context using Python
How can I pick tags from an article or a user's post using Python? Is the following method ok? Build a list of word frequency from the text and sort them. Remove some common words and pick the top 10 words remained in the list as the tags. If the above method is ok, what library can detect if which words are common, ...
[ "Here's an article on removing stop words. The link to the stop word list in the article is broken but here's another one.\n", "The Natural Language Toolkit offers a broad variety of methods for this kind of stuff. I can't give you hands-on advice as I'm not familiar with this subject, but I think it's worth the...
[ 4, 3, 2, 1, 0 ]
[]
[]
[ "python", "tags" ]
stackoverflow_0001775637_python_tags.txt
Q: Is there precision in this number that Python isn't showing me? I've run into something odd, here, and I'm at a loss -- I have a feeling this has something to do with floating precision, but I'm surprised Python would not display the approximation error, if so. I'm working on Project Euler problem 62. As a simple...
Is there precision in this number that Python isn't showing me?
I've run into something odd, here, and I'm at a loss -- I have a feeling this has something to do with floating precision, but I'm surprised Python would not display the approximation error, if so. I'm working on Project Euler problem 62. As a simple test (I've since solved using a different approach), I had a is_cube...
[ "This is using c.__str__() (aka. str(c)) :\nprint \"c is\", c\n\nThis is using c.__repr__() (aka. repr(c)) :\n>>> c # In the Python shell\n\nIIRC, __str__ truncates to 10 decimals, whereas __repr__ goes further. To get the same behavior as in the Python shell, you could do :\nprint repr(c)\n# Or\nprint \"%r\" % c\n...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001778179_python.txt
Q: If you had the time and inclination to create a programming language, what characteristics would it have? Just curious. If you had the time and inclination to create a programming language, what characteristics would it have? One language I would like to see would borrow as much from the syntax of Python as possi...
If you had the time and inclination to create a programming language, what characteristics would it have?
Just curious. If you had the time and inclination to create a programming language, what characteristics would it have? One language I would like to see would borrow as much from the syntax of Python as possible but compile to machine code that runs as fast as C or C++.
[ "I would limit my language to one statement:\nSolve my problem.\n\nMaybe i'd add one modifier though, in case its urgent:\nSolve my problem, please.\n\n", "A mix of COBOL and XML, for the lulz\n<program>\n <data>\n <const>\n <name>myStr</name>\n <value><[CDATA[Hello, World!]]></val...
[ 5, 4, 0, 0, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0001778278_c++_python.txt
Q: Where can I find a (current) example of code to bulk upload data to Google AppEngine? (For localhost, too.) I've tried to do it like they describe in the AppEngine docs but I can't get it to accept my upload. (I haven't tried to download.) I want to get it working in the development environment before I tried on t...
Where can I find a (current) example of code to bulk upload data to Google AppEngine? (For localhost, too.)
I've tried to do it like they describe in the AppEngine docs but I can't get it to accept my upload. (I haven't tried to download.) I want to get it working in the development environment before I tried on the live site. It's kind of confusing, because I don't know if I should be trying appcfg.py or bulkloader.py. (I m...
[ "The docs have a section on uploading and downloading data, with examples. You should be using appcfg.py unless you need one of the features of bulkloader.py that are not yet integrated, such as --dump/--restore functionality.\nIt sounds like the authentication problems you're having are related to Google Apps: If ...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001777949_google_app_engine_python.txt
Q: Why does Python allow comparison of a callable and a number? I used python to write an assignment last week, here is a code snippet def departTime(): ''' Calculate the time to depart a packet. ''' if(random.random < 0.8): t = random.expovariate(1.0 / 2.5) else: t = random.expova...
Why does Python allow comparison of a callable and a number?
I used python to write an assignment last week, here is a code snippet def departTime(): ''' Calculate the time to depart a packet. ''' if(random.random < 0.8): t = random.expovariate(1.0 / 2.5) else: t = random.expovariate(1.0 / 10.5) return t Can you see the problem? I compar...
[ "This isn't always a mistake\nFirstly, just to make things clear, this isn't always a mistake.\nIn this particular case, it's pretty clear the comparison is an error.\nHowever, because of the dynamic nature of Python, consider the following (perfectly valid, if terrible) code:\nimport random\nrandom.random = 9 # Ve...
[ 9, 7, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001778521_python.txt
Q: Data visualization in python - after connecting to a database Can you help me to connect to my postgresql database with python? I need to create graphic interface with python which will visualize shapefile data from my database (i have about 50 polygons in shapefile format in that database). Can you help me with c...
Data visualization in python - after connecting to a database
Can you help me to connect to my postgresql database with python? I need to create graphic interface with python which will visualize shapefile data from my database (i have about 50 polygons in shapefile format in that database). Can you help me with creating such application? I am begginer in python.
[ "For communicating with the database, use psycopg2. It's quick, easy and efficient if you are familiar with basic DB concepts.\nYou have several options from here. You can use shpUtils, which is supposed to be a nice package for parsing shapefiles. You can then visualize the data using numerous python graphics pack...
[ 6, 0, 0 ]
[]
[]
[ "database", "postgresql", "python", "visualization" ]
stackoverflow_0001778663_database_postgresql_python_visualization.txt
Q: Arched Relationship Infographic In Python This is a very specific inforgraphic challange altough the fundemental question is how do you build archs between words using matplotlib, cario or an other python libary. Given a the following data structure. me, you, 7 | me, apple, 9 | apple, you, 1 | bike, me, 5 Names w...
Arched Relationship Infographic In Python
This is a very specific inforgraphic challange altough the fundemental question is how do you build archs between words using matplotlib, cario or an other python libary. Given a the following data structure. me, you, 7 | me, apple, 9 | apple, you, 1 | bike, me, 5 Names would be displayed horizontally the names with t...
[ "matplotlib isn't the right library here, since it's not a general purpose graphics library. What you need here is either something like Cairo, or much simpler, you can do with the graphics capabilities of any GUI toolkit, such as PyQt. Another feasible approach is PyGame, which has good drawing capabilities as we...
[ 4, 1, 0 ]
[]
[]
[ "graphic", "graphviz", "matplotlib", "python" ]
stackoverflow_0001679917_graphic_graphviz_matplotlib_python.txt
Q: Populating values in module namespace I have a python module. I want to populate some values to it at runtime, how do I do it. Eg. I have a list, ['A', 'B', 'C'] I am creating there classes with these names, and want them to available as if I created them normally for el in ['A', 'B', 'C']: type(el, (object,),...
Populating values in module namespace
I have a python module. I want to populate some values to it at runtime, how do I do it. Eg. I have a list, ['A', 'B', 'C'] I am creating there classes with these names, and want them to available as if I created them normally for el in ['A', 'B', 'C']: type(el, (object,), {})
[ "I can think of a couple ways to do this... In order of (what I believe to be) best to worst we have:\nFirst, setting attributes on the current module\n# The first way I had of grabbing the module:\nmod = __import__(__name__, fromlist=['nonempty'])\n\n# From Roger's suggestion:\nimport sys\nmod = sys.modules[__name...
[ 5, 2 ]
[]
[]
[ "metaprogramming", "module", "python" ]
stackoverflow_0001778846_metaprogramming_module_python.txt
Q: When should I drop support for python2.4 on my public python library? I maintain an open source python project. Right now it supports python 2.4, 2.5, 2.6. I am looking for to add support for python 3. I guess it will be easier if I drop 2.4 support. I know it is possible to support all but it is very annoying if ...
When should I drop support for python2.4 on my public python library?
I maintain an open source python project. Right now it supports python 2.4, 2.5, 2.6. I am looking for to add support for python 3. I guess it will be easier if I drop 2.4 support. I know it is possible to support all but it is very annoying if I have to install 4 or 5 python versions on my machine and run the tests on...
[ "I'd say it depends on your target audience. For enterprise stuff I think RedHat (certainly CentOS 5) are still on 2.4 - so if you want typical RedHat/CentOS using people to able to install without resorting to third party python installations then I think you need to keep 2.4 for a while. If most of your users are...
[ 7, 3, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001778670_python.txt
Q: To insert to Pg by Psycopg How can you fix the SQL-statement in Python? The db connection works. However, cur.execute returns none which is false. My code import os, pg, sys, re, psycopg2 try: conn = psycopg2.connect("dbname='tk' host='localhost' port='5432' user='naa' password='123'") except: print "unable ...
To insert to Pg by Psycopg
How can you fix the SQL-statement in Python? The db connection works. However, cur.execute returns none which is false. My code import os, pg, sys, re, psycopg2 try: conn = psycopg2.connect("dbname='tk' host='localhost' port='5432' user='naa' password='123'") except: print "unable to connect to db" cur = conn.cur...
[ "You have to call one of the fetch methods on cur (fetchone, fetchmany, fetchall) to actually get the results of the query.\nYou should probably have a read through the a tutorial for DB-API.\n", "You have to call cur.fetchall() method (or one of other fetch*() methods) to get results from query.\n" ]
[ 2, 2 ]
[]
[]
[ "postgresql", "psycopg", "python" ]
stackoverflow_0001779009_postgresql_psycopg_python.txt
Q: Python subclass with C++ baseclass I have some C++ I have exposed to Python through SWIG. In there is a base class with a single pure virtual function. In Python, I import my module and define a class that uses the abstract class as base. import mymodule class Foo(mymodule.mybase): ... In that module is also ...
Python subclass with C++ baseclass
I have some C++ I have exposed to Python through SWIG. In there is a base class with a single pure virtual function. In Python, I import my module and define a class that uses the abstract class as base. import mymodule class Foo(mymodule.mybase): ... In that module is also a manager class, I want to add my new de...
[ "My guess is that Foo is not derived from mybase in the eyes of the C++ environment. I'm not sure if SWIG can pull this off since it requires a bidirectional understanding of inheritance - Python class uses C++ class as base and C++ code recognizes the inheritance relationship. I would take a serious look into Bo...
[ 2, 0 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0001778487_c++_python_swig.txt
Q: expand users table with django I'm using the authentication that ships with django, and as such, it comes with its own SQL table. I have a few more attributes I'd like to use with the User model that are custom to my app such as a user photo or a random user blob where users can type in notes. what's the best way ...
expand users table with django
I'm using the authentication that ships with django, and as such, it comes with its own SQL table. I have a few more attributes I'd like to use with the User model that are custom to my app such as a user photo or a random user blob where users can type in notes. what's the best way of extending the existing user table...
[ "Please see my (and others) answer to this question: \n", "The other way to handle this is to do table inheritance on the User model and develop your own derived EnhancedUser model. Typically a custom wrapper backend is also written to make sure the auth subsystem returns the EnhancedUser model as well.\nThere's...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001778025_django_python.txt
Q: There is no spawnl function in python 2.6? I just noticed that my old codes written in python 2.5 does not work now. I am in python 2.6 btw. >>> os.spawnl(os.P_NOWAIT,"setup.exe") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\python26\lib\os.py", line 612, in spawnl retur...
There is no spawnl function in python 2.6?
I just noticed that my old codes written in python 2.5 does not work now. I am in python 2.6 btw. >>> os.spawnl(os.P_NOWAIT,"setup.exe") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\python26\lib\os.py", line 612, in spawnl return spawnv(mode, file, args) OSError: [Errno 22] I...
[ "thrope is right about subprocess being preferred. But the spawn* stuff is still there in 2.6. In fact, you can see that in your error message. Your first arg seems to be valid. I'd check the second arg, which is the path.\n", "I got it work by adding DUMMY parameter finally, a bit funky though\nThis is not w...
[ 5, 5, 3, 2, 2 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0001779081_python_python_2.6.txt
Q: What does abstract mean in this context? I need some help in understanding a python concept. class TilePuzzleProblem(search.Problem): """ This class is the class for the NxN - blanks tile puzzle problem """ def __init__(self, N, blanks, initial, goal): """ Initialize """ search.Problem.__init_...
What does abstract mean in this context?
I need some help in understanding a python concept. class TilePuzzleProblem(search.Problem): """ This class is the class for the NxN - blanks tile puzzle problem """ def __init__(self, N, blanks, initial, goal): """ Initialize """ search.Problem.__init__(self, initial, goal) self.N = N ...
[ "This is a trick described here. There's not keyword abstract in Python, so, if you won't override this method in some subclass, it'll cause NotImplementedError. \n", "An abstract method is one which a class doesn't implement, making it an abstract class; subclasses must override all abstract methods (i.e., provi...
[ 11, 5, 1, 0 ]
[]
[]
[ "abstract", "python" ]
stackoverflow_0001779365_abstract_python.txt
Q: How do I save to a field that is specified in a variable? I want to do something like this: # models.py class Model(models.Model): name_in_my_model = models.CharField(max_length=100) # later fieldname = 'name_in_my_model' # this is what I want to do somehow: obj = Model.objects.get(pk=1) obj.fieldname = ...
How do I save to a field that is specified in a variable?
I want to do something like this: # models.py class Model(models.Model): name_in_my_model = models.CharField(max_length=100) # later fieldname = 'name_in_my_model' # this is what I want to do somehow: obj = Model.objects.get(pk=1) obj.fieldname = 'new name' obj.save() Is this possible? I'm making a reusable ...
[ "You can use: setattr(obj, fieldname, 'new name').\n" ]
[ 5 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001779567_django_django_models_python.txt
Q: Problem with logic in Django template Supose this portion of a Django template. regs is a list of Reg objects. Reg.editable is a BooleanField. I want to render a radio button per element in the list. If r.editable is False, the radio button must be disabled: {% for r in regs %} <input type="radio" value="{{ forloo...
Problem with logic in Django template
Supose this portion of a Django template. regs is a list of Reg objects. Reg.editable is a BooleanField. I want to render a radio button per element in the list. If r.editable is False, the radio button must be disabled: {% for r in regs %} <input type="radio" value="{{ forloop.counter }}" {% if forloop.first %}checked...
[ "Djangos templating language doesn't give you a lot in the way of logic in the template (I've heard positive things about Jinja2 if you want to change that). There's also the \"Smart\" {% if %} tag which adds some more functionality and incidentally is being proposed for inclusion in Django 1.2.\nAs for solving th...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "django", "django_templates", "python", "templates" ]
stackoverflow_0001779055_django_django_templates_python_templates.txt
Q: Making ORM with Python's Storm The question is based on the thread, since I observed that Storm allows me reuse my SQL-schemas. How can you solve the following error message in Storm? The code is based on Jason's answer and on Storm's manual. import os, pg, sys, re, psycopg2, storm from storm.locals import * from ...
Making ORM with Python's Storm
The question is based on the thread, since I observed that Storm allows me reuse my SQL-schemas. How can you solve the following error message in Storm? The code is based on Jason's answer and on Storm's manual. import os, pg, sys, re, psycopg2, storm from storm.locals import * from storm import * class Courses(): ...
[ "I'll leave out the connection details because I'm not terribly familiar with Postgres.\nfrom storm.locals import *\n\nclass Courses(object):\n __storm_table__ = 'courses'\n pkey = Int(primary=True)\n course_nro = Unicode()\n\ncourse = Courses()\ncourse.course_nro = 'abcd'\nstore.add(course)\nstore.commit(...
[ 4 ]
[]
[]
[ "orm", "python", "storm_orm" ]
stackoverflow_0001779750_orm_python_storm_orm.txt
Q: What is wrong with the pearson algorithm from “Programming Collective Intelligence”? This function is from the book "Programming Collective Intelligence”, and is supposed to calculate the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1. If two critics rate items ver...
What is wrong with the pearson algorithm from “Programming Collective Intelligence”?
This function is from the book "Programming Collective Intelligence”, and is supposed to calculate the Pearson correlation coefficient for p1 and p2, which is supposed to be a number between -1 and 1. If two critics rate items very similarly the function should return 1, or close to 1. With real user data I sometimes g...
[ "There is nothing wrong in your result. You are trying to plot a line through 3 points. In second case you have all three points with the same coordinates, i.e. effectively one point. You can't say do these points correlate or anti-correlate, because you can draw infinite number of lines through one point (den in y...
[ 11, 3, 0, 0 ]
[]
[]
[ "algorithm", "pearson", "python" ]
stackoverflow_0001778411_algorithm_pearson_python.txt
Q: How do I encode a 4-byte string as a single 32-bit integer? First, a disclaimer. I'm not a CS grad nor a math major, so simplicity is important. I have a four-character string (e.g. "isoy") that I need to pass as a single 32-bit integer field. Of course at the other end, I need to decode it back to a string. The ...
How do I encode a 4-byte string as a single 32-bit integer?
First, a disclaimer. I'm not a CS grad nor a math major, so simplicity is important. I have a four-character string (e.g. "isoy") that I need to pass as a single 32-bit integer field. Of course at the other end, I need to decode it back to a string. The string will only contain A-Z, and case is not important, if that ...
[ "To 32-bit unsigned integer:\nuint x = BitConverter.ToUInt32(Encoding.ASCII.GetBytes(\"isoy\"), 0); // 2037347177\n\nTo string:\nstring s = Encoding.ASCII.GetString(BitConverter.GetBytes(x)); // \"isoy\"\n\nBitConverter uses the native endianness of the machine.\n", "For Python, struct.unpack does the job (t...
[ 10, 8, 3, 3, 2, 2 ]
[]
[]
[ "algorithm", "c#", "powershell", "python" ]
stackoverflow_0001780922_algorithm_c#_powershell_python.txt
Q: How to access Firefox cache from webdriver? I'm able to access pages like about:cache-entry?client=HTTP&sb=1&key=(some URL) directly in Firefox, but when it renders the page, it certainly gets the data from some storage. How can I access the latter from Python Firefox Webdriver? A: The page returned by such an a...
How to access Firefox cache from webdriver?
I'm able to access pages like about:cache-entry?client=HTTP&sb=1&key=(some URL) directly in Firefox, but when it renders the page, it certainly gets the data from some storage. How can I access the latter from Python Firefox Webdriver?
[ "The page returned by such an about:cache-entry?... URL contains a line like this one:\nfile on disk: /home/fviktor/.mozilla/firefox/7jx6k3hx.default/Cache/CF7379D8d01\n\nIt is the full pathname of the cache file if any. I think you'll be able to read that file from Python as usual, but I haven't tested it yet. The...
[ 2 ]
[]
[]
[ "caching", "firefox", "python", "webdriver" ]
stackoverflow_0001778816_caching_firefox_python_webdriver.txt
Q: Ugly Code: Amusing comment? Here's a fragment of code I'm prototyping that should, by all accounts, never see the light of day. I'll refactor it and clean it up before I merge it into my project. However, it seems to be working and I happened to be listening to Arlo Guthrie when I was working on it. #!/usr/bin/en...
Ugly Code: Amusing comment?
Here's a fragment of code I'm prototyping that should, by all accounts, never see the light of day. I'll refactor it and clean it up before I merge it into my project. However, it seems to be working and I happened to be listening to Arlo Guthrie when I was working on it. #!/usr/bin/env python import re expr = re.com...
[ "If you could switch your current a-b syntax (which seems likely to get hopelessly confused by negative numbers!) to a:b, then Python's slice syntax would do the parsing for you -- you'd end up (e.g. through a fake class with an indexing method) with a tuple including slices and scalars:\n>>> class x(object):\n... ...
[ 4, 1 ]
[]
[]
[ "comments", "python" ]
stackoverflow_0001780721_comments_python.txt
Q: Error while installing Poster (Python Module) I'm trying to install Chris Atlee's python Poster library so I can upload a file using a HTTP POST query from within my script. On python 2.3, when I type # python setup.py install, I get the following error. The install continues, but I can't >>> import poster later o...
Error while installing Poster (Python Module)
I'm trying to install Chris Atlee's python Poster library so I can upload a file using a HTTP POST query from within my script. On python 2.3, when I type # python setup.py install, I get the following error. The install continues, but I can't >>> import poster later on. byte-compiling build/bdist.linux-x86_64/egg/post...
[ "Python 2.3 didn't have support for decorators (that's what @classmethod is) or list comprehensions (which is the second error), so you're either going to have to find an older version of Poster, or stick with urllib/urllib2 for doing your HTTP work.\nActually, it looks like Poster was created around July, 2008, so...
[ 1 ]
[]
[]
[ "http_post", "http_post_vars", "httppostedfile", "post", "python" ]
stackoverflow_0001781158_http_post_http_post_vars_httppostedfile_post_python.txt
Q: Resize image twice in Django using PIL I have a function in which I'm trying to resize a photo twice from request.FILES['image']. I'm using the image.thumbnail() with the Parser as well. This works fine when I create one thumbnail, but in my view if I repeat the exact same thing again, it fails in the parser via I...
Resize image twice in Django using PIL
I have a function in which I'm trying to resize a photo twice from request.FILES['image']. I'm using the image.thumbnail() with the Parser as well. This works fine when I create one thumbnail, but in my view if I repeat the exact same thing again, it fails in the parser via IOError cannot parse image. I'm very confused...
[ "If this works once, as you say, the image you retrieved is just fine. There are at least two different ways to get multiple thumbnails out of single PIL images.\n\nYou can use PIL's resize method, which will return a resized copy of the original. You just have to calculate the dimensions you'll need if you want to...
[ 2, 2, 0 ]
[]
[]
[ "django", "image_manipulation", "python", "python_imaging_library" ]
stackoverflow_0001485569_django_image_manipulation_python_python_imaging_library.txt
Q: How to load DLL using ctypes in Python? Please provide me a sample explaining how to load & call a functions in c++ dll using Python? I found some articles saying we can use "ctypes" to load and call a function in DLL using Python. But i am not able to find a working sample? It would be great if anyone provide me ...
How to load DLL using ctypes in Python?
Please provide me a sample explaining how to load & call a functions in c++ dll using Python? I found some articles saying we can use "ctypes" to load and call a function in DLL using Python. But i am not able to find a working sample? It would be great if anyone provide me an sample of how to do it.
[ "Here is some actual code I used in a project to load a DLL, lookup a function and set up and call that function.\nimport ctypes\n\n# Load DLL into memory.\n\nhllDll = ctypes.WinDLL (\"c:\\\\PComm\\\\ehlapi32.dll\")\n\n# Set up prototype and parameters for the desired function call\n# in the DLL, `HLLAPI()` (the ...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0001781531_python.txt
Q: Regular expression matching everything except a given regular expression I am trying to figure out a regular expression which matches any string that doesn't start with mpeg. A generalization of this is matching any string which doesn't start with a given regular expression. I tried something like as follows: [^m]...
Regular expression matching everything except a given regular expression
I am trying to figure out a regular expression which matches any string that doesn't start with mpeg. A generalization of this is matching any string which doesn't start with a given regular expression. I tried something like as follows: [^m][^p][^e][^g].* The problem with this is that it requires at least 4 characte...
[ "^(?!mpeg).*\n\nThis uses a negative lookahead to only match a string where the beginning doesn't match mpeg. Essentially, it requires that \"the position at the beginning of the string cannot be a position where if we started matching the regex mpeg, we could successfully match\" - thus matching anything which doe...
[ 34, 11, 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001781554_python_regex.txt
Q: How does the layout of a Python application look? In most programming environments it's clear how the code is distributed into several parts and how everything interacts. In Python I seem to be completely lost. How should the layout of a Python application look? Currently I have: setup.py application_name/ _...
How does the layout of a Python application look?
In most programming environments it's clear how the code is distributed into several parts and how everything interacts. In Python I seem to be completely lost. How should the layout of a Python application look? Currently I have: setup.py application_name/ __main__.py __init__.py views/ controllers/ ...
[ "There are several parts to this question so I'll try to answer them in turn:\n1: Its really up to you, there are no hard-and-fast rules beyond those for establishing that a directory should be treated as a package and so on. Some frameworks will prescribe a directory structure using a script to generate scaffoldi...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0001781657_python.txt
Q: To understand: From PHP Array to Python? This is Common task In PHP and other programming languages.I moved from PHP developer. I want to make sure with this collections. Anyone have who good in python please help me to understand clearly . This is my collections from PHP code. <?php $php = array(1,2,3,4,5,6,7,8,9...
To understand: From PHP Array to Python?
This is Common task In PHP and other programming languages.I moved from PHP developer. I want to make sure with this collections. Anyone have who good in python please help me to understand clearly . This is my collections from PHP code. <?php $php = array(1,2,3,4,5,6,7,8,9,10); for ($i = 0; $i < 10 ; $i ++) echo $php[...
[ "All of these are quite obvious really. I'm only listing the Pythonic ways to do these things. Update: Examples should now work in both Python 2 and Python 3. In Python 2 you could substitute xrange() for range() and iteritems() for items() for efficiency.\nExample 1\nPHP\n$php = array(1,2,3,4,5,6,7,8,9,10);\nfor (...
[ 30, 10, 3, 0 ]
[]
[]
[ "arrays", "loops", "php", "python" ]
stackoverflow_0001781617_arrays_loops_php_python.txt