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: What python equivalent of Sinatra would you recommend? I like the sinatra framework, but might have to work in python. A quick web search has uncovered a few python equivalents including itty, flask and juno. I'd like to know people's experience of these, or other sinatra equivalents. Which would you recommend? A...
What python equivalent of Sinatra would you recommend?
I like the sinatra framework, but might have to work in python. A quick web search has uncovered a few python equivalents including itty, flask and juno. I'd like to know people's experience of these, or other sinatra equivalents. Which would you recommend?
[ "Okay. So I'm biased because I'm the author of Flask, but here something to help you make the pick:\n\nitty - very minimal framework, Bottle is probably a more stable alternative if you want a single file installation.\nFlask - new and actively developed, shaped similar to Sinatra but also differs in a few points. ...
[ 39 ]
[]
[]
[ "frameworks", "python", "sinatra", "web_frameworks" ]
stackoverflow_0003070469_frameworks_python_sinatra_web_frameworks.txt
Q: py2app, pyObjc & macports compilation errors I'm currently writing a small python app that embeds cherrypy and django using py2app. It worked well until I tried to include pyobjc in my project, since my app needed a small GUI (which consists of a small icon in the top menu bar + a drop down menu). I can run my pyt...
py2app, pyObjc & macports compilation errors
I'm currently writing a small python app that embeds cherrypy and django using py2app. It worked well until I tried to include pyobjc in my project, since my app needed a small GUI (which consists of a small icon in the top menu bar + a drop down menu). I can run my python script without any problem (I'm using python 2...
[ "I'm guessing it's because a required library is not in your library path, so the loader can't figure out where it is so it can link the symbols in. You should do one of two things:\n\nAdd /opt/local/lib to your $LD_LIBRARY_PATH environment variable when launching the app; or\nBundle the appropriate libraries with ...
[ 0 ]
[]
[]
[ "macports", "py2app", "pyobjc", "python" ]
stackoverflow_0003051874_macports_py2app_pyobjc_python.txt
Q: how can i pass a value of variable defined in python to a procedure in mysql as an input? I made a procedure in mysql and i call it using python but it take an input and i need to pass the value of a variable in python to it but the mysql doesn't understand that it is a variable because the variable is not defined...
how can i pass a value of variable defined in python to a procedure in mysql as an input?
I made a procedure in mysql and i call it using python but it take an input and i need to pass the value of a variable in python to it but the mysql doesn't understand that it is a variable because the variable is not defined in it's list of fields . for example for a code written in python : variable = "someValue" cur...
[ "you mean something like this?\ncursor.execute(\"call procedure('%s');\" % variable )\n\n" ]
[ 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003084721_mysql_python.txt
Q: Confused about using XPath or not This follows my previous questions on using lxml and Python. I have a question, as to when I have a choice between using the methods provided by the lxml.etree and where I can make use of XPath, what should I use? For example, to get a list of all the X tags in a XML document, I ...
Confused about using XPath or not
This follows my previous questions on using lxml and Python. I have a question, as to when I have a choice between using the methods provided by the lxml.etree and where I can make use of XPath, what should I use? For example, to get a list of all the X tags in a XML document, I could either iterate through it using t...
[ "XPath is usually preferable to an explicit iteration over elements. XPath is more succinct, and will likely be faster since it is implemented inside the XML engine.\nYou'd want to use an explicit iteration if there were complex criteria that couldn't be expressed easily (or at all) in XPath, or if you needed to v...
[ 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0003084627_lxml_python.txt
Q: How to workaround lack of multiple ao.lock? I'm programming a simple pyS60 app, not really done anything with python or using multiple threads before so this is all a bit new to me. In order to keep the app open, I set an e32.Ao_lock to wait() after the body of the application is initialised, and then signal the l...
How to workaround lack of multiple ao.lock?
I'm programming a simple pyS60 app, not really done anything with python or using multiple threads before so this is all a bit new to me. In order to keep the app open, I set an e32.Ao_lock to wait() after the body of the application is initialised, and then signal the lock on the exit_key_handler. One of the tasks the...
[ "I solved this problem by defining a separate second lock, and making sure only one was waiting at a time. It seems to work without any problem. Current code can be found hosted on google code\n" ]
[ 0 ]
[]
[]
[ "locking", "multithreading", "nokia", "pys60", "python" ]
stackoverflow_0001207497_locking_multithreading_nokia_pys60_python.txt
Q: How to set python enviroment variable on windows I've downloaded python installer from http://www.python.org/ftp/python/3.1.2/ , this python-3.1.2.msi file, I need to execute some python files? How do I do that? For example in php I'd do php filename.php from console, I do however have python command line but I do...
How to set python enviroment variable on windows
I've downloaded python installer from http://www.python.org/ftp/python/3.1.2/ , this python-3.1.2.msi file, I need to execute some python files? How do I do that? For example in php I'd do php filename.php from console, I do however have python command line but I don't know how to execute those files. So if I could se...
[ "There is an option in the installer called \"Register Extensions\" to associate Python files with the interpreter, so double-clicking them or entering filename.py in the console should work.\nApart from that you might want to add C:\\Python31 to your PATH variable (right-click on My Computer, choose Settings, choo...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003085146_python.txt
Q: How to fetch multiple values of a class all at once without loop? I know this is simple but I couldn' figure this out, I am fetching all the instances for a given linkname but I want to call all their values(rating2) to perform a calculation, what I realized though is in looping through I believe this is making a...
How to fetch multiple values of a class all at once without loop?
I know this is simple but I couldn' figure this out, I am fetching all the instances for a given linkname but I want to call all their values(rating2) to perform a calculation, what I realized though is in looping through I believe this is making an individual call each time, (its slow) it takes 2 seconds for only 100...
[ "Your app isn't making any more calls than it needs to be. The only RPCs occur when you do the .fetch() operations. Any source of slowness is likely elsewhere.\n", "If your concern is that an RPC is firing inside each loop iteration, I don't think it would be. You're using fetch to eager load your entities, and y...
[ 3, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003084697_google_app_engine_python.txt
Q: Cheat sheet documentation django python Is there any Cheat Sheet or Document where I can see all the build-in modules, functions, commands etc in Django and or Python and where I will get an overview of ALL possible elements I could use. I am sure this is would be a big file/image etc , but it would be very helpfu...
Cheat sheet documentation django python
Is there any Cheat Sheet or Document where I can see all the build-in modules, functions, commands etc in Django and or Python and where I will get an overview of ALL possible elements I could use. I am sure this is would be a big file/image etc , but it would be very helpful to know what commands I could use.
[ "Run:\npydoc -p 8080\n\nAnd go here.\n", "For django use this. It is a little out of date but still relevant.\nFor python I like this quick reference.\n", "\nThere is the Global Module Index\nfor Python.\nHere are some build-in functions\n\n", "If you're using django, a useful way of browsing the template ta...
[ 5, 2, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003085196_django_python.txt
Q: Using Crypto by placing folder in python path? - Python I'm using Django in order to serve a web service. I have only access to FTP and code refresh at the moment. No access to command-line or executing any kind of executable. I am using a Windows Server 2005 machine. Would I be able to use Crypto just by placing ...
Using Crypto by placing folder in python path? - Python
I'm using Django in order to serve a web service. I have only access to FTP and code refresh at the moment. No access to command-line or executing any kind of executable. I am using a Windows Server 2005 machine. Would I be able to use Crypto just by placing the folder within my Django project? Are there any good alter...
[ "You'll need to build pycrypto before you upload it. This will need to be done on a machine with as similar an environment to your server as possible.\nTo build, run python setup.py build from inside the pycrypto-2.1.0 directory. This will create build\\lib.win32-2.6\\Crypto (the name of the libxxx directory might ...
[ 1 ]
[]
[]
[ "aes", "django", "pycrypto", "python" ]
stackoverflow_0003083366_aes_django_pycrypto_python.txt
Q: how to connect my app python code to gui? i had made a program for text to speech convertion in python..and now want to make an gui for it... i have installed wxpython..and have been trying few example available online to understand,but i am not exactly understanding it.. i basically want a frame and a text box to...
how to connect my app python code to gui?
i had made a program for text to speech convertion in python..and now want to make an gui for it... i have installed wxpython..and have been trying few example available online to understand,but i am not exactly understanding it.. i basically want a frame and a text box to enter text and a button...on clicking the butt...
[ "Since Ned Batchelder covered the VB part of your question, I'll outline a wxPython approach.\nIn short you'll need to import your module that contains the code you've written previously, then bind the button's click event to a function that calls your code.\nimport myText2Speech\n... code above ...\n\nhellobtn.Bin...
[ 1, 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003084898_python_wxpython.txt
Q: Rejecting files with Windows line endings using Perforce triggers Using Perforce, I'd like to be able to reject submits which contain files with Windows line endings (\r\n IIRC, maybe just \r anywhere as really we only want files with Unix line endings). Rather than dos2unix incoming files or similar, to help trac...
Rejecting files with Windows line endings using Perforce triggers
Using Perforce, I'd like to be able to reject submits which contain files with Windows line endings (\r\n IIRC, maybe just \r anywhere as really we only want files with Unix line endings). Rather than dos2unix incoming files or similar, to help track down instances where users attempt to submit files with Windows line ...
[ "Here's the minimal edit I can thing of for the bash example found in the p4 docs:\n#!/bin/sh\n# Set target string, files to search, location of p4 executable...\nTARGET='\\r\\n'\nDEPOT_PATH=\"//depot/src/...\"\nCHANGE=$1\nP4CMD=\"/usr/local/bin/p4 -p 1666 -c copychecker\"\nXIT=0\necho \"\"\n# For each file, strip ...
[ 4 ]
[]
[]
[ "bash", "perforce", "python", "triggers" ]
stackoverflow_0003085825_bash_perforce_python_triggers.txt
Q: Is it possible to get the value of an item contained in Django's "changed_data" list? I have the following code in my Django application: if 'book' in authorForm.changed_data: #Do something here... I realize Django can tell me which values have changed in my form by utilizing the "changed_data" list object, bu...
Is it possible to get the value of an item contained in Django's "changed_data" list?
I have the following code in my Django application: if 'book' in authorForm.changed_data: #Do something here... I realize Django can tell me which values have changed in my form by utilizing the "changed_data" list object, but I'd like to know the new values of the fields that have changed. Any thoughts?
[ "Hmm... Try this:\nif authorForm.is_valid() and 'book' in authorForm.changed_data:\n new_value = authorForm.cleaned_data['book']\n\n", "The short answer to my original question is \"No\".\n" ]
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000247922_django_python.txt
Q: How to extract data from an irregularly formatted data file in python I need to extract certain data from a file, but this file is formatted to be read by humans, and is therefore irregular. First off there is a large amount of text before any of the data actually begins: DL_POLY Version 2.20 ...
How to extract data from an irregularly formatted data file in python
I need to extract certain data from a file, but this file is formatted to be read by humans, and is therefore irregular. First off there is a large amount of text before any of the data actually begins: DL_POLY Version 2.20 Running on 10 nodes *************** DLPOLY: LiNbO3 ...
[ "I'd probably do this:\n\niterate over lines in the output\nsearch for one containing eng_tot:\n\n\nif 'eng_tot' in line.split(): process_blocks\n\ngobble up lines until one matches all dashes (with optional spaces on either side)\n\n\nif re.match(\"\\s+-+\\s+\", line): proccess_metrics_block\n\nprocess the first l...
[ 1, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003086257_parsing_python.txt
Q: Django: return one filtered object per foreign key Is it possible to return querysets that return only one object per foreign key? For instance, I want the to get the latest comments from django_comments, but I only want one comment (the latest comment) per object, i.e., only return the latest comment on an objec...
Django: return one filtered object per foreign key
Is it possible to return querysets that return only one object per foreign key? For instance, I want the to get the latest comments from django_comments, but I only want one comment (the latest comment) per object, i.e., only return the latest comment on an object and exclude all the past comments on that object. I gu...
[ "This is a fairly difficult thing to do in SQL at all; you probably won't be able to do it through the ORM.\nYou can't use GROUP BY for this. That's used for telling SQL how to group items for aggregation, which isn't what you're doing here. \"SELECT x, y FROM table GROUP BY x\" is illegal SQL, because the value ...
[ 2, 0 ]
[ "Consider storing the last post as a foreign key somewhere (e.g. in the parent object table). Each time a message is posted or deleted, update this key.\nYes, it's duplication, but worth considering. Having to run complex queries for each request (especially the index page) could take your application performance d...
[ -1 ]
[ "content_type", "django", "django_comments", "django_orm", "python" ]
stackoverflow_0003080326_content_type_django_django_comments_django_orm_python.txt
Q: Python memory usage: Which of my objects is hogging the most memory? The program I've written stores a large amount of data in dictionaries. Specifically, I'm creating 1588 instances of a class, each of which contains 15 dictionaries with 1500 float to float mappings. This process has been using up the 2GB of memo...
Python memory usage: Which of my objects is hogging the most memory?
The program I've written stores a large amount of data in dictionaries. Specifically, I'm creating 1588 instances of a class, each of which contains 15 dictionaries with 1500 float to float mappings. This process has been using up the 2GB of memory on my laptop pretty quickly (I start writing to swap at about the 1000t...
[ "The floats do take up 16 bytes apiece, and a dict with 1500 entries about 100k:\n>> sys.getsizeof(1.0)\n16\n>>> d = dict.fromkeys((float(i) for i in range(1500)), 2.0)\n>>> sys.getsizeof(d)\n98444\n\nso the 22,500 dicts take over 2GB all by themselves, the 68 million floats another GB or so. Not sure how you compu...
[ 7 ]
[]
[]
[ "memory_management", "python" ]
stackoverflow_0003086514_memory_management_python.txt
Q: What's the equivalent of python's __file__ in ruby? In python after imports, one can see the file, that has been loaded/where the module comes from. >>> import os >>> os.__file__ '/Users/tm/lib/python2.6/os.pyc' What would be the equivalent in ruby? >> require 'xmlrpc/client' => true >> ... A: There's nothing t...
What's the equivalent of python's __file__ in ruby?
In python after imports, one can see the file, that has been loaded/where the module comes from. >>> import os >>> os.__file__ '/Users/tm/lib/python2.6/os.pyc' What would be the equivalent in ruby? >> require 'xmlrpc/client' => true >> ...
[ "There's nothing that's an exact match. It's easy to find it yourself, though:\n# Find where a path `p` was loaded from.\ndef locate(p)\n # Find the first path in your load-paths that contains a file matching `p`.\n $:.find { |l|\n File.exists?(File.join(l, p))\n }\nend\n\nruby-1.9.1-p378 > locate('yaml')\n =...
[ 1, 1, 1 ]
[]
[]
[ "module", "path", "python", "ruby" ]
stackoverflow_0003085949_module_path_python_ruby.txt
Q: python postgres Hi i want to store null value in a column.The column is nullable.The column value is not null always it depends on certain conditions.I dont want to write two queries in this case.I have tried None,null both but it gives me error saying worng type for double precision A: You do not say which Pyth...
python postgres
Hi i want to store null value in a column.The column is nullable.The column value is not null always it depends on certain conditions.I dont want to write two queries in this case.I have tried None,null both but it gives me error saying worng type for double precision
[ "You do not say which Python / PostGreSQL interface module you're using -- there are several, not all DB API compliant. In DB API compliant modules, the None singleton is definitely the way to represent SQL NULLs on the Python side of things -- the API docs leave no doubt:\n\nSQL NULL values are represented by the...
[ 2 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0003086265_postgresql_python.txt
Q: Problem with cgi-bin python program putting output in wrong place I have a cgi python program which runs an os.system command and this command is printing output and causing havoc. How do I get python to run the os.system command and have that command print to the webpage it is being run on? A: Do you have to us...
Problem with cgi-bin python program putting output in wrong place
I have a cgi python program which runs an os.system command and this command is printing output and causing havoc. How do I get python to run the os.system command and have that command print to the webpage it is being run on?
[ "Do you have to use os.system? I would use \nstdout, stderr = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr.PIPE).communicate()\n\n" ]
[ 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0003086832_cgi_python.txt
Q: wxPython: VirtualTreeListCtrl with millions of items I would like to add 1,000,000+ entries to the root node of a TreeListCtrl. Therefore I would like to make it "virtual", i.e. work just like a virtual ListCtrl so that it's still fast and I can easily scroll around due to the currently-displayed items being loade...
wxPython: VirtualTreeListCtrl with millions of items
I would like to add 1,000,000+ entries to the root node of a TreeListCtrl. Therefore I would like to make it "virtual", i.e. work just like a virtual ListCtrl so that it's still fast and I can easily scroll around due to the currently-displayed items being loaded on-demand. But I can't use a virtual ListCtrl because I ...
[ "One thing you might do is leave the sub-nodes empty, and catch the expand-node event. Then you check to see if the node's sub-nodes are populated. If they aren't, you add them before expanding the node. If they are populated, you simply ignore the event.\n", "You're right that the treemixin doesn't make the Tree...
[ 0, 0, 0 ]
[]
[]
[ "listctrl", "python", "treecontrol", "virtual", "wxpython" ]
stackoverflow_0003074175_listctrl_python_treecontrol_virtual_wxpython.txt
Q: How to match a word that doesn't start with X but ends with Y with regex Example; X=This Y=That not matching; ThisWordShouldNotMatchThat ThisWordShouldNotMatch WordShouldNotMatch matching; AWordShouldMatchThat I tried (?<!...) but seems not to be easy :) A: ^(?!This).*That$ As a free-spacing regex: ^ ...
How to match a word that doesn't start with X but ends with Y with regex
Example; X=This Y=That not matching; ThisWordShouldNotMatchThat ThisWordShouldNotMatch WordShouldNotMatch matching; AWordShouldMatchThat I tried (?<!...) but seems not to be easy :)
[ "^(?!This).*That$\n\nAs a free-spacing regex:\n^ # Start of string\n (?!This) # Assert that \"This\" can't be matched here\n .* # Match the rest of the string\n That # making sure we match \"That\"\n$ # right at the end of the string\n\nThis will match a single word tha...
[ 14 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003087398_python_regex.txt
Q: How to print out the line after the line found in re.compile() Using this code import re file = open('FilePath/OUTPUT.01') lines = file.read() file.close() for match in re.finditer(r"(?m)^\s*-+\s+\S+\s+(\S+)", lines): eng = match.group(1) open('Tmp.txt', 'w').writelines(eng) print match.group(1) I get a column o...
How to print out the line after the line found in re.compile()
Using this code import re file = open('FilePath/OUTPUT.01') lines = file.read() file.close() for match in re.finditer(r"(?m)^\s*-+\s+\S+\s+(\S+)", lines): eng = match.group(1) open('Tmp.txt', 'w').writelines(eng) print match.group(1) I get a column of data that looks like this: -1.1266E+05 -1.1265E+05 -1.1265E+...
[ "You could use a single regex:\nfile = open('FilePath/OUTPUT.01')\nlines = file.read()\nfile.close()\nwith open(\"output.txt\",\"w\") as f:\n for match in re.finditer(r\"(?m)^\\s*-+\\s+\\S+\\s+(-?[\\d.]+E[+-]\\d+)\", lines):\n f.write(match.group(1)+\"\\n\")\n\nThis should write all the second numbers tha...
[ 2, 0, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003087175_parsing_python.txt
Q: texmate and django, is there intellisense? New to mac and textmate AND python. I don't seem to be getting any intellisensewith textmate, is there a plugin? what are the keyboard shortcuts I should know about (basic ones at this point). thanks! A: There are bundles for Django that make it easier to work with Djan...
texmate and django, is there intellisense?
New to mac and textmate AND python. I don't seem to be getting any intellisensewith textmate, is there a plugin? what are the keyboard shortcuts I should know about (basic ones at this point). thanks!
[ "There are bundles for Django that make it easier to work with Django projects in TextMate. They offer the ability to search online for documentation, and there are a lot of \"snippets\" defined so you can type a few characters, hit Tab, and \"auto\"-complete some frequently-used strings, but none offer anything on...
[ 1, 1 ]
[]
[]
[ "macos", "python", "textmate" ]
stackoverflow_0003081602_macos_python_textmate.txt
Q: django-haystack more_like_this returns nothing I've installed the haystack app and I'm using the solr backend. Search works perfectly although when I try to use the more_like_this template tag, nothing is returned. I have added <requestHandler name="/mlt" class="solr.MoreLikeThisHandler" /> to solrconfig.xml and I...
django-haystack more_like_this returns nothing
I've installed the haystack app and I'm using the solr backend. Search works perfectly although when I try to use the more_like_this template tag, nothing is returned. I have added <requestHandler name="/mlt" class="solr.MoreLikeThisHandler" /> to solrconfig.xml and I can make queries at http://127.0.0.1:8080/solr/mlt ...
[ "I found that mlt was pretty picky, I had to improve my indexing templates to get good mlt results.\n" ]
[ 1 ]
[]
[]
[ "django", "django_haystack", "python", "solr" ]
stackoverflow_0003064046_django_django_haystack_python_solr.txt
Q: Memory issues: Should I be writing to file/database if I'm using swap? (Python) I'm creating and processing a very large data set, with about 34 million data points, and I'm currently storing them in python dictionaries in memory (about 22,500 dictionaries, with 15 dictionaries in each of 1588 class instances). Wh...
Memory issues: Should I be writing to file/database if I'm using swap? (Python)
I'm creating and processing a very large data set, with about 34 million data points, and I'm currently storing them in python dictionaries in memory (about 22,500 dictionaries, with 15 dictionaries in each of 1588 class instances). While I'm able to manage this all in memory, I'm using up all of my RAM and most of my ...
[ "Because you will be looking at \"select portions\", your application will be able to make better use of core than Virtual Memory will. VM is convenient, but - by definition - kinda stupid about locality of reference. \nUse a database.\nI'd probably start with module sqlite3 on the basis of simplicity, unless or un...
[ 1, 1, 1 ]
[]
[]
[ "memory", "python", "swap" ]
stackoverflow_0003087741_memory_python_swap.txt
Q: what does python.exe take as arguments? does it take the filename of the .py and then what? A: Documentation here. A: It takes any options for python.exe itself, then the name of the file (or command or module), then any arguments to be passed to your program. If no file is specified, it puts you in interactiv...
what does python.exe take as arguments?
does it take the filename of the .py and then what?
[ "Documentation here.\n", "It takes any options for python.exe itself, then the name of the file (or command or module), then any arguments to be passed to your program.\nIf no file is specified, it puts you in interactive mode.\nAs indicated in the comments by Adam, type python -h to see the full list. \n" ]
[ 19, 8 ]
[]
[]
[ "arguments", "python" ]
stackoverflow_0003088493_arguments_python.txt
Q: Create an utf-8 csv file in Python I can't create an utf-8 csv file in Python. I'm trying to read it's docs, and in the examples section, it says: For all other encodings the following UnicodeReader and UnicodeWriter classes can be used. They take an additional encoding parameter in their constructor and ...
Create an utf-8 csv file in Python
I can't create an utf-8 csv file in Python. I'm trying to read it's docs, and in the examples section, it says: For all other encodings the following UnicodeReader and UnicodeWriter classes can be used. They take an additional encoding parameter in their constructor and make sure that the data passes the rea...
[ "You don't have to use codecs.open; UnicodeWriter takes Unicode input and takes care of encoding everything into UTF-8. When UnicodeWriter writes into the file handle you passed to it, everything is already in UTF-8 encoding (therefore it works with a normal file you opened with open).\nBy using codecs.open, you es...
[ 14, 1, 1, 0 ]
[]
[]
[ "csv", "encoding", "python", "utf_8" ]
stackoverflow_0003085263_csv_encoding_python_utf_8.txt
Q: Basic HTTP Parsing Using Twisted I am a newcomer to the Python and Twisted game so excuse the ignorance I will likely be asking this question with. As a sort of first program, I am trying to write a basic HTTP server using twisted.web.sever which would simply print to screen the HTTP request, and then print to scr...
Basic HTTP Parsing Using Twisted
I am a newcomer to the Python and Twisted game so excuse the ignorance I will likely be asking this question with. As a sort of first program, I am trying to write a basic HTTP server using twisted.web.sever which would simply print to screen the HTTP request, and then print to screen the HTTP response. I am trying to ...
[ "Take a look at the Request and IRequest API docs to get an idea of what that request parameter offers you. You should be able to find just about everything in the request there.\nI'm not sure what you mean by raw response data though. The response is up to you to generate.\n" ]
[ 2 ]
[]
[]
[ "http", "logging", "python", "twisted", "twisted.web" ]
stackoverflow_0003087651_http_logging_python_twisted_twisted.web.txt
Q: MySQL database back up using Python I'm trying to write a python script which backs up the database every midnight. The code i am using is below: from subprocess import call call (["mysqldump", "-u", "root", "-p*****", "normalisation", ">", "date_here.sql"]) The first problem i came across is that mysql thinks t...
MySQL database back up using Python
I'm trying to write a python script which backs up the database every midnight. The code i am using is below: from subprocess import call call (["mysqldump", "-u", "root", "-p*****", "normalisation", ">", "date_here.sql"]) The first problem i came across is that mysql thinks the ">" is a table when it is not, the que...
[ "use a shell script. there's a million that do this task already online. you can generate the filename using the date command with the right format string, and you can make it run at a scheduled time using cron.\n", "Your command is failing because output redirection is a function of the shell, not mysqldump. Tr...
[ 1, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003088497_mysql_python.txt
Q: Twisted: tcp server with push producer example? I want to put together simple TCP server using Python and Twisted. The server starts up and waits for connection - I already have client - non-python application. Once connection is made server starts sending data at some interval (e.g. 1 sec). The server reads data ...
Twisted: tcp server with push producer example?
I want to put together simple TCP server using Python and Twisted. The server starts up and waits for connection - I already have client - non-python application. Once connection is made server starts sending data at some interval (e.g. 1 sec). The server reads data from a static file (a record at a time), I should be ...
[ "Here is a complete example of a push producer. It's been added to the twisted svn as an example.\n", "What about something simplistic like:\nthedata = '''\nQuesta mattina\nmi son svegliato\no bella ciao, bella ciao,\nbella ciao, ciao, ciao\nquesta mattina\nmi son svegliato\nho trovato l'invasor!\n'''.splitlines...
[ 4, 2 ]
[]
[]
[ "python", "tcpserver", "twisted" ]
stackoverflow_0001591787_python_tcpserver_twisted.txt
Q: Object/XML Backwards-Compatibility We store objects in XML. Sometimes we update the base objects, then we have to save more data in our files to represent the extra attributes of our objects. How to organize/implement a system to ensure backwards compatibility with old versions of our files? The complicated part c...
Object/XML Backwards-Compatibility
We store objects in XML. Sometimes we update the base objects, then we have to save more data in our files to represent the extra attributes of our objects. How to organize/implement a system to ensure backwards compatibility with old versions of our files? The complicated part comes when looking at several versions at...
[ "When I increment versions like this I typically keep the old reader, and just update it to write into the new model. This means I only have the current model for the rest of my code to deal with, but I can still read old files. I would not keep old classes around, no matter what other choices you may make - you ...
[ 1 ]
[]
[]
[ "backwards_compatibility", "python", "xml" ]
stackoverflow_0003088269_backwards_compatibility_python_xml.txt
Q: Python: Elegant way to replace a given dictionary by child key somewhere in a tree? Is there some kind of enumeration library or method I should use or should I write from scratch with recursion? I'm parsing a JSON tree into an object tree as it happens, and I'd like to replace some nodes with other kinds of objec...
Python: Elegant way to replace a given dictionary by child key somewhere in a tree?
Is there some kind of enumeration library or method I should use or should I write from scratch with recursion? I'm parsing a JSON tree into an object tree as it happens, and I'd like to replace some nodes with other kinds of objects. E.g: db = {'bigBang' : {'stars': {'planets': {}, 'is_list':...
[ "It's hard to tell exactly what you're trying to accomplish; I guess you want deepReplace to replace any node named \"planets\" with a map containing \"earth\" and \"mars\"?\nIt's pretty easy to write that function, especially if you know the tree will contain dicts. If not, you need to test the type (or catch the...
[ 1, 1 ]
[]
[]
[ "oop", "python", "recursion" ]
stackoverflow_0003088841_oop_python_recursion.txt
Q: Python Exceptions: EAFP and What is Really Exceptional? It's been said in a couple places (here and here) that Python's emphasis on "it's easier to ask for forgiveness than permission" (EAFP) should be tempered with the idea that exceptions should only be called in truly exceptional cases. Consider the following, ...
Python Exceptions: EAFP and What is Really Exceptional?
It's been said in a couple places (here and here) that Python's emphasis on "it's easier to ask for forgiveness than permission" (EAFP) should be tempered with the idea that exceptions should only be called in truly exceptional cases. Consider the following, in which we're popping and pushing on a priority queue until ...
[ "\nexceptions should only be called in\n truly exceptional cases\n\nNot in Python: for example, every for loop (unless it prematurely breaks or returns) terminates by an exception (StopIteration) being thrown and caught. So, an exception that happens once per loop is hardly strange to Python -- it's there more of...
[ 32, 9, 7, 4, 3 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0003086806_exception_python.txt
Q: Not all of arguments converted during string formatting Im wrtiting a script which saves the current date and time as a filename but I get an error stating "TypeError: not all arguments converted during string formatting" I am new to Python andmay of missed something obvious. Code below: from subprocess import Pop...
Not all of arguments converted during string formatting
Im wrtiting a script which saves the current date and time as a filename but I get an error stating "TypeError: not all arguments converted during string formatting" I am new to Python andmay of missed something obvious. Code below: from subprocess import Popen import datetime today = datetime.date.today() today = st...
[ "You're putting the string formatting in the wrong place; it needs to be right after the string that's being formatted:\nf = open(\"%s.sql\" % (today), \"w\")\n\nIt's legal to not pass any formatting arguments, like you did with \"%s.sql\", but it's not legal to pass arguments but not the right amount (\"w\" % (tod...
[ 30, 4 ]
[]
[]
[ "datetime", "formatting", "python", "string" ]
stackoverflow_0003089038_datetime_formatting_python_string.txt
Q: explicit joining of python threads? I need to start some threads in a python program. The threads perform a background task which might take a long time, so I don't want to block the main thread waiting on the task to happen. Python provides the ability to 'reap' threads using Thread.join() and Thread.isAlive(). B...
explicit joining of python threads?
I need to start some threads in a python program. The threads perform a background task which might take a long time, so I don't want to block the main thread waiting on the task to happen. Python provides the ability to 'reap' threads using Thread.join() and Thread.isAlive(). But I don't actually care about finding ou...
[ "You don't have to explicitly join threads -- just make sure they're not \"daemonized\" (leave their daemon attribute to the default, False) so they'll keep the process alive until they're all done (if you make your threads daemons, then you must make sure the main thread does not terminate until all relevant threa...
[ 1 ]
[]
[]
[ "background", "multithreading", "python" ]
stackoverflow_0003088449_background_multithreading_python.txt
Q: Overwrite global var in one line in Python? I know that I can write: foo = 'bar' def update_foo(): global foo foo = 'baz' But do I really need two lines of code there? Python, alas, won't allow me to say global foo = 'baz' I could also mash the two lines together with the unfortunately repetitive global foo;...
Overwrite global var in one line in Python?
I know that I can write: foo = 'bar' def update_foo(): global foo foo = 'baz' But do I really need two lines of code there? Python, alas, won't allow me to say global foo = 'baz' I could also mash the two lines together with the unfortunately repetitive global foo; foo = 'baz' Any other shortcuts? I'm on Python ...
[ "You could use my favorite alternative to global (a pretty idiosyncratic taste...):\nimport sys\nthismodule = sys.modules[__name__]\nthismodule.foo = 'bar'\n\ndef update_foo():\n thismodule.foo = 'baz'\n\nOnce you've made the thismodule reference, you don't need to use global in this module, because you're always ...
[ 19, 7, 6, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003089208_python.txt
Q: Pydev in Eclipse default working directory What is the default working directory for my project? I have several projects under my workspace, and a couple of run configurations. I use os.getcwd() and the directory goes to other project's folder, after deleting all run configurations, the directory goes to eclipse's...
Pydev in Eclipse default working directory
What is the default working directory for my project? I have several projects under my workspace, and a couple of run configurations. I use os.getcwd() and the directory goes to other project's folder, after deleting all run configurations, the directory goes to eclipse's install folder. How to make the default working...
[ "Open Run Dialog...-> Select your run configuration->Arguments Tab->Working directory:\nmine is set to ${workspace_loc}:test/src/ for a project name test i created in my workspace\n" ]
[ 8 ]
[]
[]
[ "eclipse", "python" ]
stackoverflow_0003089070_eclipse_python.txt
Q: How to use python on webserver for web pages I have read in the documentation that there are 4 or 5 ways in which i can python for web pages. Like With CGI Mod_python : mod_python does have some problems. Unlike the PHP interpreter, the Python interpreter uses caching when executing files, so changes to a file w...
How to use python on webserver for web pages
I have read in the documentation that there are 4 or 5 ways in which i can python for web pages. Like With CGI Mod_python : mod_python does have some problems. Unlike the PHP interpreter, the Python interpreter uses caching when executing files, so changes to a file will require the web server to be restarted FastCGI...
[ "I believe mod_python is deprecated so you shouldn't use it. \nsee http://blog.dscpl.com.au/2010/05/modpython-project-soon-to-be-officially.html\nmod_wsgi is mentioned as a replacement.\n", "I am a big fan of cherrypy. Yes there are a lot of choices out there.\n", "You could also use Google App Engine with Pyt...
[ 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003089450_python.txt
Q: Django-modpython deploying project I am deploying a Django project on apache server with mod_python in linux. I have created a directory structure like: /var/www/html/django/demoInstall where demoInstall is my project. In the httpd.conf I have put the following code. <Location "/django/demoInstall"> SetHandler...
Django-modpython deploying project
I am deploying a Django project on apache server with mod_python in linux. I have created a directory structure like: /var/www/html/django/demoInstall where demoInstall is my project. In the httpd.conf I have put the following code. <Location "/django/demoInstall"> SetHandler python-program PythonHandler django...
[ "There's a fairly simple way around this using just django, without having to touch apache.\nRename your urls.py to something else, e.g. site_urls.py\nThen create a new urls.py which includes that \nfrom django.conf.urls.defaults import *\n\nurlpatterns = patterns('',\n (r'^django/demoInstall/', include('site_ur...
[ 2, 0 ]
[]
[]
[ "django", "mod_python", "python" ]
stackoverflow_0003060311_django_mod_python_python.txt
Q: Python not opening Japanese filenames I've been working on a python script to open up a file with a unicode name (Japanese mostly) and save to a randomly generated (Non-unicode) filename in Windows Vista 64-bit, and I'm having issues... It just doesn't work, it works fine with non-unicode filenames (Even if it has...
Python not opening Japanese filenames
I've been working on a python script to open up a file with a unicode name (Japanese mostly) and save to a randomly generated (Non-unicode) filename in Windows Vista 64-bit, and I'm having issues... It just doesn't work, it works fine with non-unicode filenames (Even if it has unicode content), but the second you try t...
[ "You have to convert your inpath to unicode, like this:\ninpath = sys.argv[1]\ninpath = inpath.decode(\"UTF-8\")\nfilein = open(inpath, \"rb\")\n\nI'm guessing you are using Python 2.6, because in Python 3, all strings are unicode by default, so this problem wouldn't happen.\n", "My guess is that sys.argv1 and sy...
[ 3, 1 ]
[]
[]
[ "file_io", "python", "unicode", "windows" ]
stackoverflow_0003089700_file_io_python_unicode_windows.txt
Q: Is there a python equivalent to the Unix `which` command? I'd like to know where the module I'm about to import is coming from. Is there a which command in python? Example: >>> which module_name /usr/lib/python2.6/site-packages/module_name.py A: import imp imp.find_module(module_name) Help on built-in function...
Is there a python equivalent to the Unix `which` command?
I'd like to know where the module I'm about to import is coming from. Is there a which command in python? Example: >>> which module_name /usr/lib/python2.6/site-packages/module_name.py
[ "import imp\nimp.find_module(module_name)\n\n\nHelp on built-in function find_module\n in module imp: \nfind_module(...)\n find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n Search for a module. If path is omitted or None, search for a\n built-in, frozen or special module and co...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0003089939_python.txt
Q: Python getattr equivalent for dictionaries? What's the most succinct way of saying, in Python, "Give me dict['foo'] if it exists, and if not, give me this other value bar"? If I were using an object rather than a dictionary, I'd use getattr: getattr(obj, 'foo', bar) but this raises a key error if I try using a di...
Python getattr equivalent for dictionaries?
What's the most succinct way of saying, in Python, "Give me dict['foo'] if it exists, and if not, give me this other value bar"? If I were using an object rather than a dictionary, I'd use getattr: getattr(obj, 'foo', bar) but this raises a key error if I try using a dictionary instead (a distinction I find unfortunat...
[ "dict.get(key, default) returns dict[key] if key in dict, else returns default.\nNote that the default for default is None so if you say dict.get(key) and key is not in dict then this will just return None rather than raising a KeyError as happens when you use the [] key access notation. \n", "Also take a look at...
[ 104, 5 ]
[]
[]
[ "python" ]
stackoverflow_0003089186_python.txt
Q: Django Inlines user permissions + view only - permissions issues I'm not sure if this is a bug or I'm just missing something (although I have already parsed the documentation about inlines), but: Let's say I have a model A. Model A is an inline of model B. User U has full access to model B, but only change permiss...
Django Inlines user permissions + view only - permissions issues
I'm not sure if this is a bug or I'm just missing something (although I have already parsed the documentation about inlines), but: Let's say I have a model A. Model A is an inline of model B. User U has full access to model B, but only change permissions to model A (so, no add, nor delete). However, when editing model ...
[ "If I want a read-only version of what's in the admin, I just write some normal Django views and keep them out of the admin.\nI don't think the kind of thing you're talking about (allowing changes to an object but not its inlines) is really supported by the admin. Don't get me wrong: the admin is very flexible and...
[ 2 ]
[]
[]
[ "django", "inlines", "permissions", "python" ]
stackoverflow_0002858040_django_inlines_permissions_python.txt
Q: Parse items from text file I have a text file that includes data inside {[]} tags. What would be the suggested way to parse that data so I can just use the data inside the tags? Example text file would look like this: 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some i...
Parse items from text file
I have a text file that includes data inside {[]} tags. What would be the suggested way to parse that data so I can just use the data inside the tags? Example text file would look like this: 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.' I would like ...
[ "I would use regular expressions. This answer assumes that none of the tag characters {}[] appear within other tag characters.\nimport re\ntext = 'this is a bunch of text that is not {[really]} useful in any {[way]}. I need to {[get]} some items {[from]} it.'\n\nfor s in re.findall(r'\\{\\[(.*?)\\]\\}', text):\n ...
[ 6, 3, 2, 1 ]
[]
[]
[ "python", "string", "text_processing" ]
stackoverflow_0003040115_python_string_text_processing.txt
Q: Pylons and NodeJS / Comet I'm building Pylons web applications that use a lot of jQuery and AJAX/JSON to make these apps more Web 2.0'ie. I've been looking at the server push technologies and have questions about how to do this with Pylons. I've looked at Comet and NodeJS (though I don't know much about NodeJS ye...
Pylons and NodeJS / Comet
I'm building Pylons web applications that use a lot of jQuery and AJAX/JSON to make these apps more Web 2.0'ie. I've been looking at the server push technologies and have questions about how to do this with Pylons. I've looked at Comet and NodeJS (though I don't know much about NodeJS yet) and am confused about what w...
[ "Pylons is unlikely to help you with \"Comet\" (aka Server Push) Comet relies on \"seeping\" data over connections open for long time. Pylons is WSGI in the core - which really precludes long-open connections.\nYou will likely need a separate ASYNCHRONOUS messaging server that will be your \"comet\" server.\nFor st...
[ 4, 1 ]
[]
[]
[ "ajax", "jquery", "pylons", "python" ]
stackoverflow_0003077490_ajax_jquery_pylons_python.txt
Q: sine wave glissando from one pitch to another in Numpy I have been working on a program where I need to slowly and smoothly change the pitch of a sine wave from one pitch to another. I am able to get an array of the frequency the pitch should be at any given moment (for instance, [440, 526.5, 634.2 794.8, 880], t...
sine wave glissando from one pitch to another in Numpy
I have been working on a program where I need to slowly and smoothly change the pitch of a sine wave from one pitch to another. I am able to get an array of the frequency the pitch should be at any given moment (for instance, [440, 526.5, 634.2 794.8, 880], though much, much longer) but it seems I am unable to actuall...
[ "The issue is that as you ramp through the frequencies, each frequency effectively has a different phase for the given time. When you scroll through these phases quickly and continuously, they drive the sine wave at higher frequency (or lower is also possible). \nImagine, for example, that you changed the frequen...
[ 11, 0 ]
[]
[]
[ "audio", "math", "numpy", "python", "trigonometry" ]
stackoverflow_0003089832_audio_math_numpy_python_trigonometry.txt
Q: Help with py2exe error I'm trying to compile to an exe my script of python, but I'm getting an error that I'm not know how to resolve... my script include this libraries import pyHook import pythoncom import time import win32com.client and the py2exe script is from distutils.core import setup import py2exe import...
Help with py2exe error
I'm trying to compile to an exe my script of python, but I'm getting an error that I'm not know how to resolve... my script include this libraries import pyHook import pythoncom import time import win32com.client and the py2exe script is from distutils.core import setup import py2exe import sys sys.argv.append('py2ex...
[ "Try bundle_files=3 :\nhttp://mail.python.org/pipermail/python-win32/2009-June/009227.html\n" ]
[ 0 ]
[]
[]
[ "py2exe", "python", "windows" ]
stackoverflow_0003089677_py2exe_python_windows.txt
Q: In Pylons, how do I perform actions after writing the response? In a pylons controller, I would like to first return the response to the request (so that the user gets a response ASAP), and then perform some additional operations (say, updating view counts, etc.) that didn't need to happen to generate the response...
In Pylons, how do I perform actions after writing the response?
In a pylons controller, I would like to first return the response to the request (so that the user gets a response ASAP), and then perform some additional operations (say, updating view counts, etc.) that didn't need to happen to generate the response. What's the best-practice for doing things like this? Thanks!
[ "On most wsgi-based servers (like the standard wsgiref, nwsgi etc) there is a way to send some portion of a body out work a little more and send some more. I guess the \"send some more\" is optional. \nUse yield instead of return. WSGI example (not sure if it translates well into Pylons):\ndef application(environ, ...
[ 1, 0 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002907966_pylons_python.txt
Q: OpenSSL for HTTPS without a certificate I'm looking to create an application in Django which will allow for each client to point their domain to my server. At this point, I would want their domain to be accessed via https protocol and have a valid SSL connection. With OpenSSL, more specifically M2Crypto, can I do ...
OpenSSL for HTTPS without a certificate
I'm looking to create an application in Django which will allow for each client to point their domain to my server. At this point, I would want their domain to be accessed via https protocol and have a valid SSL connection. With OpenSSL, more specifically M2Crypto, can I do this right out the gate? Or, do I still need ...
[ "You will need a certificate, but there are even free SSL certs now that work in most common browsers.\nFor very low volume site you could let M2Crypto handle SSL. However, for any public service you should go with a regular server to handle the SSL.\nIn theory you can serve multiple SSL domains from the same IP ad...
[ 3, 2 ]
[]
[]
[ "m2crypto", "openssl", "python", "ssl" ]
stackoverflow_0003078487_m2crypto_openssl_python_ssl.txt
Q: WHich framework should i use for building ecommerce site in Python I have chosen Python as a langauge to build my ecommerce webiste. The site will contains 1)Logins 2)registration 3)SHop Cart 4)Payment gateway 5)Admin can edit some content pages I have started learning basic python. But i want to build website an...
WHich framework should i use for building ecommerce site in Python
I have chosen Python as a langauge to build my ecommerce webiste. The site will contains 1)Logins 2)registration 3)SHop Cart 4)Payment gateway 5)Admin can edit some content pages I have started learning basic python. But i want to build website and i have to start with one framework the web users can vary fromm 100's ...
[ "I bet you already reviewed your choices:\nhttp://wiki.python.org/moin/WebFrameworks\nIf you understand the value proposition of using SQLAlchemy (as compared to being forced to do \"ActiveRecord\" style database (non)abstraction) stick with those platforms that offer native support for SQLAlchemy. Mastering it = h...
[ 7, 4, 0 ]
[]
[]
[ "frameworks", "python" ]
stackoverflow_0003089554_frameworks_python.txt
Q: problem with inheritance in python in school we got this class file: class Konto: def __init__(self, nummer): self.__nr = nummer self.__stand = 0 self.__minimum = -1000.0 def getStand(self): return self.__stand def getNr(self): return self.__nr def einzahl...
problem with inheritance in python
in school we got this class file: class Konto: def __init__(self, nummer): self.__nr = nummer self.__stand = 0 self.__minimum = -1000.0 def getStand(self): return self.__stand def getNr(self): return self.__nr def einzahlen(self, betrag): self.__stand =...
[ "Daniel was halfway there, you do need to change self.__einzahlen -> self.einzaheln, as he said.\nAlso, self.__stand belongs to the parent class. With the double underscore in the name, it gets mangled used anywhere else. But you don't need to use self.__stand directly. Konto gives you getStand().\nTry something l...
[ 2, 1, 1 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0003090683_inheritance_python.txt
Q: How to improve the performance? I had prepared a project on making a software application. It is complete and working fine except that the speed of execution is very slow.. I have taken several chunks of code and optimized it.. I tried psyco.. ie I installed psyco and added two lines on the top of my code import p...
How to improve the performance?
I had prepared a project on making a software application. It is complete and working fine except that the speed of execution is very slow.. I have taken several chunks of code and optimized it.. I tried psyco.. ie I installed psyco and added two lines on the top of my code import psyco psyco.full() Don't know whether...
[ "You could get a lot better performance if you could switch to binary file formats. Most of your code is doing parsing and string manipulation. You're doing a lot of converting strings to floats, which is slower than you think.\n", "You are unlikely to see a 5x performance difference by just tweaking the code aro...
[ 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "optimization", "psyco", "python" ]
stackoverflow_0003090397_optimization_psyco_python.txt
Q: What is the lightest way of doing this task? I have a file whose contents are of the form: .2323 1 .2327 1 .3432 1 .4543 1 and so on some 10,000 lines in each file. I have a variable whose value is say a=.3344 From the file I want to get the row number of the row whose first column is closest to this variab...
What is the lightest way of doing this task?
I have a file whose contents are of the form: .2323 1 .2327 1 .3432 1 .4543 1 and so on some 10,000 lines in each file. I have a variable whose value is say a=.3344 From the file I want to get the row number of the row whose first column is closest to this variable...for example it should give row_num='3' as .34...
[ "Is the data in the file sorted in numerical order? Are all the lines of the same length? If not, the simplest approach is best. Namely, reading through the file line by line. There's no need to store more than one line in memory at a time.\nCode:\ndef closest(num):\n closest_row = None\n closest_value = No...
[ 3, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003090746_python.txt
Q: +\ operator in Python What does the +\ operator do in Python? I came across this piece of code - rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'+\ 's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996'%t +\ '&ignore=.csv').readlines( ) and can't find any references that explain it. A: The + is addition....
+\ operator in Python
What does the +\ operator do in Python? I came across this piece of code - rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'+\ 's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996'%t +\ '&ignore=.csv').readlines( ) and can't find any references that explain it.
[ "The + is addition. The \\ at the end of the line continues the current statement or expression on the next line.\n", "N.B. The \\ continuation is unnecessary in this case since the expression is inside parentheses. Python is smart enough to know that a line continues until all brackets, braces and parentheses a...
[ 18, 11, 7, 1 ]
[]
[]
[ "operators", "python", "string" ]
stackoverflow_0003090780_operators_python_string.txt
Q: Disable (mako) template caching in Pylons 1.0 I recently jumped on a project using Pylons. I'm not familiar with either Python or Pylons, but I haven't had very much trouble getting the hang of things. Pylon projects seem to cache templates indefinitely by default and I can't figure out a way to clear the cached t...
Disable (mako) template caching in Pylons 1.0
I recently jumped on a project using Pylons. I'm not familiar with either Python or Pylons, but I haven't had very much trouble getting the hang of things. Pylon projects seem to cache templates indefinitely by default and I can't figure out a way to clear the cached templates (stored by default in /data/templates) exc...
[ "The problem was entirely something else..\nPylons always caches templates, but updates its template cache automatically by comparing the last-modified timestamp of the template and its cached version. The problem had to do with synchronizing the server's clock with real time.\nIt was a couple minutes ahead and upl...
[ 2, 1 ]
[]
[]
[ "caching", "mako", "pylons", "python" ]
stackoverflow_0003089114_caching_mako_pylons_python.txt
Q: Python ? (conditional/ternary) operator for assignments C and many other languages have a conditional (AKA ternary) operator. This allows you to make very terse choices between two values based on the truth of a condition, which makes expressions, including assignments, very concise. I miss this because I find th...
Python ? (conditional/ternary) operator for assignments
C and many other languages have a conditional (AKA ternary) operator. This allows you to make very terse choices between two values based on the truth of a condition, which makes expressions, including assignments, very concise. I miss this because I find that my code has lots of conditional assignments that take four...
[ "Python has such an operator:\nvariable = something if condition else something_else\n\nAlternatively, although not recommended (see karadoc's comment):\nvariable = (condition and something) or something_else\n\n", "In older Python code, you may see the trick:\ncondition and something or something_else\n\nHowever...
[ 235, 21 ]
[]
[]
[ "c", "language_features", "python" ]
stackoverflow_0003091316_c_language_features_python.txt
Q: In Amazon EC2, how do I make it run a python script when I "clone" that instance? Suppose I have a script in /home/myuser/go.py How do I run that script, when a new instance is booted? (I'm used to using the point-and-click control panel Amazon has...) A: I'm gonna try my nonexistent Linux skills here - creat...
In Amazon EC2, how do I make it run a python script when I "clone" that instance?
Suppose I have a script in /home/myuser/go.py How do I run that script, when a new instance is booted? (I'm used to using the point-and-click control panel Amazon has...)
[ "I'm gonna try my nonexistent Linux skills here - create a shell script that runs your go.py and add a symlink to the shell script in /etc/init.d/\n/home/myser/go.sh\n#!/bin/bash\npython /home/myuser/go.py\n\nsymlink\nln -s /etc/init.d/go.sh /home/myuser/go.sh\n\n\nAfter reading up a bit myself, /etc/rc.local is pr...
[ 2 ]
[]
[]
[ "amazon_ec2", "amazon_web_services", "linux", "python", "unix" ]
stackoverflow_0003091454_amazon_ec2_amazon_web_services_linux_python_unix.txt
Q: Where to trigger ast modifications in Python? I'm doing some AST modifications in Python. This may be done for optimization purpose or other. Where is the right place to put it, so when you do something like: python myfile.py or python runserver.py myapp the modifications took place for every .py executed file? ...
Where to trigger ast modifications in Python?
I'm doing some AST modifications in Python. This may be done for optimization purpose or other. Where is the right place to put it, so when you do something like: python myfile.py or python runserver.py myapp the modifications took place for every .py executed file?
[ "Put your modifications in a site.py or sitecustomize.py (Python < 2.6) file (in the lib/site-packages directory ; Python will try to import and run it @ interpreter startup).\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003091544_python.txt
Q: MacOS X Error when installing python MySQLdb I am trying to install python mysqldb in my mac but I got the following errors. For mysql I am using the one that is bundled with MAMP. Thanks! here is the error message: running build running build_py copying MySQLdb/release.py -> build/lib.darwin-8.11.1-i386-2.3/MySQL...
MacOS X Error when installing python MySQLdb
I am trying to install python mysqldb in my mac but I got the following errors. For mysql I am using the one that is bundled with MAMP. Thanks! here is the error message: running build running build_py copying MySQLdb/release.py -> build/lib.darwin-8.11.1-i386-2.3/MySQLdb running build_ext building '_mysql' extension g...
[ "I guess it's not enough to use the MySQL that's bundled with MAMP, as it does not contain the C development tools for MySQL (i.e. the header files such as mysql.h). Here is a step-by-step tutorial on compiling the MySQL extension for Python on Mac OS X, but it looks like you will need the \"official\" MySQL distri...
[ 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0003090709_mysql_python.txt
Q: Copy files to network path or drive using python on OSX I have a similar question like the one asked here but I need it to work on OSX. How to copy files to network path or drive using Python So i want to save a file on a SMB network share. Can this be done? Thanks! A: Yes, it can be done. First, mount your SMB...
Copy files to network path or drive using python on OSX
I have a similar question like the one asked here but I need it to work on OSX. How to copy files to network path or drive using Python So i want to save a file on a SMB network share. Can this be done? Thanks!
[ "Yes, it can be done. First, mount your SMB network share to the local filesystem by calling a command like this from Python:\nmount -t smbfs //user@server/sharename share\n\n(You can do it using the subprocess module). share is the name of the directory where the SMB network share will be mounted to, and I guess i...
[ 19 ]
[]
[]
[ "macos", "network_programming", "python", "smb" ]
stackoverflow_0003090724_macos_network_programming_python_smb.txt
Q: Django: Call self function inside a Django model I want to call for a self function of a model class as such in upload_to: class Foo(models.Model): filestack = models.FileField(upload_to=self. gen_save_path) def gen_save_path(self): """ gen_save_path: void -> String Generates the p...
Django: Call self function inside a Django model
I want to call for a self function of a model class as such in upload_to: class Foo(models.Model): filestack = models.FileField(upload_to=self. gen_save_path) def gen_save_path(self): """ gen_save_path: void -> String Generates the path as a string for fileStack field. """ ...
[ "filestack is a class attribute and while declaring it you can not use self as there is no object of class (self) yet created, anyway according to django docs upload_to takes two arguments, instance (An instance of the model where the FileField is defined) and filename (The filename that was originally given to the...
[ 5 ]
[ "I think this will work if you use a lambda function:\nclass Foo(models.Model):\n filestack = models.FileField(upload_to=lambda: self.gen_save_path())\n\n def gen_save_path(self):\n \"\"\"\n gen_save_path: void -> String\n Generates the path as a string for fileStack field.\n \"\"\...
[ -2, -2 ]
[ "django", "django_models", "python" ]
stackoverflow_0003091667_django_django_models_python.txt
Q: question regarding universal feed parser I faced a problem grabbing the content from a couple of blog feeds I have crawled. I'm uncertain what is the reason, but by parsing one or two blogs with the feedparser returns me this particular error: results = feedparser.parse(url) ent = [] for entry in results.ent...
question regarding universal feed parser
I faced a problem grabbing the content from a couple of blog feeds I have crawled. I'm uncertain what is the reason, but by parsing one or two blogs with the feedparser returns me this particular error: results = feedparser.parse(url) ent = [] for entry in results.entries: e = {} e['title'] = entry.titl...
[ "There is a mapping between the XML tags used in the feed and the attributes available on the entries in feedparser. View the source of one of the feeds that has been causing the problem and see what tags it uses. You might find it doesn't include content for the entries or that the links are in a field like uid ra...
[ 1 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0003091476_feedparser_python.txt
Q: does google app engine display unicode differently in StringProperty v StringListProperty objs? I have a db.StringProperty() mRegion that is set to some Korean text. I see in my Dashboard that the value is visibly in Korean like this: 한국 : 충청남도 However, when I take this field and add it into a string list propert...
does google app engine display unicode differently in StringProperty v StringListProperty objs?
I have a db.StringProperty() mRegion that is set to some Korean text. I see in my Dashboard that the value is visibly in Korean like this: 한국 : 충청남도 However, when I take this field and add it into a string list property (db.StringListProperty()) I end up with something like this: \ud55c\uad6d : \ucda9\uccad\ub0a8\ub3c...
[ "It's quite possible that the admin interface displays the two differently, yes. In the latter case it's clearly doing a repr(s), while in the former it's just printing the string.\nThe admin interface's interface doesn't affect how your code works, though - both Strings and StringLists are stored the same way in t...
[ 2 ]
[]
[]
[ "google_app_engine", "python", "string" ]
stackoverflow_0003091034_google_app_engine_python_string.txt
Q: Python script to read from a file and get values If in a file the values present are in either " or , separated values "Name" "Tom" "CODE 041" "Has" "Address" "NSYSTEMS c/o" "First Term" "123" 18 "Occ" "Engineer" "Level1" "JT" 18 How should the python script be written so as to get al...
Python script to read from a file and get values
If in a file the values present are in either " or , separated values "Name" "Tom" "CODE 041" "Has" "Address" "NSYSTEMS c/o" "First Term" "123" 18 "Occ" "Engineer" "Level1" "JT" 18 How should the python script be written so as to get all the above values individually
[ "Your question is a little vague, and there are no commas in your example, so it's a bit hard to provide a good answer.\nOn your example file containing\n\"Name\" \"Tom\" \"CODE 041\" \"Has\"\n\"Address\" \"NSYSTEMS c/o\" \"First Term\" \"123\" 18 \n\"Occ\" \"Engineer\" \"Level1\" \"JT\" 18\n\nthis script\nimport ...
[ 3, 1, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003091976_file_io_python.txt
Q: Python time.gmtime() returning time that's 5 hours ahead of system time I have been scouring the google machine and have come up with nothing to answer this. When making calls to: time.gmtime() This ends up returning a time, as the subject line says, 5 hours ahead of my system time. I cannot figure out what i...
Python time.gmtime() returning time that's 5 hours ahead of system time
I have been scouring the google machine and have come up with nothing to answer this. When making calls to: time.gmtime() This ends up returning a time, as the subject line says, 5 hours ahead of my system time. I cannot figure out what is going on. time.tzname() returns the proper timezone. Aside from setting pyt...
[ "Have you tried moving to London? I think that will solve your problem. :)\n", "Are you looking for time.localtime? As docs say time.gmtime returns time struct in UTC.\n", "time.gmtime() returns Greenwich Mean Time. This is five hours ahead of Eastern Standard Time, for example; taking into account daylight sav...
[ 20, 6, 5 ]
[]
[]
[ "python", "time", "timezone" ]
stackoverflow_0003092479_python_time_timezone.txt
Q: Django: custom serialization options? I'm working on a Django-based web service and I'm trying to figure out what the best way to do my serialization will be. The tricky requirement, though, is that I'd like to have pretty much full control over format of, and fields contained in, the response. For example, the Dj...
Django: custom serialization options?
I'm working on a Django-based web service and I'm trying to figure out what the best way to do my serialization will be. The tricky requirement, though, is that I'd like to have pretty much full control over format of, and fields contained in, the response. For example, the Django serializers (which, unfortunately, inc...
[ "Have you looked at django-piston? It should have a bunch of stuff to make this easier.\n(Not sure about serialization specifically, but Django RESTy web services.)\n", "When I need some custom serialization really fast and my case doesn't require deserialization I just write django template that can make any for...
[ 1, 1, 1 ]
[]
[]
[ "django", "django_piston", "python", "serialization" ]
stackoverflow_0003055650_django_django_piston_python_serialization.txt
Q: Python dynamically importing a script, need to have its __name__ == "__main__" code to be called While importing a python script from another script I want the script code that is classically protected by if __name__ == "__main__": .... .... to be run, how can I get that code run? What I am trying to...
Python dynamically importing a script, need to have its __name__ == "__main__" code to be called
While importing a python script from another script I want the script code that is classically protected by if __name__ == "__main__": .... .... to be run, how can I get that code run? What I am trying to do is from a python script, dynamically change a module then import an existing script which should s...
[ "If you can edit the file being imported, one option is to follow the basic principle of putting important code inside of functions.\n# Your script.\nimport foo\n\nfoo.main()\n\n# The file being imported.\ndef main():\n print \"running foo.main()\"\n\nif __name__ == \"__main__\":\n main()\n\nIf you can't edit...
[ 6 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003092319_import_python.txt
Q: Increasing throughput in a python script I'm processing a list of thousands of domain names from a DNSBL through dig, creating a CSV of URLs and IPs. This is a very time-consuming process that can take several hours. My server's DNSBL updates every fifteen minutes. Is there a way I can increase throughput in my Py...
Increasing throughput in a python script
I'm processing a list of thousands of domain names from a DNSBL through dig, creating a CSV of URLs and IPs. This is a very time-consuming process that can take several hours. My server's DNSBL updates every fifteen minutes. Is there a way I can increase throughput in my Python script to keep pace with the server's upd...
[ "The vast majority of the time here is spent in the external calls to dig, so to improve that speed, you'll need to multithread. This will allow you to run multiple calls to dig at the same time. See for example: Python Subprocess.Popen from a thread . Or, you can use Twisted ( http://twistedmatrix.com/trac/ ).\n...
[ 2, 2, 0, 0 ]
[]
[]
[ "python", "python_multithreading", "unix" ]
stackoverflow_0003089413_python_python_multithreading_unix.txt
Q: Python C API: Switch on PyObject type I have some code to interface Python to C++ which works fine but every time I look at it I think there must be a better way to do it. On the C++ side there is a 'variant' type that can deal with a fixed range of basic types - int, real, string, vector of variants, etc. I hav...
Python C API: Switch on PyObject type
I have some code to interface Python to C++ which works fine but every time I look at it I think there must be a better way to do it. On the C++ side there is a 'variant' type that can deal with a fixed range of basic types - int, real, string, vector of variants, etc. I have some code using the Python API to convert...
[ "In a way, I think you've answered your own question.\nSomewhere, you're going to have to select functionality based on data. The way to do this in C is to use function pointers.\nCreate a map of object_type->function mappers... where each function has a clearly-defined interface.\nvariant PyBoolToVariant(PyObject ...
[ 3 ]
[]
[]
[ "c", "python", "python_c_api", "python_c_extension" ]
stackoverflow_0003092786_c_python_python_c_api_python_c_extension.txt
Q: python listen 2 port same file I would like to listen on 2 different UDP port with the same server. I use SocketServer lib for my server, and basicly it looks like that; SocketServer.UDPServer(('', 7878),CLASSNAME) I would like to listen on 7878 and 7879 with the same server and same file. Is that possible? If yes...
python listen 2 port same file
I would like to listen on 2 different UDP port with the same server. I use SocketServer lib for my server, and basicly it looks like that; SocketServer.UDPServer(('', 7878),CLASSNAME) I would like to listen on 7878 and 7879 with the same server and same file. Is that possible? If yes how?
[ "Sure you can, using threads. Here's a server:\nimport SocketServer\nimport threading\n\n\nclass MyUDPHandler(SocketServer.BaseRequestHandler):\n def handle(self):\n data = self.request[0].strip()\n socket = self.request[1]\n print \"%s wrote:\" % self.client_address[0]\n print data\n...
[ 3, 1, 0 ]
[]
[]
[ "python", "socketserver", "udp" ]
stackoverflow_0002069566_python_socketserver_udp.txt
Q: How to use Python files spread out over many folders, or: how to organize a project I am looking to make my project fulfill the guidelines described here: http://infinitemonkeycorps.net/docs/pph/. I currently have the following directories: src/ test/ doc/ I would really like to organize my src/ file as follows: ...
How to use Python files spread out over many folders, or: how to organize a project
I am looking to make my project fulfill the guidelines described here: http://infinitemonkeycorps.net/docs/pph/. I currently have the following directories: src/ test/ doc/ I would really like to organize my src/ file as follows: src/ similar_files/ other_files/ helpers/ etc However, I'm not familiar with...
[ "You'll want to read the tutorial.. here! :D\nSection 6.4.2 also contains the references that would assist you.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003093249_python.txt
Q: Python: Object assignment with variable argument list Is there a method to pass a variable number of arguments to a function and have it change those arguments using the ( *args, **keywords ) style of argument passing? I've tried a few things but either see no change or have an error raised by the compiler: def f...
Python: Object assignment with variable argument list
Is there a method to pass a variable number of arguments to a function and have it change those arguments using the ( *args, **keywords ) style of argument passing? I've tried a few things but either see no change or have an error raised by the compiler: def foo( *args ): args[0] = 4 This gets me TypeError: objec...
[ "No - Python uses call by object-sharing, also known as call-by-value.\nTo clarify the terminology: you are not receiving a deep copy of the object, but a copy of the object reference. Note: this is not the same as call-by-reference! You can think of it as call by value, and that the values are references to object...
[ 4, 3, 1 ]
[]
[]
[ "arguments", "python", "variadic_functions" ]
stackoverflow_0003093352_arguments_python_variadic_functions.txt
Q: What is affected by ReferenceProperty? In reference to these two questions (see links below) and the Google AppEngine doc, I got a little bit confused: class Author(db.Model): name = db.StringProperty() class Story(db.Model): author = db.ReferenceProperty(Author) story = db.get(story_key) author_name = s...
What is affected by ReferenceProperty?
In reference to these two questions (see links below) and the Google AppEngine doc, I got a little bit confused: class Author(db.Model): name = db.StringProperty() class Story(db.Model): author = db.ReferenceProperty(Author) story = db.get(story_key) author_name = story.author.name Source: Google The doc ex...
[ "The notion of ownership here is purely semantic, ReferenceProperty fields are only used for navigability.\n", "References imply only referentiality - a \"has a\" relationship, if you like - not ownership. In your example, a Story \"has an\" Author. Another way to think about it is in the same way you would use a...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "gql", "python" ]
stackoverflow_0003093288_google_app_engine_gql_python.txt
Q: Removing spaces and newlines between tags in html (aka unformatting) in python An example: <p> Hello</p> <div>hgello</div> <pre> code code <pre> turns in something like: <p> Hello</p><div>hgello</div><pre> code code <pre> How to do this in python? I make also intensive use of < pre> tags so subst...
Removing spaces and newlines between tags in html (aka unformatting) in python
An example: <p> Hello</p> <div>hgello</div> <pre> code code <pre> turns in something like: <p> Hello</p><div>hgello</div><pre> code code <pre> How to do this in python? I make also intensive use of < pre> tags so substituting all '\n' with '' is not an option. What's the best way to do that?
[ "You could use re.sub(\">\\s*<\",\"><\",\"[here your html string]\").\nMaybe string.replace(\">\\n\",\">\"), i.e. look for an enclosing bracket and a newline and remove the newline.\n", "I would choose to use the python regex:\nstring.replace(\">\\s+<\",\"><\")\n\nWhere the '\\s' finds any whitespace character an...
[ 6, 2 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0003093802_html_python_regex.txt
Q: is ready made vmware images good for python website development I tried a lot and was not able to set python with django and wastd full day. I just found this http://bitnami.org/stack/djangostack Is that good for development and alos does it has mod_wsgi enabled on apache. I want to make sure that , everything is ...
is ready made vmware images good for python website development
I tried a lot and was not able to set python with django and wastd full day. I just found this http://bitnami.org/stack/djangostack Is that good for development and alos does it has mod_wsgi enabled on apache. I want to make sure that , everything is ok , so that i can start building app on this IF there are any other ...
[ "http://www.instantdjango.com is a good click-and-go dev stack for Windows users. It bundles Python which is otherwise 80% of the hassle.\nI suggest you be cautious when you deploy to a server though as a Django install on Linux may differ... But that's a problem you've got some time to think about.\n" ]
[ 0 ]
[]
[]
[ "python", "vmware" ]
stackoverflow_0003092907_python_vmware.txt
Q: How to run a clean up when terminating Python script I have a python script that does some jobs. I use multiprocessing.Pool to have a few workers do some commands for me. My problem is when I try to terminate the script. When I press Ctrl-C, I would like, that every worker immediately cleans up its experiment (whi...
How to run a clean up when terminating Python script
I have a python script that does some jobs. I use multiprocessing.Pool to have a few workers do some commands for me. My problem is when I try to terminate the script. When I press Ctrl-C, I would like, that every worker immediately cleans up its experiment (which is some custom code, or actually even a subprocess comm...
[ "How about trying the atexit standard module?\nIt allows you to register a function that will be executed upon termination.\n", "Are you working with Unix? If yes, why not catch SIGTERM in the subprocesses? In fact, the documentation of Process.terminate() reads:\nTerminate the process. On Unix this is done usi...
[ 2, 0 ]
[]
[]
[ "multiprocessing", "python", "terminate" ]
stackoverflow_0003090661_multiprocessing_python_terminate.txt
Q: Dynamically set inheritance in Python I have class A that is supposed to inherit class B whose name is not yet known at the time of A being written. Is it possible to declare A not inheriting anything, and add B as the base class during A's instantiation? Example: First file class B: def __init__(self): self...
Dynamically set inheritance in Python
I have class A that is supposed to inherit class B whose name is not yet known at the time of A being written. Is it possible to declare A not inheriting anything, and add B as the base class during A's instantiation? Example: First file class B: def __init__(self): self.__name = "Class B" def name(self): ...
[ "Yeah, you can accomplish this with metaclasses. It's not the easiest topic to wrap your head around but it'll do the job. There's a Stack Overflow question about them that looks like it has some good information and I also found an IBM article that might help as well. Somewhere in the official Python documentation...
[ 2 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0003094265_inheritance_python.txt
Q: determining if process has terminated successfully I have some code to execute the unix shell command in background in python import subprocess process = subprocess.Popen('find / > tmp.txt &',shell=True) I need to capture the scenario where i come to know that process has finished successful completion . Plea...
determining if process has terminated successfully
I have some code to execute the unix shell command in background in python import subprocess process = subprocess.Popen('find / > tmp.txt &',shell=True) I need to capture the scenario where i come to know that process has finished successful completion . Please explain with sample code Tazim
[ "There is no need for the &: the command is launched in a separate process, and runs independently.\nIf you want to wait until the process terminates, use wait():\nprocess = subprocess.Popen('find / > tmp.txt', shell = True)\nexitcode = process.wait()\nif exitcode == 0:\n # successful completion\nelse:\n # er...
[ 4, 2 ]
[]
[]
[ "bash", "python", "unix" ]
stackoverflow_0003084214_bash_python_unix.txt
Q: Quickest language to make a little 'Connect to a SSL webpage' script I just need some advice. I already know how to play with bash, ruby, python and perl and I'd like to know: with which of them would it be faster to make a little script that would connect to a website with SSL and login. I just need to do this sc...
Quickest language to make a little 'Connect to a SSL webpage' script
I just need some advice. I already know how to play with bash, ruby, python and perl and I'd like to know: with which of them would it be faster to make a little script that would connect to a website with SSL and login. I just need to do this script and make a cron job with it. So it must be executable from the consol...
[ "I don't know about the others so can't compare, but in Perl, it's quick and easy with WWW::Mechanize or LWP\n", "You could look at Scrubyt if you are familiar with ruby.\nan example from http://github.com/scrubber/scrubyt_examples/blob/master/ebay.rb\n#simple ebay example\n\nrequire 'rubygems'\nrequire 'scrubyt'...
[ 5, 2 ]
[]
[]
[ "bash", "perl", "python", "ruby", "ssl" ]
stackoverflow_0003094138_bash_perl_python_ruby_ssl.txt
Q: Google App Engine django model form does not pick up BlobProperty I have the following model: class Image(db.Model): auction = db.ReferenceProperty(Auction) image = db.BlobProperty() thumb = db.BlobProperty() caption = db.StringProperty() item_to_tag = db.StringProperty() And the following for...
Google App Engine django model form does not pick up BlobProperty
I have the following model: class Image(db.Model): auction = db.ReferenceProperty(Auction) image = db.BlobProperty() thumb = db.BlobProperty() caption = db.StringProperty() item_to_tag = db.StringProperty() And the following form: class ImageForm(djangoforms.ModelForm): class Meta: mode...
[ "I think my problem hinges on the fact that Django does not support blobs, so the BlobProperty is simply ignored when generating Django forms.\n", "You can use the widgets attribute to define the field type used for your blob properties:\nclass ImageForm(djangoforms.ModelForm):\nclass Meta:\n model = Image\n ...
[ 1, 0 ]
[]
[]
[ "django_forms", "google_app_engine", "python" ]
stackoverflow_0003033945_django_forms_google_app_engine_python.txt
Q: Python Glade could not create GladeXML Object I've created a simple window GUI in Glade 3.6.7 and I am trying to import it into Python. Every time I try to do so I get the following error: (queryrelevanceevaluation.py:8804): libglade-WARNING **: Expected <glade-interface>. Got <interface>. (queryrelevanceevalu...
Python Glade could not create GladeXML Object
I've created a simple window GUI in Glade 3.6.7 and I am trying to import it into Python. Every time I try to do so I get the following error: (queryrelevanceevaluation.py:8804): libglade-WARNING **: Expected <glade-interface>. Got <interface>. (queryrelevanceevaluation.py:8804): libglade-WARNING **: did not finish...
[ "You have created a GtkBuilder file instead of Glade file.\nYou can use GtkBuilder as follow:\nbuilder = gtk.Builder()\nbuilder.add_from_string(string, len(string))\nbuilder.connect_signals(anobject)\nbuilder.get_object(name)\n\nEDIT:\nWhen you start a new project in glade it asks you if you want create a glade fil...
[ 23, 5 ]
[]
[]
[ "exception", "glade", "python", "user_interface" ]
stackoverflow_0002668618_exception_glade_python_user_interface.txt
Q: Segmentation fault while embedding python in ubuntu I have an application where I'm embedding python. It was developed on windows where it works fine, but now I'm porting it to linux with less success where it crashes in Py_Initialize(). From gdb, it seems to happen when loading the os module. gdb reports this cal...
Segmentation fault while embedding python in ubuntu
I have an application where I'm embedding python. It was developed on windows where it works fine, but now I'm porting it to linux with less success where it crashes in Py_Initialize(). From gdb, it seems to happen when loading the os module. gdb reports this callstack on seg fault: #0 0x002384fc in import_submodule (...
[ "Try setting the Python home with Py_SetPythonHome before calling Py_Initialize. Start with hardcoded complete path to the python directory. Also make sure you are not mixing debug & release versions. Py_GetPath is a good API to see where all python is looking for modules - but dont know if it can be called before ...
[ 2 ]
[]
[]
[ "debugging", "linux", "python", "shared_libraries" ]
stackoverflow_0003094166_debugging_linux_python_shared_libraries.txt
Q: How does import keyword in python actually work? Let's say I have 3 files: a.py from d import d class a: def type(self): return "a" def test(self): try: x = b() except: print "EXCEPT IN A" from b import b x = b() return x.type...
How does import keyword in python actually work?
Let's say I have 3 files: a.py from d import d class a: def type(self): return "a" def test(self): try: x = b() except: print "EXCEPT IN A" from b import b x = b() return x.type() b.py import sys class b: def __init__(self): ...
[ "I guess it's a problem of scoping, if you import a module in your constructor you can only use it in your constructor, after the import statement.\n", "According to the Python documentation,\n\nImport statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or na...
[ 3, 2, 1, 0 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0003094506_import_module_python.txt
Q: how to load a big file and cut it into smaller files? I have file about 4MB (which i called as big one)...this file has about 160000 lines..in a specific format...and i need to cut them at regular interval(not at equal intervals) i.e at the end of a certain format and write the part into another file.. Basically,w...
how to load a big file and cut it into smaller files?
I have file about 4MB (which i called as big one)...this file has about 160000 lines..in a specific format...and i need to cut them at regular interval(not at equal intervals) i.e at the end of a certain format and write the part into another file.. Basically,what i wanted is to copy the information for the big file in...
[ "I would first read all of the allegedly-big file in memory as a list of lines:\nwith open('socalledbig.txt', 'rt') as f:\n lines = f.readlines()\n\nshould take little more than 4MB -- tiny even by the standard of today's phones, much less ordinary computers.\nThen, perform whatever processing you need to determ...
[ 2, 1, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0003094618_file_python.txt
Q: does write mode create a new file if not existing? I'm trying to write to a file that does not already exist using a file context manager. a=open ('C:/c.txt' , 'w') The above does not succeed. How would I create a file for writing if it does already exist? A: Yes, 'w' is specified as creating a new file -- as t...
does write mode create a new file if not existing?
I'm trying to write to a file that does not already exist using a file context manager. a=open ('C:/c.txt' , 'w') The above does not succeed. How would I create a file for writing if it does already exist?
[ "Yes, 'w' is specified as creating a new file -- as the docs put it,\n\n'w' for writing (truncating the file\n if it already exists),\n\n(clearly inferring it's allowed to not already exist). Please show the exact traceback, not just your own summary of it, as details matters -- e.g. if the actual path you're usi...
[ 30, 4, 3, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003094986_file_io_python.txt
Q: Potential Multiple installations of Python on Windows I ran into the following problem: I need to supply the installation package to the client. Part of the code is python, so I have to make sure that it is installed. I am using NSIS for the installation ans would like to install python into a predefined by me fol...
Potential Multiple installations of Python on Windows
I ran into the following problem: I need to supply the installation package to the client. Part of the code is python, so I have to make sure that it is installed. I am using NSIS for the installation ans would like to install python into a predefined by me folder (let it be c:\Program Files\Project\Python26). For that...
[ "Per the docs, options such as /p (or maybe /o or /c, depending on your exact intent) should serve your purposes.\n" ]
[ 0 ]
[]
[]
[ "python", "windows", "windows_installer" ]
stackoverflow_0003095262_python_windows_windows_installer.txt
Q: Is there a minimal style for unittests in Python? I'm wondering what techniques people use for simplifying the 'size' of code used for unit testing. For example I was trying to marshal an object of the class and testing the marshal'ed object (but this presumes marshal is working correctly). Consider the class impo...
Is there a minimal style for unittests in Python?
I'm wondering what techniques people use for simplifying the 'size' of code used for unit testing. For example I was trying to marshal an object of the class and testing the marshal'ed object (but this presumes marshal is working correctly). Consider the class import unittest class Nums(object): def __init__(self, ...
[ "I echo the comments above that you should not have test methods on the actual class you are testing. Functions like test_marshal should be placed elsewhere (assuming that they do exist for testing and not for general usage), typically in your unit test files. However, setting that aside for the moment, I'd do so...
[ 3, 2 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0003094273_python_unit_testing.txt
Q: How do I extract text between two different matches? I have a text file that has sets of text I need to extract that looks something like as follows: ITEM A blah blah blah ITEM B bloo bloo bloo ITEM A blee blee blee ITEM B Here is the working code I have so far: finda = r'(Item\sA)' findb = r'(Item\sB)' match_a =...
How do I extract text between two different matches?
I have a text file that has sets of text I need to extract that looks something like as follows: ITEM A blah blah blah ITEM B bloo bloo bloo ITEM A blee blee blee ITEM B Here is the working code I have so far: finda = r'(Item\sA)' findb = r'(Item\sB)' match_a = re.finditer(finda, usefile, 2) # the "2" is a flag to sa...
[ "why not just:\nwith open(fname, 'w') as file:\n for match in re.finditer(r'Item A(.+?)Item B', subject, re.I):\n s = match.group(1)\n if len(s) > 50:\n file.write(s)\n\nNote: using actual numerical values of flags is rather oblique, use provided in re flags.\n", "This can be done in a...
[ 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003095574_python_regex.txt
Q: Django blog generate next/previous entries In a blog application (which I have mostly built following a tutorial), I would like to have a next and previous post link on the single page views of the posts. The blog app's urls.py file looks like this: from django.conf.urls.defaults import * from django.views.generi...
Django blog generate next/previous entries
In a blog application (which I have mostly built following a tutorial), I would like to have a next and previous post link on the single page views of the posts. The blog app's urls.py file looks like this: from django.conf.urls.defaults import * from django.views.generic import list_detail from sandy.blog.models impo...
[ "You want the get_next_by_FOO() and get_previous_by_FOO() model methods.\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003095725_django_python.txt
Q: Django models.Model class member not appearing in model_instance._meta.fields I have a django.contrib.contenttypes.generic.genericForeignKeyField as a member of my model, however, it is not appearing when I instantiate the model and then try to get the fields out of the _meta of the object. e.g: class A(models...
Django models.Model class member not appearing in model_instance._meta.fields
I have a django.contrib.contenttypes.generic.genericForeignKeyField as a member of my model, however, it is not appearing when I instantiate the model and then try to get the fields out of the _meta of the object. e.g: class A(models.Model): field2 = models.IntegerField(...) field1 = generic.genericForeignKe...
[ "Your are not setting up the generic relation correctly. Read the documentation:\n\nThere are three parts to setting up a GenericForeignKey:\n\nGive your model a ForeignKey to ContentType. \nGive your model a field that can store a primary-key value from the models you'll be relating to. (For most models, this mea...
[ 1, 1 ]
[]
[]
[ "django", "generics", "metadata", "models", "python" ]
stackoverflow_0003096040_django_generics_metadata_models_python.txt
Q: In Python, what happens when you import inside of a function? What are the pros and cons of importing a Python module and/or function inside of a function, with respect to efficiency of speed and of memory? Does it re-import every time the function is run, or perhaps just once at the beginning whether or not the f...
In Python, what happens when you import inside of a function?
What are the pros and cons of importing a Python module and/or function inside of a function, with respect to efficiency of speed and of memory? Does it re-import every time the function is run, or perhaps just once at the beginning whether or not the function is run?
[ "\nDoes it re-import every time the function is run?\n\nNo; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn't actually force them to go through the whole import process again. 1\n\nDoes it import once at the beginning whether o...
[ 222, 58, 22, 10, 7, 3 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0003095071_python_python_import.txt
Q: Python xmlrpc server in windows I'm looking for a library that can help me build a good XMLRPC server in Python that could run on Windows. The SimpleXMLRPCServer class looks fine but I don't know if it will suit all my needs, since I'd like to be able to connect from multiple clients at the same time. I found this...
Python xmlrpc server in windows
I'm looking for a library that can help me build a good XMLRPC server in Python that could run on Windows. The SimpleXMLRPCServer class looks fine but I don't know if it will suit all my needs, since I'd like to be able to connect from multiple clients at the same time. I found this on GitHub, but I don't know if it'll...
[ "I like CherryPy for XMLRPC using the built-in tool/dispatcher, and it runs on Windows as far as I know.\nBut you really need to ask yourself why you want to do RPC vs. a RESTful service in 2010. XMLRPC is very limited in the variable types allowed, and adds significant encapsulation overhead, and requires a clien...
[ 1, 1, 1 ]
[]
[]
[ "python", "xml_rpc" ]
stackoverflow_0003087944_python_xml_rpc.txt
Q: python and xml integration How do I produce XML from Python? I built a program for keystroke detection integrated with open office and other softwares and i want the output of the program to be stored in an XML file? my program detects the keys stroked in an open office, ms office software. i want the outpu to be ...
python and xml integration
How do I produce XML from Python? I built a program for keystroke detection integrated with open office and other softwares and i want the output of the program to be stored in an XML file? my program detects the keys stroked in an open office, ms office software. i want the outpu to be directly stored in an XML file
[ "You should use lxml Python library.\nfrom lxml import etree\n\nroot = etree.Element(\"root\")\nroot.set(\"foo\", \"bar\")\nchild1 = etree.SubElement(root, \"spam\")\net = etree.ElementTree(root)\net.write('output_file.xml', xml_declaration=True, encoding='utf-8')\n\n", "Look into xml.dom.minidom, particulary the...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003096096_python.txt
Q: Load a .so library into ctypes I have compiled a library using cmake add_library(object3d SHARED some_file.h some_file.cpp). After compilation, I get a file: libobject3d.so I would like to call a function in this library. This function definition in some_file.h is: void ComputeGeometryImage(char * input_image, int...
Load a .so library into ctypes
I have compiled a library using cmake add_library(object3d SHARED some_file.h some_file.cpp). After compilation, I get a file: libobject3d.so I would like to call a function in this library. This function definition in some_file.h is: void ComputeGeometryImage(char * input_image, int geometry_image_size, float * output...
[ "Your C++ compiler mangles the function name to _Z20ComputeGeometryImagePciPf. You need to tell your compiler to stop mangling the function name. In some_file.h:\nextern \"C\" void ComputeGeometryImage(char * input_image, \n int geometry_image_size, \n ...
[ 4 ]
[]
[]
[ "ctypes", "linux", "python" ]
stackoverflow_0003095923_ctypes_linux_python.txt
Q: Python string formatter for paragraphs I'm trying to format some strings for output on the command-line, report style, and am looking for the easiest method to format a string such that I can get automatic paragraph formatting. In perlform formatting is done through the "format" function format Something = Tes...
Python string formatter for paragraphs
I'm trying to format some strings for output on the command-line, report style, and am looking for the easiest method to format a string such that I can get automatic paragraph formatting. In perlform formatting is done through the "format" function format Something = Test: @<<<<<<<< @||||| @>>>>> $str,...
[ "There isn't automatic formatting like this built into Python. (The .format function syntax is borrowed from C#.) After all, Perl was \"Practical Extraction and Report Language\" and Python isn't designed for formatting reports.\nYour output could be done with the textwrap module, e.g.\nfrom textwrap import fill\n...
[ 6, 4, 1 ]
[]
[]
[ "formatting", "python", "string" ]
stackoverflow_0003096402_formatting_python_string.txt
Q: Fibonacci numbers not getting printed beyond F(996) I wrote this small snippet to calculate Fibonacci numbers. It works well for numbers up to 996 and from 997 a trace back is being printed. I can't figure out what the problem is. Does it has something to do with maximum_recursion_count? def fib(n): if n==0: ...
Fibonacci numbers not getting printed beyond F(996)
I wrote this small snippet to calculate Fibonacci numbers. It works well for numbers up to 996 and from 997 a trace back is being printed. I can't figure out what the problem is. Does it has something to do with maximum_recursion_count? def fib(n): if n==0: return 0 elif n==1: return 1 else: return fib(n-1)...
[ "Probably. Take a look at sys.getrecursionlimit(). The default value is 1000, which sounds like it just might be causing the problem you're seeing: once there are 1000 frames on the stack (i.e. slightly less than 1000 recursive function calls), you'll get an error on the next function call.\nYou can set the recursi...
[ 5, 3, 3, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003095987_python.txt
Q: U combinator on a fibonacci : how would you translate this code to python? I am trying to learn about combinators and I am having trouble understand the example given at (Y overriding self-application). I think I am beginning to grasp the concept but I am still far from understanding. I would like to translate the...
U combinator on a fibonacci : how would you translate this code to python?
I am trying to learn about combinators and I am having trouble understand the example given at (Y overriding self-application). I think I am beginning to grasp the concept but I am still far from understanding. I would like to translate the following code to Python: (define (U f) (f f)) (define (fib-nr f) ...
[ "I wrote a simple translation that seems to produce correct results:\ndef U(f): return f(f)\n\ndef fibnr(f):\n def lam(n):\n if (n < 2): return 1\n return f(f)(n-1) + f(f)(n-2)\n return lam\n\nOr if you really like lambdas:\ndef fibnr(f): return lambda n: 1 if (n < 2) else f(f)(n-1) + f(f)(n-2)\...
[ 4 ]
[]
[]
[ "code_translation", "fixpoint_combinators", "python" ]
stackoverflow_0003097142_code_translation_fixpoint_combinators_python.txt
Q: How to put a Windows UAC Shield overlay on a button using wxPython? I have a button that will launch a process that requires UAC elevation. I want to display the Windows UAC shield overlay on the button, how do I do this in wxPython? The application is only going to run on Windows, so I don't need to worry about i...
How to put a Windows UAC Shield overlay on a button using wxPython?
I have a button that will launch a process that requires UAC elevation. I want to display the Windows UAC shield overlay on the button, how do I do this in wxPython? The application is only going to run on Windows, so I don't need to worry about it not working on other systems. edit 2: Got it: BCM_SETSHIELD = 0x0000160...
[ "I don't know how to send a Windows message in Python, but I assume you do. You need to send BCM_SETSHIELD with true as the parameter. It will be ignored on XP and earlier. Also make sure the button style is set to FlatStyle.System. The numerical value of BCM_SETSHIELD is 0x0000160C.\n" ]
[ 2 ]
[]
[]
[ "button", "icons", "python", "uac", "wxpython" ]
stackoverflow_0003097124_button_icons_python_uac_wxpython.txt
Q: Need a better way to execute console commands from python and log the results I have a python script which needs to execute several command line utilities. The stdout output is sometimes used for further processing. In all cases, I want to log the results and raise an exception if an error is detected. I use the f...
Need a better way to execute console commands from python and log the results
I have a python script which needs to execute several command line utilities. The stdout output is sometimes used for further processing. In all cases, I want to log the results and raise an exception if an error is detected. I use the following function to achieve this: def execute(cmd, logsink): logsink.log("exec...
[ "You can redirect to a file if you just want the output in a file for later evaluation.\nYour already defining the stdout/stderr of the processes your executuing by the stdout=/stderr= methods.\nIn your example code your just redirecting to the scripts current out/err assigments.\nsubprocess.Popen(cmd, shell=True, ...
[ 5, 2, 1, 1 ]
[]
[]
[ "command_line", "logging", "python" ]
stackoverflow_0000559578_command_line_logging_python.txt
Q: GUI tools and APIs for small/medium hierarchical data structures I'm trying to find a tool and library to edit, write and read data in a hierarchical structure, similar to an LDAP tree, a Windows registry or a Berkeley DB structure. The keys should represent some hierarchy, and the values should have a relatively ...
GUI tools and APIs for small/medium hierarchical data structures
I'm trying to find a tool and library to edit, write and read data in a hierarchical structure, similar to an LDAP tree, a Windows registry or a Berkeley DB structure. The keys should represent some hierarchy, and the values should have a relatively flexible format (typing is optional, but could be useful). Here is an ...
[ "Forgive my densitosity, but if your hierarchy is anything but the roughest kind of example, there must be hugely compelling, overpowering reasons for your choosing that over, say, JSON or even (gulp!) XML:\n\n<items>\n <item>\n <number>1</number>\n <shape>rectangle</shape>\n <top>10</top>\n <left>10</left...
[ 0 ]
[]
[]
[ "data_structures", "hierarchical_data", "python", "user_interface" ]
stackoverflow_0003097090_data_structures_hierarchical_data_python_user_interface.txt
Q: Most minimal Apache2 configuration for a python script that wgets, combines with local files and provides zip? I have a PHP site setup on my server that also has mod_wsgi + Python 2.5 on it. Occasionally I'm going to be asked to provide a zip of the entire site, and I'd like to use Python instead of PHP to do this...
Most minimal Apache2 configuration for a python script that wgets, combines with local files and provides zip?
I have a PHP site setup on my server that also has mod_wsgi + Python 2.5 on it. Occasionally I'm going to be asked to provide a zip of the entire site, and I'd like to use Python instead of PHP to do this. What's the most minimal configuration I could make so that my python script is web accessible in order such that i...
[ "The mod_wsgi site has very good documenation, including a \"QuickStart\" guide. It comes complete with a very minimal python script to get you going.\nIf you want to use Python and go even simpler (and performace/load is not an issue), there's always the cgi module.\n" ]
[ 1 ]
[]
[]
[ "apache2", "python" ]
stackoverflow_0003097682_apache2_python.txt