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: Compiling a regex inside a function that's called multiple times If you compile a regex inside a function, and that function gets called multiple times, does Python recompile the regex each time, or does Python cache the compiled regex (assuming the regex doesn't change)? For example: def contains_text_of_interest...
Compiling a regex inside a function that's called multiple times
If you compile a regex inside a function, and that function gets called multiple times, does Python recompile the regex each time, or does Python cache the compiled regex (assuming the regex doesn't change)? For example: def contains_text_of_interest(line): r = re.compile(r"foo\dbar\d") return r.match(line) ...
[ "Actually, if you look at the code in the re module, the re.compile function uses the cache just as all the other functions do, so compiling the same regex over and over again is very very cheap (a dictionary lookup). In other words, write the code to be the most understandable or maintainable or expressive, and d...
[ 14, 6, 2, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003427329_python_regex.txt
Q: Saving a temporary file I'm using xlwt in python to create a Excel spreadsheet. You could interchange this for almost anything else that generates a file; it's what I want to do with the file that's important. from xlwt import * w = Workbook() #... do something w.save('filename.xls') I want to I have two use cas...
Saving a temporary file
I'm using xlwt in python to create a Excel spreadsheet. You could interchange this for almost anything else that generates a file; it's what I want to do with the file that's important. from xlwt import * w = Workbook() #... do something w.save('filename.xls') I want to I have two use cases for the file: I stream it ...
[ "cStringIO\n(or mmap if it should be mutable)\n", "Generalising the answer, as you suggested: If the \"anything else that generates a file\" won't accept a file-like object as well as a filepath, then you can reduce the hassle by using tempfile.NamedTemporaryFile\n" ]
[ 5, 1 ]
[]
[]
[ "python", "xlwt" ]
stackoverflow_0003406061_python_xlwt.txt
Q: Eclipse: Debug script that expects command line parameters I have a python script I am trying to debug in eclipse. I can execute it, breakpoint all that jazz, but this specific script requires a handful of command line parameters. Is it possible to setup my dev environment in eclipse to put these parameters in? Ri...
Eclipse: Debug script that expects command line parameters
I have a python script I am trying to debug in eclipse. I can execute it, breakpoint all that jazz, but this specific script requires a handful of command line parameters. Is it possible to setup my dev environment in eclipse to put these parameters in? Right now my program is just generating the line to execute, like:...
[ "Use a launch configuration\nTo create:\n - Right mouse button on your script, => Run as / Python Run\n => this creates a Run configuration\n - Right mouser button again, Run as / Run Configurations\n => opens this specific configuration\n - Tab 'Arguments', enter your arguments\nTo use:\n - from the same...
[ 3, 2 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0003418270_eclipse_pydev_python.txt
Q: are there tutorials on how to name variables? as you can probably tell from my previous posts i have horrific naming conventions. do you know of any tutorials dealing with how to name stuff? A: i will recommend to check this book http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/...
are there tutorials on how to name variables?
as you can probably tell from my previous posts i have horrific naming conventions. do you know of any tutorials dealing with how to name stuff?
[ "i will recommend to check this book \nhttp://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=sr_1_1?s=books&ie=UTF8&qid=1281129036&sr=1-1\n", "I don't think there will be any good tutorials, because there aren't any hard-and-fast rules. Here are some tips:\n\nConform to convention:...
[ 11, 7, 5, 4, 3, 3, 3, 3, 2, 2, 1, 1 ]
[]
[]
[ ".net", "language_agnostic", "naming_conventions", "python" ]
stackoverflow_0003427795_.net_language_agnostic_naming_conventions_python.txt
Q: XML and Python: Get the namespaces declared in root element How do I access the multiple xmlns declarations at the root element of an XML tree? For example: import xml.etree.cElementTree as ET data = """<root xmlns:one="http://www.first.uri/here/" xmlns:two="http://www.second.uri/here/"> ...
XML and Python: Get the namespaces declared in root element
How do I access the multiple xmlns declarations at the root element of an XML tree? For example: import xml.etree.cElementTree as ET data = """<root xmlns:one="http://www.first.uri/here/" xmlns:two="http://www.second.uri/here/"> ...all other child elements here... </root>"...
[ "I'm not sure how this might be done with xml.etree, but with lxml.etree you could do this:\nimport lxml.etree as le\ndata = \"\"\"<root\n xmlns:one=\"http://www.first.uri/here/\"\n xmlns:two=\"http://www.second.uri/here/\">\n\n ...all other child elements here...\n </root>...
[ 2 ]
[]
[]
[ "python", "xml", "xml_namespaces" ]
stackoverflow_0003428792_python_xml_xml_namespaces.txt
Q: Elegant Python? I am trying to teach myself Python, and I have realized that the only way I really learn stuff is by reading the actual programs. Tutorials/manuals just cause me to feel deeply confused. It's just my learning style, and I'm like that with everything I've studied (including natural languages -- I'v...
Elegant Python?
I am trying to teach myself Python, and I have realized that the only way I really learn stuff is by reading the actual programs. Tutorials/manuals just cause me to feel deeply confused. It's just my learning style, and I'm like that with everything I've studied (including natural languages -- I've managed to teach my...
[ "I would recommend studying the Standard Python Library (all the parts of it that are coded in Python, that is) -- it's not uniformly excellent in elegance, but it sets a pretty high standard. Plus, the study has the extra benefit of making you very familiar with the library itself (an absolutely crucial part of m...
[ 18, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003428245_python.txt
Q: python regex to find any link that contains the text 'abc123' I am using beautifuly soup to find all href tags. links = myhtml.findAll('a', href=re.compile('????')) I need to find all links that have 'abc123' in the href text. I need help with the regex , see ??? in my code snippet. A: If 'abc123' is literally ...
python regex to find any link that contains the text 'abc123'
I am using beautifuly soup to find all href tags. links = myhtml.findAll('a', href=re.compile('????')) I need to find all links that have 'abc123' in the href text. I need help with the regex , see ??? in my code snippet.
[ "If 'abc123' is literally what you want to search for, anywhere in the href, then re.compile('abc123') as suggested by other answers is correct. If the actual string you want to match contains punctuation, e.g. 'abc123.com', then use instead\nre.compile(re.escape('abc123.com'))\n\nThe re.escape part will \"escape\...
[ 2, 1, 1 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0003428845_beautifulsoup_python_regex.txt
Q: Is there a way to automate restarting the python process after every change I make to Django models? I am using Django with Passenger on Dreamhost. Every time I make a change to models, settings or views I need to pkill python from a terminal session. Does anyone know of a way to automate this? Is this somethi...
Is there a way to automate restarting the python process after every change I make to Django models?
I am using Django with Passenger on Dreamhost. Every time I make a change to models, settings or views I need to pkill python from a terminal session. Does anyone know of a way to automate this? Is this something that Passenger can do?
[ "My advice would be to test locally using Django's builtin server.\nIt does precisely auto-reload, so that any change to your code will be available.\nI'm not familiar with Dreamhost, but if modwsgi is on embedded mode this is not possible.\nIn Daemon mode, you could write some code to detect file changes and resta...
[ 2 ]
[]
[]
[ "django", "passenger", "python", "wsgi" ]
stackoverflow_0003427287_django_passenger_python_wsgi.txt
Q: Forgetting self qualifier: how to catch this mistake? I understand why Python requires explicit self qualifier when referring to instance attributes. But I often forget it, since I didn't need it in C++. The bug I introduce this way is sometimes extremely hard to catch; e.g., suppose I write if x is not None: ...
Forgetting self qualifier: how to catch this mistake?
I understand why Python requires explicit self qualifier when referring to instance attributes. But I often forget it, since I didn't need it in C++. The bug I introduce this way is sometimes extremely hard to catch; e.g., suppose I write if x is not None: f() instead of if self.x is not None: f() Suppose att...
[ "Don't name your instance attributes the same things as your globals/locals.\nIf there isn't a global/local of the same name, you'll get a global \"foo\" is not defined error when you try to access self.foo but forget the self..\nAs a corollary: give your variables descriptive names. Don't name everything x - not o...
[ 5 ]
[]
[]
[ "debugging", "python", "self" ]
stackoverflow_0003429073_debugging_python_self.txt
Q: Python requires a GIL. But Jython & IronPython don't. Why? Why is it that you can run Jython and IronPython without the need for a GIL but Python (CPython) requires a GIL? A: Parts of the Interpreter aren't threadsafe, though mostly because making them all threadsafe by massive lock usage would slow single-threa...
Python requires a GIL. But Jython & IronPython don't. Why?
Why is it that you can run Jython and IronPython without the need for a GIL but Python (CPython) requires a GIL?
[ "Parts of the Interpreter aren't threadsafe, though mostly because making them all threadsafe by massive lock usage would slow single-threaded extremely (source). This seems to be related to the CPython garbage collector using reference counting (the JVM and CLR don't, and therefore don't need to lock/release a ref...
[ 11, 3 ]
[]
[]
[ "gil", "ironpython", "jython", "multithreading", "python" ]
stackoverflow_0003429159_gil_ironpython_jython_multithreading_python.txt
Q: Convert html entities to ascii in Python I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML. Right now, I only really know how to create unicode from these entities when I need ASCII...
Convert html entities to ascii in Python
I need to convert any html entity into its ASCII equivalent using Python. My use case is that I am cleaning up some HTML used to build emails to create plaintext emails from the HTML. Right now, I only really know how to create unicode from these entities when I need ASCII (I think) so that the plaintext email reads c...
[ "Here is a complete implementation that also handles unicode html entities. You might find it useful.\nIt returns a unicode string that is not ascii, but if you want plain ascii, you can modify the replace operations so that it replaces the entities to empty string.\ndef convert_html_entities(s):\n matches = re....
[ 8, 2, 1, 0 ]
[]
[]
[ "ascii", "python" ]
stackoverflow_0001197981_ascii_python.txt
Q: Pylons formencode - How do I POST an array of data? I have a form that is similar to the following: Enter Name: Enter Age: [add more] That add more field copies the Name and Age inputs and can be clicked as many times as the user wants. Potentially, they could end up submitting 50 sets of Name and Age data. How c...
Pylons formencode - How do I POST an array of data?
I have a form that is similar to the following: Enter Name: Enter Age: [add more] That add more field copies the Name and Age inputs and can be clicked as many times as the user wants. Potentially, they could end up submitting 50 sets of Name and Age data. How can I handle this received data when it's posted to my Pyl...
[ "You would post something like this (URL encoded, of course)\nusers-0.name=John\nusers-0.age=21\nusers-1.name=Mike\nusers-1.age=30\n...\n\nDo that for users 0-N where N is as many users as you have, zero-indexed. Then, on the Python side after you run this through variabledecode, you'll have:\nusers = UserSchema.to...
[ 1 ]
[]
[]
[ "arrays", "formencode", "pylons", "python" ]
stackoverflow_0003429348_arrays_formencode_pylons_python.txt
Q: getting a list of files in a custom directory using glob() Im trying to write a program that renames files when a use input their own custom file directory. I'm at a very early part of it. And this is my first time using the OS and glob commands. My code is below. However when I tried running that, the result was ...
getting a list of files in a custom directory using glob()
Im trying to write a program that renames files when a use input their own custom file directory. I'm at a very early part of it. And this is my first time using the OS and glob commands. My code is below. However when I tried running that, the result was an empty list. I tried typing a file root directory into the glo...
[ "Python is white-space sensitive, so you need to make sure that everything you want inside the function is indented.\nStackoverflow has its own indentation requirements for code, which makes it hard to be sure what indentation your code originally had.\nimport os, glob\ndef fileDirectory():\n #Asks the user for ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003429584_python.txt
Q: sort date objects in Python I start out with date strings: from operator import itemgetter import datetime as DT # unsorted dates raw = (map(int, "2010-08-01".split("-")), map(int, "2010-03-25".split("-")), map(int, "2010-07-01".split("-"))) transactions = [] for year, month, day in raw: new = ...
sort date objects in Python
I start out with date strings: from operator import itemgetter import datetime as DT # unsorted dates raw = (map(int, "2010-08-01".split("-")), map(int, "2010-03-25".split("-")), map(int, "2010-07-01".split("-"))) transactions = [] for year, month, day in raw: new = (DT.date(year, month, day), "Some...
[ "Well, the reason it's not sorted is that you haven't reassigned the sorted list back to transactions; you want: \ntransactions = sorted(transactions, key=itemgetter(0))\n\nI should point out that datetime has a strptime function that does what you're doing manually:\ntransactions = [ ( DT.datetime.strptime( datest...
[ 4, 3, 2 ]
[]
[]
[ "date", "object", "python", "sorting" ]
stackoverflow_0003429985_date_object_python_sorting.txt
Q: python regex to get all text until a (, and get text inside brackets I need help with two regex operations. Get all text until an open bracket. e.g. 'this is so cool (234)' => 'this is so cool' Get the text inside the brackets, so the number '234' A: Up until the paren: regex = re.compile("(.*?)\s*\(") Inside ...
python regex to get all text until a (, and get text inside brackets
I need help with two regex operations. Get all text until an open bracket. e.g. 'this is so cool (234)' => 'this is so cool' Get the text inside the brackets, so the number '234'
[ "Up until the paren: regex = re.compile(\"(.*?)\\s*\\(\")\nInside the first set of parens: regex = re.compile(\".*?\\((.*?)\\)\")\nEdit: Single regex version: regex = re.compile(\"(.*?)\\s*\\((.*?)\\)\")\nExample output:\n>>> import re\n>>> r1 = re.compile(\"(.*?)\\s*\\(\")\n>>> r2 = re.compile(\".*?\\((.*?)\\)\")\...
[ 7, 3, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003429086_python_regex.txt
Q: Howto import a function with python I'm developing a Python application for the GAE. The application consists of a bunch of classes and functions which are at the moment all in the same file main.py. The application is running without problems. Now, I want to refactor the application and outsource all the classes...
Howto import a function with python
I'm developing a Python application for the GAE. The application consists of a bunch of classes and functions which are at the moment all in the same file main.py. The application is running without problems. Now, I want to refactor the application and outsource all the classes. Every class should be in her own file. ...
[ "Try moving the extra functions from main.py into a separate file.\nmain.py\nlibrary.py # contains login() and other functions from main\n/directory1/class1.py\n/directory1/class2.py\n/directory2/class1.py\n\n", "Sometimes it is good to leave classes in same module not separate without purpose if they belong toge...
[ 2, 0 ]
[]
[]
[ "function", "google_app_engine", "python" ]
stackoverflow_0003429874_function_google_app_engine_python.txt
Q: Using Pylons validate and authenticate_form decorator The validate and authenticate_form decorators don't seem to play nice together. This is my template: <html> <title>Test</title> <body> ${h.secure_form('/meow/do_post')} <input type="text" name="dummy"> <form:error name="dummy"><br> <input type="submit" name="do...
Using Pylons validate and authenticate_form decorator
The validate and authenticate_form decorators don't seem to play nice together. This is my template: <html> <title>Test</title> <body> ${h.secure_form('/meow/do_post')} <input type="text" name="dummy"> <form:error name="dummy"><br> <input type="submit" name="doit" value="Do It"> ${h.end_form()} </body> </html> And thi...
[ "@validate(schema=MeowForm(), form='index')\n@authenticate_form\ndef do_post(self):\n\nYou need to change order of decorators, authenticate decorator must be last\n" ]
[ 2 ]
[]
[]
[ "formencode", "htmlfill", "pylons", "python" ]
stackoverflow_0002981555_formencode_htmlfill_pylons_python.txt
Q: pymacs: General question and Installation problem I am trying to setup emacs for python development. From what I read, it is recommended to use python-mode.el rather than the default python.el from Emacs 22.3. So I embark on the new adventure. From what I understand, python-mode has the several dependencies, so I...
pymacs: General question and Installation problem
I am trying to setup emacs for python development. From what I read, it is recommended to use python-mode.el rather than the default python.el from Emacs 22.3. So I embark on the new adventure. From what I understand, python-mode has the several dependencies, so I need to install rope, ropemode and ropemacs. Then on t...
[ "I have never used pymacs so far, but one thing which catches my eye when I look at your .emacs is that you apparently didn't add the pymacs directory to the emacs load-path but only to the pymacs one:\n(setq pymacs-load-path '( \"~/.emacs.d/site-lisp/rope\"\n \"~/.emacs.d/site-lisp/ropemod...
[ 1, 1, 1 ]
[]
[]
[ "emacs", "pymacs", "python", "rope" ]
stackoverflow_0001078069_emacs_pymacs_python_rope.txt
Q: is this code useful? def _oauth_escape(val): if isinstance(val, unicode):# useful ? val = val.encode("utf-8")#useful ? return urllib.quote(val, safe="~") i think it is not useful , yes ?? updated i think unicode is ‘utf-8’ ,yes ? A: utf-8 is an encoding, a recipe for concretely representing uni...
is this code useful?
def _oauth_escape(val): if isinstance(val, unicode):# useful ? val = val.encode("utf-8")#useful ? return urllib.quote(val, safe="~") i think it is not useful , yes ?? updated i think unicode is ‘utf-8’ ,yes ?
[ "utf-8 is an encoding, a recipe for concretely representing unicode data as a series of bytes. This is one of many such encodings. Python str objects are bytestrings, which can represent arbitrary binary data, such as text in a specific encoding.\nPython's unicode type is an abstract, not-encoded way to represent t...
[ 1, 1, 0 ]
[]
[]
[ "encode", "python" ]
stackoverflow_0002880499_encode_python.txt
Q: Demonstrating instruction level parallelism at work I'm trying to show instruction level parallelism at work. What I was originally doing was using python (willing to change) and doing the following: def test(): for i in range(5000): j = 0 k = 0 l = 0 def test2(): for i in range(50...
Demonstrating instruction level parallelism at work
I'm trying to show instruction level parallelism at work. What I was originally doing was using python (willing to change) and doing the following: def test(): for i in range(5000): j = 0 k = 0 l = 0 def test2(): for i in range(5000): j = i * i k = j * 2 l = k * ...
[ "Your professor is correct. I think an acceptable demonstration would have to be written in assembler, or at most C/C++, possibly using something like the MMX instruction set.\n", "There is a chance that your professor might be correct -- you might prove him wrong if you could show that cpython is actually using ...
[ 3, 1, 0 ]
[]
[]
[ "parallel_processing", "python" ]
stackoverflow_0003405640_parallel_processing_python.txt
Q: FastCGI, Apache, Django and 500 Error I am getting 500 Internal error with Apache and FastCGI. Spent the whole day to find the reason :-/ /etc/apache2/vhost.d/mysite.conf FastCGIExternalServer /home/me/web/mysite.fcgi -socket /home/me/web/mysite.sock Listen 80 <VirtualHost *:80> ServerName os.me #That's my...
FastCGI, Apache, Django and 500 Error
I am getting 500 Internal error with Apache and FastCGI. Spent the whole day to find the reason :-/ /etc/apache2/vhost.d/mysite.conf FastCGIExternalServer /home/me/web/mysite.fcgi -socket /home/me/web/mysite.sock Listen 80 <VirtualHost *:80> ServerName os.me #That's my localhost machine DocumentRoot /ho...
[ "See \n\nhttp://iamtgc.com/2007/07/04/django-on-lighttpd-with-fastcgi/\nWSGIServer errors when trying to run Django app\n\n", "Thanks to help from #django irc channel (specially to zk). \nFastCGIExternalServer /home/me/web/mysite.fcgi -socket /home/me/web/mysite.sock\n\nMust be changed to (as apache should spawn ...
[ 1, 1 ]
[]
[]
[ "apache", "django", "fastcgi", "python" ]
stackoverflow_0003428384_apache_django_fastcgi_python.txt
Q: is json package included in Python for Windows? is json package included in Python for Windows? A: Yes, the json module is part of the Python standard library since version 2.6. All standard Python library modules are available on all platforms unless specifically indicated otherwise.
is json package included in Python for Windows?
is json package included in Python for Windows?
[ "Yes, the json module is part of the Python standard library since version 2.6. All standard Python library modules are available on all platforms unless specifically indicated otherwise.\n" ]
[ 2 ]
[]
[]
[ "json", "python", "windows" ]
stackoverflow_0003430701_json_python_windows.txt
Q: MVC Webframeworks Possible Duplicate: Choosing a Java Web Framework now? I know that Ruby-on-Rails and Django are 2 MVC oriented webframeworks, in Ruby and Python respectively. Are there any other MVC frameworks ? Any MVC frameworks that use Java ? A: Something closer to rails in Java (well, not really Java) ...
MVC Webframeworks
Possible Duplicate: Choosing a Java Web Framework now? I know that Ruby-on-Rails and Django are 2 MVC oriented webframeworks, in Ruby and Python respectively. Are there any other MVC frameworks ? Any MVC frameworks that use Java ?
[ "Something closer to rails in Java (well, not really Java) would be Grails.\nOf course you'd need Groovy to use that, but it's worth a shot.\n", "CakePHP is a PHP MVC framework that's fairly simple to use.\n", "Spring MVC and Struts are two popular MVC web frameworks for Java.\n" ]
[ 3, 1, 0 ]
[]
[]
[ "django", "java", "model_view_controller", "python", "ruby_on_rails" ]
stackoverflow_0003430780_django_java_model_view_controller_python_ruby_on_rails.txt
Q: Select columns of data from .txt to .csv I am quite new to python (well more like I've only been using it for the past week). My task seems fairly simple, yet I am struggling. I have several large text files each with many columns of data in them from different regions. I would like to take the data from one te...
Select columns of data from .txt to .csv
I am quite new to python (well more like I've only been using it for the past week). My task seems fairly simple, yet I am struggling. I have several large text files each with many columns of data in them from different regions. I would like to take the data from one text file and extract only the columns of data t...
[ "You need to format this question a little more legibly. :)\nTake a look at the python csv module for writing your csv files from your now-stored data: http://docs.python.org/library/csv.html\nEDIT: Here's some better, more concise code, based on comments + csv module:\nimport csv\n\ncsv_out = csv.writer(open('out....
[ 2, 0, 0, 0 ]
[]
[]
[ "csv", "python", "text" ]
stackoverflow_0003429277_csv_python_text.txt
Q: python package for distributed auction simulation Does anyone know of a package that allows for a distributed agent-based double auction simulation? I've looked at SimPy, but that's a discrete-event simulator and difficult to get working in a distributed fashion. regs, Vivek A: You're welcome to try my own Garli...
python package for distributed auction simulation
Does anyone know of a package that allows for a distributed agent-based double auction simulation? I've looked at SimPy, but that's a discrete-event simulator and difficult to get working in a distributed fashion. regs, Vivek
[ "You're welcome to try my own GarlicSim. If I understand your need correctly, it will work well for you. \nThe official website is here, the documentation is here, and there's a blog here.\nIf you'll need help or have questions, you can email me directly or use the mailing lists. I'll help you get your double-aucti...
[ 2 ]
[]
[]
[ "distributed", "python", "simulation" ]
stackoverflow_0003430360_distributed_python_simulation.txt
Q: Django update table obj = Info(name= sub,question=response_dict["question"]) obj.save() After saving the data how to update another field of the same table obj.err_flag=1 obj.update()//Will this work A: Just resave that instance: obj.some_field = some_var obj.save() Django automatically knows when to UPDATE vs...
Django update table
obj = Info(name= sub,question=response_dict["question"]) obj.save() After saving the data how to update another field of the same table obj.err_flag=1 obj.update()//Will this work
[ "Just resave that instance:\nobj.some_field = some_var\nobj.save()\n\nDjango automatically knows when to UPDATE vs. INSERT your instance in the database.\nThis is explained in the \nDjango docs.\n", "obj = Info(name=sub,question=response_dict[\"question\"])\nobj.save()\n\nAnd then later you want to get it and upd...
[ 7, 3, 2 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0003430432_django_django_models_django_templates_django_views_python.txt
Q: Stop SQL query in python Is there a way to let the user stop the execution of a sql query in python if it takes some long time? I am thinking of using a progress bar with a cancel button, but I wonder if there is a way to stop it in a clean way instead of killing abruptly the associated thread? (I am using both py...
Stop SQL query in python
Is there a way to let the user stop the execution of a sql query in python if it takes some long time? I am thinking of using a progress bar with a cancel button, but I wonder if there is a way to stop it in a clean way instead of killing abruptly the associated thread? (I am using both pysqlite2 and MySQLdb packages)
[ "the only solution i see is to get the process id:\nSHOW PROCESSLIST;\n\nand kill it:\nKILL <thread_id>;\n\ni would execute those commands with mysqldb.\nHowever, you should be carefull about the rollback. See for example:\nIf I stop a long running query, does it rollback?\nhope it helps\n" ]
[ 3 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0003431323_python_sql.txt
Q: Where does django dev server (manage.py runserver) get its path from? I recently moved a django app from c:\Users\user\django-projects\foo\foobar to c:\Python25\Lib\site-packages\foo\foobar (which is on the python path). I started a new app in the django-projects directory, and added foo.foobar to the INSTALLED_AP...
Where does django dev server (manage.py runserver) get its path from?
I recently moved a django app from c:\Users\user\django-projects\foo\foobar to c:\Python25\Lib\site-packages\foo\foobar (which is on the python path). I started a new app in the django-projects directory, and added foo.foobar to the INSTALLED_APPS setting. When I try to run the dev server (manage.py runserver) for my n...
[ "manage.py imports settings.py from the current directory and pass settings as parameter to execute_manager. You probably defined project root in settings.py.\n", "I fixed it, although I don't know which solution worked. First, I deleted the .pyc files from my project, then I reindexed my Windows search (I'm gues...
[ 1, 1 ]
[]
[]
[ "devserver", "django", "django_manage.py", "path", "python" ]
stackoverflow_0003411131_devserver_django_django_manage.py_path_python.txt
Q: How do I write only certain lines to a file in Python? I have a file that looks like this(have to put in code box so it resembles file): text (starts with parentheses) tabbed info text (starts with parentheses) tabbed info ...repeat I want to grab only "text" lines from the file(or every fourth...
How do I write only certain lines to a file in Python?
I have a file that looks like this(have to put in code box so it resembles file): text (starts with parentheses) tabbed info text (starts with parentheses) tabbed info ...repeat I want to grab only "text" lines from the file(or every fourth line) and copy them to another file. This is the code I hav...
[ "The reason why your script is copying every line is because line.startswith(\"\") is True, no matter what line equals.\nYou might try using isspace to test if line begins with a space:\ndef process_file(filename):\n with open(\"data.txt\", 'w') as output_file:\n with open(filename, \"r\") as input_file:\...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0003431673_file_python.txt
Q: Python: Completer for path to dir/file I'm writing a CLI app and there is a place, where user should to write path to using dir. Of couse, I can read it with raw_input(), but standart Completer can't autocomplete path by TAB. So is there any solution in python (or somewhere else) or should I to write my own Comple...
Python: Completer for path to dir/file
I'm writing a CLI app and there is a place, where user should to write path to using dir. Of couse, I can read it with raw_input(), but standart Completer can't autocomplete path by TAB. So is there any solution in python (or somewhere else) or should I to write my own Completer?
[ "Have a look at this SO question, the readline module, and readline.clear_history() / readline.add_history().\n" ]
[ 0 ]
[]
[]
[ "command_line_interface", "python" ]
stackoverflow_0003431850_command_line_interface_python.txt
Q: Get big TAR(gz)-file contents by dir levels I use python tarfile module. I have a system backup in tar.gz file. I need to get first level dirs and files list without getting ALL the list of files in the archive because it's TOO LONG. For example: I need to get ['bin/', 'etc/', ... 'var/'] and that's all. How can I...
Get big TAR(gz)-file contents by dir levels
I use python tarfile module. I have a system backup in tar.gz file. I need to get first level dirs and files list without getting ALL the list of files in the archive because it's TOO LONG. For example: I need to get ['bin/', 'etc/', ... 'var/'] and that's all. How can I do it? May be not even with a tar-file? Then how...
[ "You can't scan the contents of a tar without scanning the entire file; it has no central index. You need something like a ZIP.\n" ]
[ 1 ]
[]
[]
[ "python", "tar" ]
stackoverflow_0003431844_python_tar.txt
Q: how to convert python/cython unicode string to array of long integers, to do levenshtein edit distance Possible Duplicate: How to correct bugs in this Damerau-Levenshtein implementation? I have the following Cython code (adapted from the bpbio project) that does Damerau-Levenenshtein edit-distance calculation: #...
how to convert python/cython unicode string to array of long integers, to do levenshtein edit distance
Possible Duplicate: How to correct bugs in this Damerau-Levenshtein implementation? I have the following Cython code (adapted from the bpbio project) that does Damerau-Levenenshtein edit-distance calculation: #--------------------------------------------------------------------------- cdef extern from "stdlib.h": ...
[ "Use ord() to convert characters to their integer code point. It works characters from either unicode or str string types:\ncodepoints = [ord(c) for c in text]\n\n", "Caveat lector: I've never done this. The following is a rough sketch of what I'd try.\nYou will need to use the PyUnicode_AsUnicode function and t...
[ 3, 0, -2 ]
[]
[]
[ "cython", "edit_distance", "levenshtein_distance", "python", "python_3.x" ]
stackoverflow_0003367795_cython_edit_distance_levenshtein_distance_python_python_3.x.txt
Q: Why Does Specifying choices to a Widget not work in ModelForm.__init__ I'm trying to understand why I can't specify choices to a form field's widget if I'm overriding a ModelForm's field in Django. It works if I give the choices to the field but not the widget. My understanding is/was that if you give choices to a...
Why Does Specifying choices to a Widget not work in ModelForm.__init__
I'm trying to understand why I can't specify choices to a form field's widget if I'm overriding a ModelForm's field in Django. It works if I give the choices to the field but not the widget. My understanding is/was that if you give choices to a field it'll be passed onto the widget for rendering. I know I can get this ...
[ "I think the best way of explaining is to walk through the code for ChoiceField, the superclass of TypeChoiceField.\nclass ChoiceField(Field):\n widget = Select\n default_error_messages = {\n 'invalid_choice': _(u'Select a valid choice. %(value)s is not one of the available choices.'),\n }\n\n de...
[ 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003431923_django_django_forms_python.txt
Q: Serving Python scripts with CGIHTTPServer on Mac OS X I'm trying to set up Python's CGIHTTPServer on Mac OS X to be able to serve CGI scripts locally, but I seem to be unable to do this. I've got a simple test script: #!/usr/bin/env python import cgi cgi.test() It has permissions -rwxr-xr-x@ and is located in ~...
Serving Python scripts with CGIHTTPServer on Mac OS X
I'm trying to set up Python's CGIHTTPServer on Mac OS X to be able to serve CGI scripts locally, but I seem to be unable to do this. I've got a simple test script: #!/usr/bin/env python import cgi cgi.test() It has permissions -rwxr-xr-x@ and is located in ~/WWW (with permissions drwxr-xr-x). It runs just fine from ...
[ "The paths in cgi_directories are matched against the path part of the URL, not the actual filesystem path. Setting it to [\"/\"] or [\"\"] will probably work better.\n" ]
[ 4 ]
[]
[]
[ "cgi", "macos", "python" ]
stackoverflow_0003431984_cgi_macos_python.txt
Q: python data attributes in sqlalchemy model I'm getting myself into issues with python class attributes vs data attributes in my sqlalchemy model. This is a small example to demonstrate what's happening: # -*- coding: utf-8 -*- import cherrypy import sqlalchemy from sqlalchemy import create_engine from sqlalchemy i...
python data attributes in sqlalchemy model
I'm getting myself into issues with python class attributes vs data attributes in my sqlalchemy model. This is a small example to demonstrate what's happening: # -*- coding: utf-8 -*- import cherrypy import sqlalchemy from sqlalchemy import create_engine from sqlalchemy import Table, Column, Integer, String, MetaData, ...
[ "SQLAlchemy provides special syntax for such cases, http://docs.sqlalchemy.org/en/latest/orm/constructors.html?highlight=object%20initialization\n", "You should be using super() to call the base class constructor:\ndef __init__(self, username, name, email, *args, **kwargs ):\n super( User, self ).__init__( *ar...
[ 3, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003422408_python_sqlalchemy.txt
Q: How to correct bugs in this Damerau-Levenshtein implementation? I'm back with another longish question. Having experimented with a number of Python-based Damerau-Levenshtein edit distance implementations, I finally found the one listed below as editdistance_reference(). It seems to deliver correct results and appe...
How to correct bugs in this Damerau-Levenshtein implementation?
I'm back with another longish question. Having experimented with a number of Python-based Damerau-Levenshtein edit distance implementations, I finally found the one listed below as editdistance_reference(). It seems to deliver correct results and appears to have an efficient implementation. So I set down to convert the...
[ "Do some elementary debugging. You know that it is going wrong in the 2nd output line marked #ED B. The wrong values seem to indicate that it finds one edit early on and never finds any more. This is possibly because one of the min() args is somehow clamped at 1. Print deletion_cost, substitution_cost, addition_cos...
[ 2 ]
[]
[]
[ "cython", "edit_distance", "levenshtein_distance", "python", "python_3.x" ]
stackoverflow_0003431933_cython_edit_distance_levenshtein_distance_python_python_3.x.txt
Q: Scraping landing pages of a list of domains I have a reasonably long list of websites that I want to download the landing (index.html or equivalent) pages for. I am currently using Scrapy (much love to the guys behind it -- this is a fabulous framework). Scrapy is slower on this particular task than I'd like and I...
Scraping landing pages of a list of domains
I have a reasonably long list of websites that I want to download the landing (index.html or equivalent) pages for. I am currently using Scrapy (much love to the guys behind it -- this is a fabulous framework). Scrapy is slower on this particular task than I'd like and I am wondering if wget or an other alternative wou...
[ "If you want a way to concurrently download multiple sites with python, you can do so with the standard libraries like this:\nimport threading\nimport urllib\n\nmaxthreads = 4\n\nsites = ['google.com', 'yahoo.com', ] # etc.\n\nclass Download(threading.Thread):\n def run (self):\n global sites\n while ...
[ 4 ]
[]
[]
[ "python", "scrapy", "screen_scraping" ]
stackoverflow_0002501838_python_scrapy_screen_scraping.txt
Q: Building a comet server from twisted.web, for a twisted.web site So I have a website already set up, and I need a comet server for a chat application. The site is built with twisted.web, and I want to build the comet server with twisted as well since I'm already somewhat familiar with it. But I'm not sure how to d...
Building a comet server from twisted.web, for a twisted.web site
So I have a website already set up, and I need a comet server for a chat application. The site is built with twisted.web, and I want to build the comet server with twisted as well since I'm already somewhat familiar with it. But I'm not sure how to do it. I've looked at this post and understand the mechanics in the cod...
[ "You can use Orbited (which is a comet server based on Twisted) and run it in the same process as your web server. It's pretty slick. Instead of using its built-in proxy, you just use its guts directly. You'd do something like:\nfrom orbited.cometsession import Port\n...\nreactor.listenWith(Port, factory=someFactor...
[ 1 ]
[]
[]
[ "comet", "python", "twisted.web" ]
stackoverflow_0003432452_comet_python_twisted.web.txt
Q: Hot swapping python code (duck type functions?) I've been thinking about this far too long and haven't gotten any idea, maybe some of you can help. I have a folder of python scripts, all of which have the same surrounding body (literally, I generated it from a shell script), but have one chunk that's different tha...
Hot swapping python code (duck type functions?)
I've been thinking about this far too long and haven't gotten any idea, maybe some of you can help. I have a folder of python scripts, all of which have the same surrounding body (literally, I generated it from a shell script), but have one chunk that's different than all of them. In other words: Top piece of code (al...
[ "If you know the name of the function as a string and the name of module as a string, then you can do\nmod = __import__(module_name)\nfn = getattr(mod, fn_name)\nfn()\n\n", "Another possible solution is to have each of your repetitive files import the functionality from the main file\nfrom topAndBottom import top...
[ 4, 4, 2, 0, 0, 0 ]
[]
[]
[ "blender", "python", "python_3.x" ]
stackoverflow_0003432506_blender_python_python_3.x.txt
Q: How to get the size of a python object in bytes on Google AppEngine? I need to compute the sizes of some python objects, so I can break them up and store them in memcache without hitting size limits. 'sizeof()' doesn't seem to be present on python objects in the GAE environment and sys.getsizeof() is also unavaila...
How to get the size of a python object in bytes on Google AppEngine?
I need to compute the sizes of some python objects, so I can break them up and store them in memcache without hitting size limits. 'sizeof()' doesn't seem to be present on python objects in the GAE environment and sys.getsizeof() is also unavailable. GAE itself is clearly checking sizes behind the scenes to enforce th...
[ "memcache internally and invariably uses pickle and stores the resulting string, so you can check with len(pickle.dumps(yourobject, -1)). Note that sys.getsizeof (which requires 2.6 or better, which is why it's missing on GAE) would not really help you at all:\n>>> import sys\n>>> sys.getsizeof(23)\n12\n>>> import...
[ 13 ]
[]
[]
[ "google_app_engine", "memcached", "pickle", "python" ]
stackoverflow_0003432402_google_app_engine_memcached_pickle_python.txt
Q: File object in memory using Python I'm not sure how to word this exactly but I have a script that downloads an SSL certificate from a web server to check it's expiration date. To do this, I need to download the CA certificates. Currently I write them to a temporary file in the /tmp directory and read it back later...
File object in memory using Python
I'm not sure how to word this exactly but I have a script that downloads an SSL certificate from a web server to check it's expiration date. To do this, I need to download the CA certificates. Currently I write them to a temporary file in the /tmp directory and read it back later but I am sure there must be a way to do...
[ "the response from urllib is a file object. just use those wherever you are using the actual files instead. This is assuming that the code that consumes the file objects doesn't need to write to them of course.\n", "Wow, don't do this. You're hitting cacert's site every time? That's INCREDIBLY rude and needlessly...
[ 4, 4, 1 ]
[]
[]
[ "file", "memory", "python" ]
stackoverflow_0003432911_file_memory_python.txt
Q: Generating custom forms from DB schema I am a current web2py user, but find I still go back to Django once in a while (where I started). Specifically when working on projects where I want to make use of some specific django apps/plugins/extensions that don't yet exist in web2py. One thing that I can't live withou...
Generating custom forms from DB schema
I am a current web2py user, but find I still go back to Django once in a while (where I started). Specifically when working on projects where I want to make use of some specific django apps/plugins/extensions that don't yet exist in web2py. One thing that I can't live without in web2py, which I am looking for a soluti...
[ "If you haven't already, take a look at Django's ModelForm. I am assuming that you have models mapped to the tables in question. Vanilla ModelForm instances will work without JS. However ModelForms are usually defined ahead of time and not constructed on the fly. I suppose they can be created on the fly but that wo...
[ 1, 1 ]
[]
[]
[ "django", "django_forms", "pylons", "python", "web2py" ]
stackoverflow_0003431722_django_django_forms_pylons_python_web2py.txt
Q: Number in python - 010 Possible Duplicate: How do you express binary literals in Python? When using the interactive shell: print 010 I get back an 8. I started playing around using other numbers having zeroes before (0110 = 72, 013 = 11) but I could not figure it out... What is going on here? A: Numbers ente...
Number in python - 010
Possible Duplicate: How do you express binary literals in Python? When using the interactive shell: print 010 I get back an 8. I started playing around using other numbers having zeroes before (0110 = 72, 013 = 11) but I could not figure it out... What is going on here?
[ "Numbers entered with a leading zero are interpreted as octal (base 8).\n007 == 7\n010 == 8\n011 == 9\n\n", "like many languages, an integer with a leading zero is interpreted as an octal. this means that it's base eight. for example, 020 has decimal value 16 and 030 has decimal value 24.\nfor the sake of complet...
[ 13, 3, 3 ]
[]
[]
[ "numbers", "python", "python_2.x", "syntax" ]
stackoverflow_0003433150_numbers_python_python_2.x_syntax.txt
Q: type enforcement on _ssl.sslwrap function params The _ssl.sslwrap function appears to check to see if the sock passed in is a subclass of _socket.socket. I am passing in a class that implements the interface of _socket.socket. It gets mad because my socket isn't a subclass. Is this something I should fix on my s...
type enforcement on _ssl.sslwrap function params
The _ssl.sslwrap function appears to check to see if the sock passed in is a subclass of _socket.socket. I am passing in a class that implements the interface of _socket.socket. It gets mad because my socket isn't a subclass. Is this something I should fix on my side, or is this something that I should ask about from...
[ "I agree that explicitly enforcing the type hierarchy seems un-Pythonic and that you might want to ask the developers about that.\nOTOH, I wonder if it has to do with _ssl and _socket being the implementation modules for ssl and socket. I haven't used ssl, and I've barely used socket, but is it actually routinely n...
[ 1 ]
[]
[]
[ "python", "sockets", "ssl" ]
stackoverflow_0003433115_python_sockets_ssl.txt
Q: Elegant way to count frequency and correlation of many-to-many relationships with Django ORM? I have a Pizza model and a Topping model, with a many-to-many relationship between the two. Can you recommend an elegant way to extract: the popularity (frequency) of each topping the correlation between toppings (i.e. w...
Elegant way to count frequency and correlation of many-to-many relationships with Django ORM?
I have a Pizza model and a Topping model, with a many-to-many relationship between the two. Can you recommend an elegant way to extract: the popularity (frequency) of each topping the correlation between toppings (i.e. which sets of toppings are most frequent) Thanks
[ "Update: Found a better way using a separate model for the join table. Consider a relationship like this:\nclass Weapon(models.Model):\n name = models.CharField(...)\n\nclass Unit(models.Model):\n weapons = models.ManyToManyField(Weapon, through = 'Units_Weapons')\n\nclass Units_Weapons(models.Model):\n un...
[ 1 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0003432184_django_django_orm_python.txt
Q: Is there a way to have a class evaluate as a number? i have a python class like so: class TAG_Short(NBTTag): def __init__(self, value=None): self.name = None self.value = value def __repr__(self): return "TAG_Short: %i" % self.value This tag is filled out at runtime, but i'd also ...
Is there a way to have a class evaluate as a number?
i have a python class like so: class TAG_Short(NBTTag): def __init__(self, value=None): self.name = None self.value = value def __repr__(self): return "TAG_Short: %i" % self.value This tag is filled out at runtime, but i'd also like to be able to use it like: mytag = TAG_Short(3) mycal...
[ "You have to overload some operators. For the example you present, these are the methods you should overload:\ndef __add__(self, other):\n return self.value + other\n\ndef __mod__(self, other):\n return self.value % other\n\ndef __rdiv__(self, other):\n return other / self.value\n\nSee this guide for additional ...
[ 4, 3, 1, 1 ]
[]
[]
[ "class", "python" ]
stackoverflow_0003433227_class_python.txt
Q: Python--How do I write the value of a variable into the pasteboard in iPhone (iOS 4)/ I am running iOS 4 on a jailbroken iPhone 3GS. Before I upgraded to iOS 4, I had installed Python on the iPhone and had found the following snippet of Python code to copy a variable (key in this case) to the pasteboard. I then ...
Python--How do I write the value of a variable into the pasteboard in iPhone (iOS 4)/
I am running iOS 4 on a jailbroken iPhone 3GS. Before I upgraded to iOS 4, I had installed Python on the iPhone and had found the following snippet of Python code to copy a variable (key in this case) to the pasteboard. I then was able to open another application and paste the value into a text field. out = os.popen(...
[ "You need to install the package \"Erica Utilities\" available in the modmyi repository (enabled by default) in Cydia.\n" ]
[ 2 ]
[]
[]
[ "ios4", "iphone", "pyobjc", "python" ]
stackoverflow_0003432827_ios4_iphone_pyobjc_python.txt
Q: Python tags loop How would you replace these tags with actual data: [|RSSITEMS:] [|RSSITEM:TITLE|] [|RSSITEM:CONTENT|] [|END:RSSITEMS|] [|RSSITEMS:] starts loop at the top and ends its [|END:RSSITEMS|] [|RSSITEM:TITLE|] and [|RSSITEM:CONTENT|] should be replaced with data from rss feeds. Feed data is already ...
Python tags loop
How would you replace these tags with actual data: [|RSSITEMS:] [|RSSITEM:TITLE|] [|RSSITEM:CONTENT|] [|END:RSSITEMS|] [|RSSITEMS:] starts loop at the top and ends its [|END:RSSITEMS|] [|RSSITEM:TITLE|] and [|RSSITEM:CONTENT|] should be replaced with data from rss feeds. Feed data is already in database. Can not u...
[ "Maybe you could use an existing template engine instead, such as Cheetah (example) or the one from Django (example with for loop).\n", "Don't use custom templates for RSS. There is a syndication framework:\nhttp://docs.djangoproject.com/en/dev/ref/contrib/syndication/\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003433201_python.txt
Q: pyGTK Multiple line input fields? Already searched on google... doesnt seem to be there... help! A: http://www.pygtk.org/pygtk2tutorial/sec-TextViews.html http://www.pygtk.org/docs/pygtk/class-gtktextview.html
pyGTK Multiple line input fields?
Already searched on google... doesnt seem to be there... help!
[ "http://www.pygtk.org/pygtk2tutorial/sec-TextViews.html\nhttp://www.pygtk.org/docs/pygtk/class-gtktextview.html\n" ]
[ 4 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003433776_pygtk_python.txt
Q: "Vanilla" web python I was reading on web2py framework for a hobby project of mine I am doing. I learned how to program in Python when I was younger so I do have a grasp on it. Right now I am more of a PHP dev but kindda loathe it. I just have this doubt that pops in: Is there a way to use "Vanilla" python on the ...
"Vanilla" web python
I was reading on web2py framework for a hobby project of mine I am doing. I learned how to program in Python when I was younger so I do have a grasp on it. Right now I am more of a PHP dev but kindda loathe it. I just have this doubt that pops in: Is there a way to use "Vanilla" python on the backend? I mean Vanilla li...
[ "The mixing of logic, content, and presentation as naïvely encouraged by PHP is an abomination. It is the polar opposite of good design practice, and should not be imported to other languages (it shouldn't even be used in PHP, and thankfully the PHP world in general is ever so slowly moving away from it).\nYou shou...
[ 3, 2, 2 ]
[]
[]
[ "backend", "python" ]
stackoverflow_0003433806_backend_python.txt
Q: Python window focus I would like to find out if a window has focus. I am using pyGTK and would be helpful to us that but have got some Xlib in my script as well. I've used: self.window.add_events( gdk.FOCUS_CHANGE_MASK ) self.window.connect("focus-in-event", self.helloworld) but this gives me the event every time...
Python window focus
I would like to find out if a window has focus. I am using pyGTK and would be helpful to us that but have got some Xlib in my script as well. I've used: self.window.add_events( gdk.FOCUS_CHANGE_MASK ) self.window.connect("focus-in-event", self.helloworld) but this gives me the event every time the window is being focu...
[ "You can check whether a window is active using the is-active property. Connect to notify::is-active to get a notification when the property value changes.\nExample:\ndef is_active_changed(window, param):\n print window.props.is_active\nwindow.connect('notify::is-active', is_active_changed)\n\n" ]
[ 2 ]
[]
[]
[ "focus", "gtk", "pygtk", "python", "xlib" ]
stackoverflow_0003433615_focus_gtk_pygtk_python_xlib.txt
Q: import django module I am trying to import from django.http import HttpResponse, but I am getting the following exception: ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. Could anyone help me please? Thanks in advance A: If you want to use Django from ...
import django module
I am trying to import from django.http import HttpResponse, but I am getting the following exception: ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. Could anyone help me please? Thanks in advance
[ "If you want to use Django from a (say) Python script, you have to setup the settings module as you said.\nAnother way of doing, is as follow:\n#!/usr/bin/python\nfrom django.core.management import setup_environ\nimport os\nimport settings\n\nos.environ['DJANGO_SETTINGS_MODULE'] = \"mysite.settings\" # or just \"se...
[ 4, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003433885_django_python.txt
Q: add item to dictionary i read a lot in that forum, but i couldn't find a proper way to add all items to my dictionary... So maybe someone can help me! first a explanation: rows = cur.fetchall() columns=[desc[0] for desc in cur.description] GID_Distances = {} if len(rows) > 0: for row in rows: items ...
add item to dictionary
i read a lot in that forum, but i couldn't find a proper way to add all items to my dictionary... So maybe someone can help me! first a explanation: rows = cur.fetchall() columns=[desc[0] for desc in cur.description] GID_Distances = {} if len(rows) > 0: for row in rows: items = zip(columns, row) GI...
[ "If you have an iterable of pairs i.e. [(k1,v1),(k2,v2),...], you could apply dict on it to make it a dictionary. Therefore, your code could be written simply as\nrows = cur.fetchall() \ncolumns = [desc[0] for desc in cur.description] \n# or: columns = list(map(operator.itemgetter(0), cur.description))\n# don'...
[ 3, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003433971_dictionary_python.txt
Q: Django - how to extend 3rd party models without modifying I want to add a column to a database table but I don't want to modify the 3rd party module in case I need/decide to upgrade the module in the future. Is there a way I can add this field within my code so that with new builds I don't have to add the field ma...
Django - how to extend 3rd party models without modifying
I want to add a column to a database table but I don't want to modify the 3rd party module in case I need/decide to upgrade the module in the future. Is there a way I can add this field within my code so that with new builds I don't have to add the field manually?
[ "You can use ModelName.add_to_class (or .contribute_to_class), but if you have already run syncdb, then there is no way to automatically have it add the columns you need.\nFor maintainable code, you will probably want to extend by sub-classing the desired model in your own app, and use something like south to handl...
[ 10, 1 ]
[]
[]
[ "django", "django_models", "model", "python" ]
stackoverflow_0003433131_django_django_models_model_python.txt
Q: Django model attribute to refer to arbitrary model instance I'm working on a logging app in Django to record when models in other apps are created, changed, or deleted. All I really need to record is the user who did it, a timestamp, a type of action, and the item that was changed. The user, timestamp, and action ...
Django model attribute to refer to arbitrary model instance
I'm working on a logging app in Django to record when models in other apps are created, changed, or deleted. All I really need to record is the user who did it, a timestamp, a type of action, and the item that was changed. The user, timestamp, and action type are all easy, but I'm not sure what a good way to store the ...
[ "Use generic relations which do just that (use instance id and model class) but are integrated in Django and you also get a shortcut attribute that returns related instance so you don't have to query it yourself. Example usage.\n", "Check out generic relations.\n" ]
[ 4, 1 ]
[]
[]
[ "django", "django_models", "generic_relations", "python" ]
stackoverflow_0003434402_django_django_models_generic_relations_python.txt
Q: testing urllib2 application, http responses loaded from files My python application makes many http requests to many urls using urllib2. I would like to build a unit test suite to test my data parsing and error handling code. I have a directory full of test data, with a number of files, each file containing a sin...
testing urllib2 application, http responses loaded from files
My python application makes many http requests to many urls using urllib2. I would like to build a unit test suite to test my data parsing and error handling code. I have a directory full of test data, with a number of files, each file containing a single http response, with headers and response data. (using curl -i)...
[ "I think the best approach is to mock a subset of httplib.HTTPConnection (call the resulting class mockcon for concreteness in the following) and add a handler using it and subclassing HTTPHandler (to use in build_opener -- the subclassing means it can replace HTTPHandler that build_opener uses by default):\nclass ...
[ 2, 1 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0003278418_python_urllib2.txt
Q: How to use os.spawnv to send email copy using Python? First let me say that I know it's better to use the subprocess module, but I'm editing other people's code and I'm trying to make as few changes as possible, which includes avoiding the importing any new modules. So I'd like to stick to the currently-imported ...
How to use os.spawnv to send email copy using Python?
First let me say that I know it's better to use the subprocess module, but I'm editing other people's code and I'm trying to make as few changes as possible, which includes avoiding the importing any new modules. So I'd like to stick to the currently-imported modules (os, sys, and paths) if at all possible. The code i...
[ "While it might not make sense, that does appear to be the case\nimport os\n\nos.spawnv(os.P_WAIT,\"/usr/bin/wc\", (\"/usr/bin/wc\",))\nos.execv(\"/usr/bin/wc\", (\"/usr/bin/wc\",))\n\n$ cat j.py | python j.py \n 4 6 106\n 0 0 0\n\nIn which case you might do something like this\nim...
[ 1, 0 ]
[]
[]
[ "mailman", "postfix_mta", "process", "python" ]
stackoverflow_0003269770_mailman_postfix_mta_process_python.txt
Q: How to develop an Avahi client/server I am trying to develop a client/server solution using python, the server must broadcast the service availability using Avahi. I am using the following code to publish the service: import avahi import dbus __all__ = ["ZeroconfService"] class ZeroconfService: """A simple c...
How to develop an Avahi client/server
I am trying to develop a client/server solution using python, the server must broadcast the service availability using Avahi. I am using the following code to publish the service: import avahi import dbus __all__ = ["ZeroconfService"] class ZeroconfService: """A simple class to publish a network service with zero...
[ "I have found that the code works as expect. I had firewall rules blocking the avahi related publishing.\n" ]
[ 4 ]
[]
[]
[ "avahi", "python" ]
stackoverflow_0003430245_avahi_python.txt
Q: How to get unpickling to work with iPython? I'm trying to load pickled objects in iPython. The error I'm getting is: AttributeError: 'FakeModule' object has no attribute 'World' Anybody know how to get it to work, or at least a workaround for loading objects in iPython in order to interactively browse them? Than...
How to get unpickling to work with iPython?
I'm trying to load pickled objects in iPython. The error I'm getting is: AttributeError: 'FakeModule' object has no attribute 'World' Anybody know how to get it to work, or at least a workaround for loading objects in iPython in order to interactively browse them? Thanks edited to add: I have a script called world.py...
[ "Looks like you've modified FakeModule between the time you pickled your data, and the time you're trying to unpickle it: specifically, you have removed from that module some top-level object named World (perhaps a class, perhaps a function).\nPickling serializes classes and function \"by name\", so they need to be...
[ 12, 2 ]
[]
[]
[ "ipython", "pickle", "python" ]
stackoverflow_0003431419_ipython_pickle_python.txt
Q: simplify simple C++ code -- something like Pythons any Right now, I have this code: bool isAnyTrue() { for(std::list< boost::shared_ptr<Foo> >::iterator i = mylist.begin(); i != mylist.end(); ++i) { if( (*i)->isTrue() ) return true; } return false; } I have used Boost here and the...
simplify simple C++ code -- something like Pythons any
Right now, I have this code: bool isAnyTrue() { for(std::list< boost::shared_ptr<Foo> >::iterator i = mylist.begin(); i != mylist.end(); ++i) { if( (*i)->isTrue() ) return true; } return false; } I have used Boost here and then but I couldn't really remember any simple way to write it ...
[ "C++ does not (yet) have a foreach construct. You have to write that yourself/\nThat said, you can use the std::find_if algorithm here:\nbool isAnyTrue()\n{\n return std::find_if(mylist.begin(), mylist.end(), std::mem_fun(&Foo::isTrue))\n != mylist.end();\n}\n\nAlso, you should probably be using std::v...
[ 6, 4, 4 ]
[]
[]
[ "any", "c++", "python" ]
stackoverflow_0003434582_any_c++_python.txt
Q: Python : Allowing methods not specifically defined to be called ala __getattr__ I'm trying to write a Python class that has the ability to do the following: c = MyClass() a = c.A("a name for A") # Calls internally c.create("A", "a name for A") b = c.B("a name for B") # Calls internally c.create("B", "a name for B"...
Python : Allowing methods not specifically defined to be called ala __getattr__
I'm trying to write a Python class that has the ability to do the following: c = MyClass() a = c.A("a name for A") # Calls internally c.create("A", "a name for A") b = c.B("a name for B") # Calls internally c.create("B", "a name for B") A and B could be anything (well, they're defined in a database, but I don't want t...
[ "Have __getattr__ return a local wrapper function:\nclass MyClass(object):\n def create(self, itemType, itemName):\n print \"Creating item %s with name %s\" % (itemType, itemName)\n\n def __getattr__(self, attrName):\n def create_wrapper(name):\n self.create(attrName, name)\n r...
[ 8, 6 ]
[]
[]
[ "class", "methods", "python" ]
stackoverflow_0003434938_class_methods_python.txt
Q: Calculate exact result of complex throw of two D30 Okay, this bugged me for several years, now. If you sucked in statistics and higher math at school, turn away, now. Too late. Okay. Take a deep breath. Here are the rules. Take two thirty sided dice (yes, they do exist) and roll them simultaneously. Add the two n...
Calculate exact result of complex throw of two D30
Okay, this bugged me for several years, now. If you sucked in statistics and higher math at school, turn away, now. Too late. Okay. Take a deep breath. Here are the rules. Take two thirty sided dice (yes, they do exist) and roll them simultaneously. Add the two numbers If both dice show <= 5 or >= 26, throw again and ...
[ "I had to first rewrite your code before I could understand it:\ndef OW60(sign=1):\n r1 = random.randint (1, 30)\n r2 = random.randint (1, 30)\n val = sign * (r1 + r2)\n\n islow = (r1<=5) + (r2<=5)\n ishigh = (r1>=26) + (r2>=26)\n\n if islow == 2 or ishigh == 2:\n return val + OW60(1)\n ...
[ 6, 2, 1, 0 ]
[]
[]
[ "math", "puzzle", "python", "statistics" ]
stackoverflow_0000302379_math_puzzle_python_statistics.txt
Q: How do you mix raw SQL with ORM APIs when you use django.db? ORM tools are great when the queries we need are simple select or insert clauses. But sometimes we may have to fall back to use raw SQL queries, because we may need to make queries so complex that simply using the ORM API can not give us an efficient and...
How do you mix raw SQL with ORM APIs when you use django.db?
ORM tools are great when the queries we need are simple select or insert clauses. But sometimes we may have to fall back to use raw SQL queries, because we may need to make queries so complex that simply using the ORM API can not give us an efficient and effective solution. What do you do to deal with the difference be...
[ "I personally strive to design my models so I don't have to deffer to writing raw SQL queries, or fallback to mixing in the ContentTypes framework for complex relationships, so I have no experience on the topic.\nThe documentation covers the topic of the APIs for performing raw SQL queries. You can either use the M...
[ 3, 1 ]
[]
[]
[ "django_models", "orm", "python", "sql" ]
stackoverflow_0003433707_django_models_orm_python_sql.txt
Q: Dynamic wx.RadioButtons I'm having some trouble with the procedure below. First pass through the procedure, everything appears to work OK. Subsequent passes, the labels overwrite the previous label w/o erasing, plus the initial loop that hides the buttons doesn't appear to function. def drawbutton(self, event): ...
Dynamic wx.RadioButtons
I'm having some trouble with the procedure below. First pass through the procedure, everything appears to work OK. Subsequent passes, the labels overwrite the previous label w/o erasing, plus the initial loop that hides the buttons doesn't appear to function. def drawbutton(self, event): rbuttons = [ wx.Radio...
[ "try calling self.Refresh() to force a repaint. \nhttp://www.wxpython.org/docs/api/wx.Window-class.html#Refresh\nBTW, the way you're using the 'i' is kinda confusing on the scope... \ni = 0\n....\nfor i in range(nphones):\n rbuttons[i].SetLabel(voice1.phones[i].name)\n rbuttons[i].Show()\n\ni =...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003434371_python_wxpython.txt
Q: Get selected path from response I am using response.headers['Content-Type'] = gluon.contenttype.contenttype('.xls') response.headers['Content-disposition'] = 'attachment; filename=projects.xls' to generate save as dialog box. Is there a way to get the selected path by the user? A: The browser displays the Save...
Get selected path from response
I am using response.headers['Content-Type'] = gluon.contenttype.contenttype('.xls') response.headers['Content-disposition'] = 'attachment; filename=projects.xls' to generate save as dialog box. Is there a way to get the selected path by the user?
[ "The browser displays the Save As dialog box to the user, then writes your content into that file. It doesn't inform the server what path the content was saved to. I'm afraid you can't get that information.\n", "If your question is about how to send the file contents to the user, you simply write the content to...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003434088_python.txt
Q: What is the best Python IDE for Mac OS X? Possible Duplicate: What’s a good IDE for Python on the Mac? Hi, I'm going to start a quite big python project development under Mac OS X. What is the best python IDE for Mac OS X -recommended freeware-. A: Pydev with Eclipse.
What is the best Python IDE for Mac OS X?
Possible Duplicate: What’s a good IDE for Python on the Mac? Hi, I'm going to start a quite big python project development under Mac OS X. What is the best python IDE for Mac OS X -recommended freeware-.
[ "Pydev with Eclipse.\n" ]
[ 2 ]
[]
[]
[ "ide", "macos", "python" ]
stackoverflow_0003435458_ide_macos_python.txt
Q: Unpacking big-endian encoded port number I'm trying to convert a big-endian 2 byte string into a numeric port number. I've already got some code, but I have no idea if it's right: from struct import unpack def unpack_port(big_endian-port): return unpack("!H", big_endian-port)[0] The port (using Python repr() )...
Unpacking big-endian encoded port number
I'm trying to convert a big-endian 2 byte string into a numeric port number. I've already got some code, but I have no idea if it's right: from struct import unpack def unpack_port(big_endian-port): return unpack("!H", big_endian-port)[0] The port (using Python repr() ) is \x1a\xe1, and I get 6881 out of that funct...
[ "Yes, '!' is the character that says 'network byte order', and 'H' says '16-bit unsigned integer', so your code is correct. 6881 is typically a Bittorrent port.\nIn this case, I believe '!' is the correct character. Since it's a port number, I expect your data is coming from a network. But, if you knew your data...
[ 4 ]
[]
[]
[ "endianness", "networking", "python" ]
stackoverflow_0003435589_endianness_networking_python.txt
Q: What language (Java or Python) + framework for mid sized web project? I plan to start a mid sized web project, what language + framework would you recommend? I know Java and Python. I am looking for something simple. Is App Engine a good option? I like the overall simplicity and free hosting, but I am worried abou...
What language (Java or Python) + framework for mid sized web project?
I plan to start a mid sized web project, what language + framework would you recommend? I know Java and Python. I am looking for something simple. Is App Engine a good option? I like the overall simplicity and free hosting, but I am worried about the datastore (how difficult is it to make it similarly fast as a standar...
[ "Since you mentioned python, I would suggest looking into Django. You may need to look harder for hosting options, however...\n", "\nIs App Engine a good option? I like the overall simplicity and free hosting, but I am worried about the datastore (how difficult is it to make it similarly fast as a standard SQL so...
[ 4, 3, 2, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "java", "python", "stripes", "web_applications" ]
stackoverflow_0003427946_google_app_engine_java_python_stripes_web_applications.txt
Q: Multi-split in Python How would I split a string by two opposing values? For example ( and ) are the "deliminators" and I have the following string: Wouldn't it be (most) beneficial to have (at least) some idea? I need the following output (as an array) ["Wouldn't it be ", "most", " beneficial to have ", "at leas...
Multi-split in Python
How would I split a string by two opposing values? For example ( and ) are the "deliminators" and I have the following string: Wouldn't it be (most) beneficial to have (at least) some idea? I need the following output (as an array) ["Wouldn't it be ", "most", " beneficial to have ", "at least", " some idea?"]
[ "re.split()\ns = \"Wouldn't it be (most) beneficial to have (at least) some idea?\"\nl = re.split('[()]', s);\n\n", "In this particular case, sounds like it would make more sense to first split by space and then trim the brackets.\nout = []\nfor element in \"Wouldn't it be (most) beneficial to have (at least) som...
[ 13, 1, 0, 0 ]
[]
[]
[ "python", "split", "string" ]
stackoverflow_0003435900_python_split_string.txt
Q: I need a message/queuing solution for my web-based system I am looking for a message/queuing solution for my web based system running on Ubuntu. The system was built on the following technologies: Javascript (Extjs framework) - Frontend PHP Python (Daemon service which interacts with the encryption device) Pyt...
I need a message/queuing solution for my web-based system
I am looking for a message/queuing solution for my web based system running on Ubuntu. The system was built on the following technologies: Javascript (Extjs framework) - Frontend PHP Python (Daemon service which interacts with the encryption device) Python pyserial - (Serial port interactions) MySQL Linux - Ccust...
[ "I believe the popular RabbitMQ implementation of AMQP offers a PHP extension (here) and you can definitely access AMQP in Python, e.g. via Qpid. RabbitMQ is also easy to install on Ubuntu (or Debian), see e.g. here.\nWhether via RabbitMQ or otherwise, adopting an open messaging and queueing protocol such as AMQP ...
[ 5, 0 ]
[]
[]
[ "message_queue", "mysql", "python", "ubuntu" ]
stackoverflow_0003435954_message_queue_mysql_python_ubuntu.txt
Q: Datetime/time issue with python (18 hours off) I'm working on making a small ban system, and the snippet below will tell the client how much time of their ban is remaining. The problem: When you call Bans.timeleft_str(), rather then showing something less then a day, it will show the timestamp + 18 hours. Snippet:...
Datetime/time issue with python (18 hours off)
I'm working on making a small ban system, and the snippet below will tell the client how much time of their ban is remaining. The problem: When you call Bans.timeleft_str(), rather then showing something less then a day, it will show the timestamp + 18 hours. Snippet: http://pastebin.com/Zumn0tLv This problem occurs if...
[ "time.time, as the docs I just pointed to say, works in UTC (once known as \"Greenwich\" time, now \"universal time coordinate\"). mktime, again as said in its docs, takes as argument \n9-tuple [...] which expresses the time in local time, not UTC.\n\nstrptime may work either way (but you're not supplying a timezo...
[ 1 ]
[]
[]
[ "datetime", "python", "time" ]
stackoverflow_0003436262_datetime_python_time.txt
Q: Confusion while counting elapsed time in python? So I wanted to compare the performance of python between 2.6 and 3.1, so I wrote this simple program test.py that will perform some basic lengthy operation: from time import time start = time() q = 2 ** 1000000000 q += 3 << 1000000000 print(q.__sizeof__(), time() - ...
Confusion while counting elapsed time in python?
So I wanted to compare the performance of python between 2.6 and 3.1, so I wrote this simple program test.py that will perform some basic lengthy operation: from time import time start = time() q = 2 ** 1000000000 q += 3 << 1000000000 print(q.__sizeof__(), time() - start) I didn't get what I expected, since after laun...
[ "There may be many explanations, such as a different set of directories (and zipfiles) on sys.path, automatically loaded/executed code at initialization, other processes running on the platform -- your code is not at all isolated nor repeatable, therefore its results are of very little value. Use python -mtimeit t...
[ 3, 2 ]
[]
[]
[ "python", "time" ]
stackoverflow_0003436291_python_time.txt
Q: Gender problem in a django i18n translation I need to solve a gender translation problem, and Django doesn't seem to have gettext contexts implemented yet... I need to translate from english: <p>Welcome, {{ username }}</p> In two forms of spanish, one for each gender. If user is a male: <p>Bienvenido, {{ username...
Gender problem in a django i18n translation
I need to solve a gender translation problem, and Django doesn't seem to have gettext contexts implemented yet... I need to translate from english: <p>Welcome, {{ username }}</p> In two forms of spanish, one for each gender. If user is a male: <p>Bienvenido, {{ username }}</p> and if is a female: <p>Bienvenida, {{ us...
[ "The way that I've solved this is:\n{% if profile.male %}\n{% blocktrans with profile.name as male %}Welcome, {{ male }}{% endblocktrans %}\n{% else %}\n{% blocktrans with profile.name as female %}Welcome, {{ female }}{% endblocktrans %}\n{% endif %}\n\n", "Django is just Python so you can use the Python gettext ...
[ 10, 4, 2 ]
[]
[]
[ "django", "internationalization", "localization", "python" ]
stackoverflow_0001329115_django_internationalization_localization_python.txt
Q: numpy arrays type conversion in C I would like to convert the numpy double array to numpy float array in C(Swig). I am trying to use PyObject *object = PyArray_FROM_OT(input,NPY_FLOAT) or PyObject *object = PyArray_FROMANY(input,NPY_FLOAT,0,0,NPY_DEFAULT) or PyObject *object = PyArray_FromObject(input,NPY_FLOAT...
numpy arrays type conversion in C
I would like to convert the numpy double array to numpy float array in C(Swig). I am trying to use PyObject *object = PyArray_FROM_OT(input,NPY_FLOAT) or PyObject *object = PyArray_FROMANY(input,NPY_FLOAT,0,0,NPY_DEFAULT) or PyObject *object = PyArray_FromObject(input,NPY_FLOAT,0,0) or PyObject *object = PyArray_Co...
[ "Your approach is correct, yet your assumption about they numpy C API is not. NPY_FLOAT is just an integral constant, yet the functions you posted require the type parameter to be a pointer to a PyArray_Descr struct.\nIn order to get a type description from a mere type, you can call PyArray_DescrFromType, so your c...
[ 5 ]
[]
[]
[ "numpy", "python", "swig" ]
stackoverflow_0003213654_numpy_python_swig.txt
Q: Accessing the underlying struct of a PyObject I am working on creating a python c extension but am having difficulty finding documentation on what I want to do. I basically want to create a pointer to a cstruct and be able to have access that pointer. The sample code is below. Any help would be appreciated. typede...
Accessing the underlying struct of a PyObject
I am working on creating a python c extension but am having difficulty finding documentation on what I want to do. I basically want to create a pointer to a cstruct and be able to have access that pointer. The sample code is below. Any help would be appreciated. typedef struct{ int x; int y; } Point; typedef struct ...
[ "Your PyArg_ParseTuple should not use format O but O! (see the docs):\nO! (object) [typeobject, PyObject *]\n\n\nStore a Python object in a C object\n pointer. This is similar to O, but\n takes two C arguments: the first is\n the address of a Python type object,\n the second is the address of the C\n variable ...
[ 3 ]
[]
[]
[ "c", "pointers", "python", "structure" ]
stackoverflow_0003436730_c_pointers_python_structure.txt
Q: Python to C code? I wrote a program in python (using standard python libraries) long ago. Now I need to write the same program in standard C due to the lack of python support for that device. Please suggest me programs or conversion method to convert that python code into C code. Thanks in advance. A: Shedskin...
Python to C code?
I wrote a program in python (using standard python libraries) long ago. Now I need to write the same program in standard C due to the lack of python support for that device. Please suggest me programs or conversion method to convert that python code into C code. Thanks in advance.
[ "Shedskin could do the trick:\n\nShed Skin is an experimental compiler,\n that can translate pure, but\n implicitly statically typed Python\n programs into optimized C++. It can\n generate stand-alone programs or\n extension modules that can be imported\n and used in larger Python programs.\n\n", "So there ...
[ 4, 1 ]
[]
[]
[ "c", "python" ]
stackoverflow_0003434524_c_python.txt
Q: Using beautifulSoup, trying to get all table rows that have a string in them I need to get all table rows on a page that contain a specific string 'abc123123' in them. The string is inside a TD, but I need the entire TR if it contains the 'abc123123' anywhere inside. I tried this: userrows = s.findAll('tr', conten...
Using beautifulSoup, trying to get all table rows that have a string in them
I need to get all table rows on a page that contain a specific string 'abc123123' in them. The string is inside a TD, but I need the entire TR if it contains the 'abc123123' anywhere inside. I tried this: userrows = s.findAll('tr', contents = re.compile('abc123123')) I'm not sure if contents is the write property. My ...
[ "No, the extra keyword arguments beyond the specified ones (name, attrs, recursive, text, limit) all refer to attributes of the tag you're searching for.\nYou cannot search for name and text at the same time (if you specify text, BS ignores name) so you need separate calls, e.g:\nallrows = s.findAll('tr')\nuserrows...
[ 4 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003436770_beautifulsoup_python.txt
Q: Expanding tuples in python In the following code: a = 'a' tup = ('tu', 'p') b = 'b' print 'a: %s, t[0]: %s, t[1]: %s, b:%s'%(a, tup[0], tup[1], b) How can I "expand" (can't figure out a better verb) tup so that I don't have to explicitly list all its elements? NOTE That I don't want to print tup per-se, but its i...
Expanding tuples in python
In the following code: a = 'a' tup = ('tu', 'p') b = 'b' print 'a: %s, t[0]: %s, t[1]: %s, b:%s'%(a, tup[0], tup[1], b) How can I "expand" (can't figure out a better verb) tup so that I don't have to explicitly list all its elements? NOTE That I don't want to print tup per-se, but its individual elements. In other wor...
[ "It is possible to flatten a tuple, but I think in your case, constructing a new tuple by concatenation is easier.\n'a: %s, t[0]: %s, t[1]: %s, b:%s'%((a,) + tup + (b,))\n# ^^^^^^^^^^^^^^^^^\n\n", "If you want to use the format method instead, you can just do:\n\"{0}{2}{3}{1}\".fo...
[ 9, 3, 2 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0003433913_python_tuples.txt
Q: source code trees: wide or deep After writing a few python appengine apps I find myself torn between two approaches to organizing my source code tree: wide or deep. For concreteness, consider an internal application for a small consulting shop to manage business operations like contact management, project tracki...
source code trees: wide or deep
After writing a few python appengine apps I find myself torn between two approaches to organizing my source code tree: wide or deep. For concreteness, consider an internal application for a small consulting shop to manage business operations like contact management, project tracking & reporting, and employee manageme...
[ "Caveat: I haven't worked in python specifically. Having said that...\nWide, and I'll tell you why: It never hurts to be able to remove things quickly. In my career I am often asked to add things and given a relatively reasonable schedule on which to do it, but when something needs to be removed, the request alm...
[ 4, 3, 2, 0 ]
[]
[]
[ "directory_structure", "google_app_engine", "python" ]
stackoverflow_0003436867_directory_structure_google_app_engine_python.txt
Q: escaping characters in a regex The regular expression below: [a-z]+[\\.\\?] Why is \\ slash used twice instead of once? A: The regular expression below: [a-z]+[\\.\\?] ...is not a regular expression but a string (which could be the pattern for a regular expression; you can build a RE for it by passing it to...
escaping characters in a regex
The regular expression below: [a-z]+[\\.\\?] Why is \\ slash used twice instead of once?
[ "\nThe regular expression below:\n\n [a-z]+[\\\\.\\\\?]\n\n...is not a regular expression but a string (which could be the pattern for a regular expression; you can build a RE for it by passing it to re.compile, for example).\n\nWhy is \\\\ slash used twice instead of\n once?\n\nYou may be misunderstanding what's ...
[ 3, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003437072_python_regex.txt
Q: determining the first sprite to animate in python/pygame so I have this spritesheet (4 sprites in a row and 3 in a coloumn) which I use to animate a character in a game I make. It animates just fine without a problem, like I want it to the problem start to arise when I want to change the state from "dash" (running...
determining the first sprite to animate in python/pygame
so I have this spritesheet (4 sprites in a row and 3 in a coloumn) which I use to animate a character in a game I make. It animates just fine without a problem, like I want it to the problem start to arise when I want to change the state from "dash" (running to the enemy) to "attack" (well, attack the enemy) it doesn't...
[ "Have you tested to ensure the starting value actually is 3, before that logic is executed? I ask because your summary includes reference to self._currentFrame, when your code refers to self.currentFrame -- are you assigning to one variable and checking another?\nEdit regarding the additional 'answer' posted by the...
[ 0, 0 ]
[]
[]
[ "animation", "pygame", "python" ]
stackoverflow_0003435718_animation_pygame_python.txt
Q: django 'module' object has no attribute 'call_command' I wrote a function like def cmd_run(host="localhost", port="8000"): """Run server at given host port (or localhost 8000)""" from django.core import management host_port = '%s:%s' % (host, port) management.call_command('runserver', host_port) W...
django 'module' object has no attribute 'call_command'
I wrote a function like def cmd_run(host="localhost", port="8000"): """Run server at given host port (or localhost 8000)""" from django.core import management host_port = '%s:%s' % (host, port) management.call_command('runserver', host_port) When I executed it, an Exception was thrown: Traceback (most ...
[ "Well, here it works... maybe your version of django has not this function? Try it in managed shell python manage.py shell and try help(management) to see if it is there on your version.\nAnother possibility is corruption or modification of the __init__.py file (where call_command is defined) in django.core.managem...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003436932_django_python.txt
Q: Why does this provided regular expression return true? I would like to know why following regular expression returns true: reg = re.compile (r'[0-9]%') reg.search ("50%") [0-9] would match any single digit, in this case 5. But then 0 doesn't match %, so it should return false, but it returns true. My code might h...
Why does this provided regular expression return true?
I would like to know why following regular expression returns true: reg = re.compile (r'[0-9]%') reg.search ("50%") [0-9] would match any single digit, in this case 5. But then 0 doesn't match %, so it should return false, but it returns true. My code might have syntax errors, but you get the gist of it.
[ "reg.search() matches the pattern anywhere in the string (so it matches the 0%). If you want the entire string to match, try this:\nre.compile(r'^[0-9]%$')\n^ - matches the start of the string\n$ - matches the end of the string\n", "This regex would match on the 0% portion of 50%.\n", "If you are searching for...
[ 8, 5, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003436950_python_regex.txt
Q: python read last line ! My problem is in this code: try: PassL = open(sys.argv[3], "r").readlines() print "[+] Passwords:",len(PassL),"\n" except(IOError): print "[-] Error: Check your wordlist path\n" sys.exit(1) for word in PassL: word = word.replace("\r","").replace("\n","") log...
python read last line !
My problem is in this code: try: PassL = open(sys.argv[3], "r").readlines() print "[+] Passwords:",len(PassL),"\n" except(IOError): print "[-] Error: Check your wordlist path\n" sys.exit(1) for word in PassL: word = word.replace("\r","").replace("\n","") login_form_seq = [ ('log', s...
[ "Most of your code never runs at all, because it's in an except block and unconditionally follows a sys.exit -- so execution will never get there, even if the exception does occur to trigger the except (if it doesn't occur of course the whole except is never entered). Look again at the code you posted...:\nexcept(...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003437250_python.txt
Q: How to step through Python threads independently? (WinPDB) I am trying to debug Python using WinPDB and I have multiple threads using threading.Thread. I can never seem to control the threads individually. If I break execution, the entire script breaks. If I step through the source code of one thread, all of th...
How to step through Python threads independently? (WinPDB)
I am trying to debug Python using WinPDB and I have multiple threads using threading.Thread. I can never seem to control the threads individually. If I break execution, the entire script breaks. If I step through the source code of one thread, all of the others continue to be interleaved and continue some of their e...
[ "I had a similar issue, it's not the most ideal answer, but I'll describe it for you and maybe you can work off of it.\nI more or less wrote a mini debugger. Udp Client / Server and a function that did nothing but grab a global lock, sleep .1 seconds, and then release it. This function got passed to each thread. ...
[ 1 ]
[]
[]
[ "debugging", "multithreading", "python", "winpdb" ]
stackoverflow_0003417212_debugging_multithreading_python_winpdb.txt
Q: How to call bash process from within django / wsgi? I'm using mod_wsgi apache2 adapter for a django site and I like to call some bash process within a view, using the usual ... p = subprocess.Popen("/home/example.com/restart-tomcat.sh", shell=True) sts = os.waitpid(p.pid, 0)[1] ... This code works perfectly from ...
How to call bash process from within django / wsgi?
I'm using mod_wsgi apache2 adapter for a django site and I like to call some bash process within a view, using the usual ... p = subprocess.Popen("/home/example.com/restart-tomcat.sh", shell=True) sts = os.waitpid(p.pid, 0)[1] ... This code works perfectly from within a usual python shell but does nothing (I can trace...
[ "The script itself may have 755 permissions, but things it calls might not have the correct permissions. Especially if you have tomcat running on port 80, which is a privileged port.\nThere are ways you can get around this sort of thing (setuid, sudo), but you'd better know exactly what you're doing.\nI'd change y...
[ 2, 0 ]
[]
[]
[ "bash", "django", "python", "subprocess", "tomcat" ]
stackoverflow_0002608464_bash_django_python_subprocess_tomcat.txt
Q: Python PySerial read-line timeout I'm using pyserial to communicate with a embedded devise. ser = serial.Serial(PORT, BAUD, timeout = TOUT) ser.write(CMD) z = ser.readline(eol='\n') So we send CMD to the device and it replies with an string of varing length ending in a '\n' if the devise cant replay then readlin...
Python PySerial read-line timeout
I'm using pyserial to communicate with a embedded devise. ser = serial.Serial(PORT, BAUD, timeout = TOUT) ser.write(CMD) z = ser.readline(eol='\n') So we send CMD to the device and it replies with an string of varing length ending in a '\n' if the devise cant replay then readline() times-out and z='' if the devise is...
[ "I think what you might like to do is..\nimport re\nimport time\nimport serial\n\ndef doRead(ser,term):\n matcher = re.compile(term) #gives you the ability to search for anything\n tic = time.time()\n buff = ser.read(128)\n # you can use if not ('\\n' in buff) too if you don't like re\n whi...
[ 5 ]
[]
[]
[ "pyserial", "python" ]
stackoverflow_0003437303_pyserial_python.txt
Q: How to Pass variables to python script? I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I...
How to Pass variables to python script?
I know it can be achieved by command line but I need to pass at least 10 variables and command line will mean too much of programming since these variables may or may not be passed. Actually I have build A application half in vB( for GUI ) and Half in python( for script ). I need to pass variables to python, similar, t...
[ "If you are using Python <2.7 I would suggest optparse.\noptparse is deprecated though, and in 2.7 you should use argparse\nIt makes passing named parameters a breeze.\n", "you can do something fun like call it as\nthepyscript.py \"x = 12,y = 'hello world', z = 'jam'\"\n\nand inside your script,\nparse do:\nstuff...
[ 9, 6, 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003434048_python.txt
Q: How do I disable a button after it's clicked in wxpython? There are two buttons in my little program, start and stop. And what I want is to disable the start button after I click it, and when I hit the stop button it should return to normal. How can I do this? I googled for a while and couldn't find the answer, ho...
How do I disable a button after it's clicked in wxpython?
There are two buttons in my little program, start and stop. And what I want is to disable the start button after I click it, and when I hit the stop button it should return to normal. How can I do this? I googled for a while and couldn't find the answer, hope you guys can help me out. Thanks!
[ "Use the button's Enable and Disable methods in the appropriate event handlers. There's a sample available at the link below:\n\nwxPython Button Demo\nIn this snippet we are playing around with wxPython's buttons, showing you how to bind the mouse click event, enable and disable, show and hide the buttons. Each bu...
[ 3 ]
[]
[]
[ "event_handling", "python", "wxpython" ]
stackoverflow_0003437438_event_handling_python_wxpython.txt
Q: How do you have python scripts display how much time it takes to execute each process? It was something like cMessage I think? I can't remember, could someone help me? A: cProfile ? To time a function, you can also use a decorator like this one: from functools import wraps import time def timed(f): """Time ...
How do you have python scripts display how much time it takes to execute each process?
It was something like cMessage I think? I can't remember, could someone help me?
[ "cProfile ?\nTo time a function, you can also use a decorator like this one:\nfrom functools import wraps\nimport time\n\ndef timed(f):\n \"\"\"Time a function.\"\"\"\n @wraps(f)\n def wrapper(*args, **kwds):\n start = time.clock()\n result = f(*args)\n end = 1000 * (time.clock() - sta...
[ 2 ]
[]
[]
[ "python", "runtime", "time" ]
stackoverflow_0003437465_python_runtime_time.txt
Q: Detect English verb tenses using NLTK I am looking for a way given an English text count verb phrases in it in past, present and future tenses. For now I am using NLTK, do a POS (Part-Of-Speech) tagging, and then count say 'VBD' to get past tenses. This is not accurate enough though, so I guess I need to go furthe...
Detect English verb tenses using NLTK
I am looking for a way given an English text count verb phrases in it in past, present and future tenses. For now I am using NLTK, do a POS (Part-Of-Speech) tagging, and then count say 'VBD' to get past tenses. This is not accurate enough though, so I guess I need to go further and use chunking, then analyze VP-chunks ...
[ "Thee exact answer depends on which chunker you intend to use, but list comprehensions will take you a long way. This gets you the number of verb phrases using a non-existent chunker.\nlen([phrase for phrase in nltk.Chunker(sentence) if phrase[1] == 'VP'])\n\nYou can take a more fine-grained approach to detect numb...
[ 10, 1 ]
[]
[]
[ "nlp", "nltk", "python" ]
stackoverflow_0003434144_nlp_nltk_python.txt
Q: Creating a Key Command in Python I'm writing my own simple key logger based on a script I found online. However, I'm trying to write a key command so that the logger program will close when this command is typed. How should I go about this? (Also I know it's not secure at all, however that's not a concern with thi...
Creating a Key Command in Python
I'm writing my own simple key logger based on a script I found online. However, I'm trying to write a key command so that the logger program will close when this command is typed. How should I go about this? (Also I know it's not secure at all, however that's not a concern with this program) For example Ctrl + 'exit' w...
[ "To get it to close via a certain command, say \"quit\" ... you'd want to create a buffer .... if you keep everything you log in a buffer, you can easily do\nbuff += newkeypress\nif \"quit\" in buff[-4:]:\n logfile.close()\n sys.exit(0)\n\nor you can do something like append/pop with a list .. or some other t...
[ 0 ]
[]
[]
[ "keylogger", "python", "windows" ]
stackoverflow_0003437545_keylogger_python_windows.txt
Q: Text mining: when to use parser, tagger, NER tool? I'm doing a project on mining blog contents and I need help differentiating on which tool to uses. When do I use a parser, when do I use a tagger, and when do I need to use a NER tool? For instance, I want to find out the most talked about topics/subjects between ...
Text mining: when to use parser, tagger, NER tool?
I'm doing a project on mining blog contents and I need help differentiating on which tool to uses. When do I use a parser, when do I use a tagger, and when do I need to use a NER tool? For instance, I want to find out the most talked about topics/subjects between several blogs; do I use a part-of-speech tagger to grab ...
[ "Instead of trying to reinvent the wheel, you might want to read up on Topic Models, which basically creates clusters of words that frequently occur together. Mallet has a readily available toolkit for doing such a task: http://mallet.cs.umass.edu/topics.php .\nTo answer your original question, POS tagger, parsers...
[ 3 ]
[]
[]
[ "nlp", "nltk", "python" ]
stackoverflow_0003108602_nlp_nltk_python.txt
Q: How to create the union of many sets using a generator expression? Suppose I have a list of sets and I want to get the union over all sets in that list. Is there any way to do this using a generator expression? In other words, how can I create the union over all sets in that list directly as a frozenset? A: Just...
How to create the union of many sets using a generator expression?
Suppose I have a list of sets and I want to get the union over all sets in that list. Is there any way to do this using a generator expression? In other words, how can I create the union over all sets in that list directly as a frozenset?
[ "Just use the .union() method.\n>>> l = [set([1,2,3]), set([4,5,6]), set([1,4,9])]\n>>> frozenset().union(*l)\nfrozenset([1, 2, 3, 4, 5, 6, 9])\n\nThis works for any iterable of iterables.\n", "I assume that what you're trying to avoid is the intermediate creations of frozenset objects as you're building up the u...
[ 64, 6, 4 ]
[]
[]
[ "generator", "python", "set" ]
stackoverflow_0003438140_generator_python_set.txt
Q: Python: date formatted with %x (locale) is not as expected I have a datetime object, for which I want to create a date string according to the OS locale settings (as specified e.g. in Windows'7 region and language settings). Following Python's datetime formatting documentation, I used the %x format code which is s...
Python: date formatted with %x (locale) is not as expected
I have a datetime object, for which I want to create a date string according to the OS locale settings (as specified e.g. in Windows'7 region and language settings). Following Python's datetime formatting documentation, I used the %x format code which is supposed to output "Locale’s appropriate date representation.". I...
[ "After reading the setlocale() documentation, I understood that the default OS locale is not used by Python as the default locale. To use it, I had to start my module with:\nimport locale\nlocale.setlocale(locale.LC_ALL, '')\n\nAlternatively, if you intend to only reset the locale's time settings, use just LC_TIME...
[ 8, 5 ]
[]
[]
[ "datetime", "internationalization", "locale", "python" ]
stackoverflow_0003438120_datetime_internationalization_locale_python.txt
Q: Reading file using python and and see if a particular string is there inthe file I have a file in the following format Summary;None;Description;Emails\nDarlene\nGregory Murphy\nDr. Ingram\n;DateStart;20100615T111500;DateEnd;20100615T121500;Time;20100805T084547Z Summary;Presence tech in smart energy management;Desc...
Reading file using python and and see if a particular string is there inthe file
I have a file in the following format Summary;None;Description;Emails\nDarlene\nGregory Murphy\nDr. Ingram\n;DateStart;20100615T111500;DateEnd;20100615T121500;Time;20100805T084547Z Summary;Presence tech in smart energy management;Description;;DateStart;20100628T130000;DateEnd;20100628T133000;Time;20100628T055408Z Summa...
[ "use the in operator to see if there is a match\nfor line in open(\"file\"):\n if \"string\" in line :\n ....\n\n", "A build on ghostdog74's answer:\ndef finder(line):\n '''Takes line number as argument. First line is number 0.'''\n with open('/home/vlad/Desktop/file.txt') as f:\n lines = f...
[ 1, 1, 1 ]
[]
[]
[ "compare", "file", "python" ]
stackoverflow_0003437530_compare_file_python.txt
Q: Create name of path files from list I want to create path of files from list. pathList = [['~/workspace'], ['test'], ['*'], ['*A', '*2'], ['*Z?', '*1??'], ['*'], ['*'], ['*'], ['*.*']] and I want [['', '~/workspace', 'test', '*', '*A', '*Z?', '*', '*', '*', '*.*']] [['', '~/workspace', 'test', '*', '*A', '*1??',...
Create name of path files from list
I want to create path of files from list. pathList = [['~/workspace'], ['test'], ['*'], ['*A', '*2'], ['*Z?', '*1??'], ['*'], ['*'], ['*'], ['*.*']] and I want [['', '~/workspace', 'test', '*', '*A', '*Z?', '*', '*', '*', '*.*']] [['', '~/workspace', 'test', '*', '*A', '*1??', '*', '*', '*', '*.*']] [['', '~/workspa...
[ "Anticipating the next step - you can create paths like this\n>>> import os, itertools\n>>> [os.path.join(*x) for x in itertools.product(*pathList)]\n['~/workspace/test/*/*A/*Z?/*/*/*/*.*',\n '~/workspace/test/*/*A/*1??/*/*/*/*.*',\n '~/workspace/test/*/*2/*Z?/*/*/*/*.*',\n '~/workspace/test/*/*2/*1??/*/*/*/*.*']\...
[ 2, 1, 1 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0003438736_list_loops_python.txt
Q: Is there a better error reporting via e-mail for Django? Quite often the error reports coming via e-mail are less than useful in tracking bugs. Most often this is due to missing session data and username of the user triggering the error. Is there a project or a library I could use to get more complete error report...
Is there a better error reporting via e-mail for Django?
Quite often the error reports coming via e-mail are less than useful in tracking bugs. Most often this is due to missing session data and username of the user triggering the error. Is there a project or a library I could use to get more complete error reports?
[ "You could write your own exception middleware, as suggested here (bottom of page).\nThere is a base snippets here and an example of how to extract the traceback here\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003438618_django_python.txt
Q: Tasks queue process in python Task is: I have task queue stored in db. It grows. I need to solve tasks by python script when I have resources for it. I see two ways: python script working all the time. But i don't like it (reason posible memory leak). python script called by cron and do a little part of task. But...
Tasks queue process in python
Task is: I have task queue stored in db. It grows. I need to solve tasks by python script when I have resources for it. I see two ways: python script working all the time. But i don't like it (reason posible memory leak). python script called by cron and do a little part of task. But i need to solve the problem of one...
[ "This is a bit of a vague question. One thing you should remember is that it is very difficult to leak memory in Python, because of the automatic garbage collection. croning a Python script to handle the queue isn't very nice, although it would work fine.\nI would use method 1; if you need more power you could make...
[ 1, 1, 1 ]
[]
[]
[ "python", "queue", "task" ]
stackoverflow_0003439020_python_queue_task.txt
Q: when i easy_install greenlet i got "error: Setup script exited with error: command 'gcc' failed with exit status 1 " when i easy_install greenlet(also eventlet) as the documents says in ubuntu 10.04 i got the error above. is there anyone know why? Expect your help! And I have install build-essential As I canot tak...
when i easy_install greenlet i got "error: Setup script exited with error: command 'gcc' failed with exit status 1 "
when i easy_install greenlet(also eventlet) as the documents says in ubuntu 10.04 i got the error above. is there anyone know why? Expect your help! And I have install build-essential As I canot take the format right here, so I paste the message printed out there http://sugelawa.appspot.com/?p=35001 Thank u very much!
[ "(Warning: Ubuntu specific answer. Somewhat applicable to Debian, to but I don't have the details in my head right now) To use easy_install to install modules that contain C extensions (like greenlet), you need a complete development stack installed on your system. For a basic install, the means build-essential for...
[ 8 ]
[]
[]
[ "easy_install", "linux", "python", "ubuntu" ]
stackoverflow_0003438624_easy_install_linux_python_ubuntu.txt