content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python/PySerial and CPU usage
I've created a script to monitor the output of a serial port that receives 3-4 lines of data every half hour - the script runs fine and grabs everything that comes off the port which at the end of the day is what matters...
What bugs me, however, is that the cpu usage seems rather hig... | Python/PySerial and CPU usage | I've created a script to monitor the output of a serial port that receives 3-4 lines of data every half hour - the script runs fine and grabs everything that comes off the port which at the end of the day is what matters...
What bugs me, however, is that the cpu usage seems rather high for a program that's just monitor... | [
"Maybe you could issue a blocking read(1) call, and when it succeeds use read(inWaiting()) to get the right number of remaining bytes.\n",
"Would a system style solution be better? Create the python script and have it executed via Cron/Scheduled Task?\npySerial shouldn't be using that much CPU but if its just sit... | [
16,
0
] | [] | [] | [
"cpu_usage",
"pyserial",
"python"
] | stackoverflow_0001328606_cpu_usage_pyserial_python.txt |
Q:
Stable python serialization (e.g. no pickle module relocation issues)
I am considering the use of Quantities to define a number together with its unit. This value most likely will have to be stored on the disk. As you are probably aware, pickling has one major issue: if you relocate the module around, unpickling w... | Stable python serialization (e.g. no pickle module relocation issues) | I am considering the use of Quantities to define a number together with its unit. This value most likely will have to be stored on the disk. As you are probably aware, pickling has one major issue: if you relocate the module around, unpickling will not be able to resolve the class, and you will not be able to unpickle ... | [
"Looks like an application of Wheeler's First Principle, \"all problems in computer science can be solved by another level of indirection\" (the Second Principle adds \"but that will usually create another problem\";-). Essentially what you need to do is an indirection to identify the type -- entity-within-type wil... | [
1
] | [] | [] | [
"pickle",
"python",
"serialization"
] | stackoverflow_0001328581_pickle_python_serialization.txt |
Q:
How do I use colour with Windows command prompt using Python?
I'm trying to patch a waf issue, where the Windows command prompt output isn't coloured when it's supposed to be. I'm trying to figure out how to actually implement this patch, but I'm having trouble finding sufficient resources - could someone point me... | How do I use colour with Windows command prompt using Python? | I'm trying to patch a waf issue, where the Windows command prompt output isn't coloured when it's supposed to be. I'm trying to figure out how to actually implement this patch, but I'm having trouble finding sufficient resources - could someone point me in right direction?
Update 1
Please don't suggest anything that re... | [
"It is possible thanks to ctypes and SetConsoleTextAttribute\nHere is an example\nfrom ctypes import *\nSTD_OUTPUT_HANDLE_ID = c_ulong(0xfffffff5)\nwindll.Kernel32.GetStdHandle.restype = c_ulong\nstd_output_hdl = windll.Kernel32.GetStdHandle(STD_OUTPUT_HANDLE_ID)\nfor color in xrange(16):\n windll.Kernel32.SetCo... | [
21,
3
] | [] | [] | [
"command_prompt",
"python",
"waf",
"windows"
] | stackoverflow_0001328643_command_prompt_python_waf_windows.txt |
Q:
How to freeze/grayish window in pygtk?
I want main window to "gray, freeze, stop working", when some other window is opened. Is there some default way to do it? Pretty much the same as gtk.Dialog is working.
EDIT: Currently I'm just replacing all contents by a text line, but I guess there should be better way.
A:... | How to freeze/grayish window in pygtk? | I want main window to "gray, freeze, stop working", when some other window is opened. Is there some default way to do it? Pretty much the same as gtk.Dialog is working.
EDIT: Currently I'm just replacing all contents by a text line, but I guess there should be better way.
| [
"You really shouldn't try to make a program become unresponsive.\nIf what you want to do is stop the user from using the window, make the dialog modal: gtk.Dialog.set_modal(True)\n"
] | [
3
] | [] | [] | [
"freeze",
"pygtk",
"python",
"window"
] | stackoverflow_0001329076_freeze_pygtk_python_window.txt |
Q:
Search function with PyGTKsourceview
I'm writing a small html editor in python mostly for personal use and have integrated a gtksourceview2 object into my Python code. All the mayor functions seem to work more or less, but I'm having trouble getting a search function to work. Obvioiusly the GUI work is already don... | Search function with PyGTKsourceview | I'm writing a small html editor in python mostly for personal use and have integrated a gtksourceview2 object into my Python code. All the mayor functions seem to work more or less, but I'm having trouble getting a search function to work. Obvioiusly the GUI work is already done, but I can't figure out how to somehow b... | [
"The reference for the C API can probably be helpful, including this chapter that I found \"Searching in a GtkSourceBuffer\".\nAs is the reference for the superclass gtk.TextBuffer\n",
"Here is the python doc, I couldn't find any up-to-date documentation so I stuffed it in my dropbox. Here is the link. What you w... | [
1,
1
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0001327906_pygtk_python.txt |
Q:
Django_tagging (v0.3/pre): Configuration issue
I am trying to use the django-tagging in one of my project and run into some errors.
I can play with tags in the shell but couldn't assign them from admin interface.
What I want to do is add "tag" functionality to a model and add/remove tags from Admin interface.
Why ... | Django_tagging (v0.3/pre): Configuration issue | I am trying to use the django-tagging in one of my project and run into some errors.
I can play with tags in the shell but couldn't assign them from admin interface.
What I want to do is add "tag" functionality to a model and add/remove tags from Admin interface.
Why is it the "tags" are seen by shell and not by "admin... | [
"The TagField requires an actual database column on your model; it uses this to cache the tags as entered. If you add a TagField to a model that already has a database table, you will need to add the column to the database table, just as with adding any other type of field. Either use a schema migration tool (like ... | [
4
] | [] | [] | [
"django",
"django_admin",
"python",
"tagging"
] | stackoverflow_0001326512_django_django_admin_python_tagging.txt |
Q:
Python Scrapy , how to define a pipeline for an item?
I am using scrapy to crawl different sites, for each site I have an Item (different information is extracted)
Well, for example I have a generic pipeline (most of information is the same) but now I am crawling some google search response and the pipeline must b... | Python Scrapy , how to define a pipeline for an item? | I am using scrapy to crawl different sites, for each site I have an Item (different information is extracted)
Well, for example I have a generic pipeline (most of information is the same) but now I am crawling some google search response and the pipeline must be different.
For example:
GenericItem uses GenericPipeline
... | [
"Now only one way - check Item type in pipeline and process it or return \"as is\"\npipelines.py:\nfrom grabbers.items import FeedItem\n\nclass StoreFeedPost(object):\n\n def process_item(self, domain, item):\n if isinstance(item, FeedItem):\n #process it...\n\n return item\n\nitems.py:\... | [
16
] | [] | [] | [
"python",
"scrapy",
"screen_scraping"
] | stackoverflow_0001056651_python_scrapy_screen_scraping.txt |
Q:
How do I efficiently do a bulk insert-or-update with SQLAlchemy?
I'm using SQLAlchemy with a Postgres backend to do a bulk insert-or-update. To try to improve performance, I'm attempting to commit only once every thousand rows or so:
trans = engine.begin()
for i, rec in enumerate(records):
if i % 1000 == 0:
... | How do I efficiently do a bulk insert-or-update with SQLAlchemy? | I'm using SQLAlchemy with a Postgres backend to do a bulk insert-or-update. To try to improve performance, I'm attempting to commit only once every thousand rows or so:
trans = engine.begin()
for i, rec in enumerate(records):
if i % 1000 == 0:
trans.commit()
trans = engine.begin()
try:
ins... | [
"You're hitting some weird Postgresql-specific behavior: if an error happens in a transaction, it forces the whole transaction to be rolled back. I consider this a Postgres design bug; it takes quite a bit of SQL contortionism to work around in some cases.\nOne workaround is to do the UPDATE first. Detect if it a... | [
5,
4
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0001330475_python_sqlalchemy.txt |
Q:
Study Objective-C , Ruby OR Python?
I am working on C++ since last 4-5 years . Recently I have bought iphone and macbook and want do do some programming for iphone.
So I have started reading one book about Objective-C. I have also learn that we can program with Ruby and Python on MAC.
So my question is which one t... | Study Objective-C , Ruby OR Python? | I am working on C++ since last 4-5 years . Recently I have bought iphone and macbook and want do do some programming for iphone.
So I have started reading one book about Objective-C. I have also learn that we can program with Ruby and Python on MAC.
So my question is which one to study? Which language you guys see the ... | [
"If you want to program for iphone then you should use objective-C. The entire iphone API is based on objective-C, and you have the benefits of using interface builder and IDE support from Xcode.\n",
"I use all the languages C++, Ruby, Python and Objective-C. I like each one in different ways. If you want to get ... | [
10,
8,
7,
7,
4,
3,
2,
2,
2,
2,
2,
1
] | [] | [] | [
"objective_c",
"programming_languages",
"python",
"ruby"
] | stackoverflow_0000550474_objective_c_programming_languages_python_ruby.txt |
Q:
How do I link relative to a Pylons application root?
In Pylons I have a mako template linking to /static/resource.css. How do I automatically link to /pylons/static/resource.css when I decide to map the application to a subdirectory on my web server?
A:
If you want your static file links to be relative to your a... | How do I link relative to a Pylons application root? | In Pylons I have a mako template linking to /static/resource.css. How do I automatically link to /pylons/static/resource.css when I decide to map the application to a subdirectory on my web server?
| [
"If you want your static file links to be relative to your app root, wrap them like this in your templates (assuming Mako and Pylons 0.9.7):\n${url('/static/resource.css')}\n\nThe root path of your app will be prepended. No need to define specific routes for each file.\n",
"What you want are static routes:\nmap.c... | [
2,
1
] | [] | [] | [
"mako",
"pylons",
"python"
] | stackoverflow_0001201555_mako_pylons_python.txt |
Q:
How Can I Empty the Used Memory With Python?
I have just written a .psf file in Python for executing an optimization algorithm for Abaqus package, but after some analysis it stops. Could you please help me and write Python code to free the memory?
Thanks
A:
You don't really explicitly free memory in Python. Wh... | How Can I Empty the Used Memory With Python? | I have just written a .psf file in Python for executing an optimization algorithm for Abaqus package, but after some analysis it stops. Could you please help me and write Python code to free the memory?
Thanks
| [
"You don't really explicitly free memory in Python. What you do is stop referencing it, and it gets freed automatically. Although del does this, it's very rare that you really need to use it in a well designed application.\nSo this is really a question of how not to use so much memory in Python. I'd say the main hi... | [
2,
1,
0
] | [] | [] | [
"memory",
"memory_management",
"python"
] | stackoverflow_0001331033_memory_memory_management_python.txt |
Q:
Python list filtering: remove subsets from list of lists
Using Python how do you reduce a list of lists by an ordered subset match [[..],[..],..]?
In the context of this question a list L is a subset of list M if M contains all members of L, and in the same order. For example, the list [1,2] is a subset of the li... | Python list filtering: remove subsets from list of lists | Using Python how do you reduce a list of lists by an ordered subset match [[..],[..],..]?
In the context of this question a list L is a subset of list M if M contains all members of L, and in the same order. For example, the list [1,2] is a subset of the list [1,2,3], but not of the list [2,1,3].
Example input:
a. [[1... | [
"This could be simplified, but:\nl = [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]]\nl2 = l[:]\n\nfor m in l:\n for n in l:\n if set(m).issubset(set(n)) and m != n:\n l2.remove(m)\n break\n\nprint l2\n[[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4... | [
9,
6,
1,
0,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0001318935_list_python.txt |
Q:
How to create probability density function graph using csv dictreader, matplotlib and numpy?
I'm trying to create a simple probability density function(pdf) graph using data from one column of a csv file using csv dictreader, matplotlib and numpy...
Is there an easy way to use CSV DictReader combined with numpy ar... | How to create probability density function graph using csv dictreader, matplotlib and numpy? | I'm trying to create a simple probability density function(pdf) graph using data from one column of a csv file using csv dictreader, matplotlib and numpy...
Is there an easy way to use CSV DictReader combined with numpy arrays? Below is code that doesn't work. The error message is TypeError: len() of unsized object, w... | [
"The line\na=scipy.stats.pdf_moments(x)\n\n\"Return[s] the Gaussian expanded pdf function given the list of central moments (first one is mean).\"\nThat is to say, a is a function, and you must take its value somehow.\nSo I modified the line:\nprob, bins, patches= hist([a(i/100.0) for i in xrange(0,100,1)], 10, ali... | [
4,
0
] | [] | [] | [
"csv",
"matplotlib",
"numpy",
"python",
"scipy"
] | stackoverflow_0001329105_csv_matplotlib_numpy_python_scipy.txt |
Q:
Soaplib functions with default arguments
I have to write soaplib method, that has many arguments. The idea is that the user should able able to choose, which arguments he wants to provide. Is that even possible?
I know it is possible in python generally, but there is an error, when i try to set it up like normal p... | Soaplib functions with default arguments | I have to write soaplib method, that has many arguments. The idea is that the user should able able to choose, which arguments he wants to provide. Is that even possible?
I know it is possible in python generally, but there is an error, when i try to set it up like normal python method with default arguments.
| [
"Create complex type\nclass Parameters(ClassSerializer):\n class types:\n param1 = primitive.String\n param2 = primitive.String\n param3 = primitive.String\n\n...\n\n@soapmethod(Parameters, _returns=primitive.String, _outVariableName='return')\ndef soSomething(self, parameters):\n if para... | [
0
] | [] | [] | [
"default_value",
"python",
"soap"
] | stackoverflow_0001227547_default_value_python_soap.txt |
Q:
Prevent python imports compiling
I have have a python file that imports a few frequently changed python files. I have had trouble with the imported files not recompiling when I change them. How do I stop them compiling?
A:
I don't think that's possible - its the way Python works. The best you could do, I think, ... | Prevent python imports compiling | I have have a python file that imports a few frequently changed python files. I have had trouble with the imported files not recompiling when I change them. How do I stop them compiling?
| [
"I don't think that's possible - its the way Python works. The best you could do, I think, is to have some kind of automated script which deletes *.pyc files at first. Or you could have a development module which automatically compiles all imports - try the compile module.\nI've personally not had this trouble befo... | [
3,
1,
1,
0
] | [] | [] | [
"compilation",
"import",
"python"
] | stackoverflow_0001331235_compilation_import_python.txt |
Q:
Why does weakproxy not always preserve equivalence in python?
MySQLDb uses weak proxy to prevent circular dependencies between cursors and connections.
But you would expect from the documentation on weakref that you could still tests for equivalence. Yet:
In [36]: interactive.cursor.connection.thread_id()
Out[36]:... | Why does weakproxy not always preserve equivalence in python? | MySQLDb uses weak proxy to prevent circular dependencies between cursors and connections.
But you would expect from the documentation on weakref that you could still tests for equivalence. Yet:
In [36]: interactive.cursor.connection.thread_id()
Out[36]: 4267758
In [37]: interactive.web_logic.conns.primary.thread_id()
... | [
"I've long found weakref.proxy's design and implementation to be somewhat shaky. Witness...:\n>>> import weakref\n>>> ob=set(range(23))\n>>> rob=weakref.proxy(ob)\n>>> rob==ob\nFalse\n>>> rob.__eq__(ob)\nTrue\n\n...DEFINITELY peculiar! In practice what I use from weakref are weak-key or sometimes weak-value dictio... | [
3,
1,
0
] | [] | [] | [
"python",
"weak_references"
] | stackoverflow_0001331800_python_weak_references.txt |
Q:
QSortFilterProxyModel.mapToSource crashes. No info why
I have the following code:
proxy_index = self.log_list.filter_proxy_model.createIndex(index, COL_REV)
model_index = self.log_list.filter_proxy_model.mapToSource(proxy_index)
revno = self.log_list.model.data(model_index,QtCore.Qt.DisplayRole)
self.setEditText(r... | QSortFilterProxyModel.mapToSource crashes. No info why | I have the following code:
proxy_index = self.log_list.filter_proxy_model.createIndex(index, COL_REV)
model_index = self.log_list.filter_proxy_model.mapToSource(proxy_index)
revno = self.log_list.model.data(model_index,QtCore.Qt.DisplayRole)
self.setEditText(revno.toString())
The code crashed on the second line. There... | [
"It may be that you're using the proxy model's createIndex() method incorrectly. Usually, the createIndex() method is called as part of a model's index() method implementation.\nHave you tried calling the proxy model's index() method to get a proxy index then mapping that to the source?\nPerhaps you could show the ... | [
2,
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"qt4"
] | stackoverflow_0000671340_pyqt_pyqt4_python_qt_qt4.txt |
Q:
Python multiprocessing for bulk file/conversion operation on Windows
I have written a python script which watches a directory for new subdirectories, and then acts on each subdirectory in a loop. We have an external process which creates these subdirectories. Inside each subdirectory is a text file and a number ... | Python multiprocessing for bulk file/conversion operation on Windows | I have written a python script which watches a directory for new subdirectories, and then acts on each subdirectory in a loop. We have an external process which creates these subdirectories. Inside each subdirectory is a text file and a number of images. There is one record (line) in the text file for each image. F... | [
"I agree that the design of this sounds like it could benefit from concurrency. Take a look at the multiprocessing module. You may also want to look at the threading module, and compare speeds. It's difficult to tell exactly how many cores are necessary to gain a benefit from multiprocessing vs. threading and ei... | [
0
] | [] | [] | [
"multiprocessing",
"python",
"windows"
] | stackoverflow_0001332583_multiprocessing_python_windows.txt |
Q:
Overloading failUnlessEqual in unittest.TestCase
I want to overload failUnlessEqual in unittest.TestCase so I created a new TestCase class:
import unittest
class MyTestCase(unittest.TestCase):
def failUnlessEqual(self, first, second, msg=None):
if msg:
msg += ' Expected: %r - Received %r' ... | Overloading failUnlessEqual in unittest.TestCase | I want to overload failUnlessEqual in unittest.TestCase so I created a new TestCase class:
import unittest
class MyTestCase(unittest.TestCase):
def failUnlessEqual(self, first, second, msg=None):
if msg:
msg += ' Expected: %r - Received %r' % (first, second)
unittest.TestCase.failUnless... | [
"You are calling assertEqual, but define failUnlessEqual. So why would you expect that your method is called - you are calling a different method, after all?\nPerhaps you have looked at the definition of TestCase, and seen the line\nassertEqual = assertEquals = failUnlessEqual\n\nThis means that the method assertEq... | [
2
] | [] | [] | [
"overloading",
"python",
"unit_testing"
] | stackoverflow_0001332656_overloading_python_unit_testing.txt |
Q:
import csv file into mysql database using django web application
i try to upload a csv file into my web application and store it into mysql database but failed.Please can anyone help me?
my user.py script:
def import_contact(request):
if request.method == 'POST':
form = UploadContactForm(request.POST, request.... | import csv file into mysql database using django web application | i try to upload a csv file into my web application and store it into mysql database but failed.Please can anyone help me?
my user.py script:
def import_contact(request):
if request.method == 'POST':
form = UploadContactForm(request.POST, request.FILES)
if form.is_valid():
csvfile = request.FILES['file']... | [
"Since you haven't provided the code for the getcsv function, I'll have to use my crystal ball here a bit.\nOne reason why the print in the for row in testReader: loop isn't working is that getcsv may already processes the file. Use the seek method to reset the objects position in the file to zero again. That way t... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0001332077_django_python.txt |
Q:
Display Django form inputs on thanks page
I'm attempting to take 4-5 fields from a large django form and display them on the thanks page.
I want to disply the values with a good degree of control, as i'll be building an iFrame with parameterd querystrings based on the form inputs.
Currently I have:
forms.py ----
-... | Display Django form inputs on thanks page | I'm attempting to take 4-5 fields from a large django form and display them on the thanks page.
I want to disply the values with a good degree of control, as i'll be building an iFrame with parameterd querystrings based on the form inputs.
Currently I have:
forms.py ----
-*- encoding: utf-8 -*-
from django import forms... | [
"The values available to the template are provided by the view.\nThe render_to_response function provides a dictionary of values that are passed to the template. See this.\nFor no good reason, you've provided locals(). Not sure why.\nYou want to provide a dictionary like request.POST -- not locals().\n\nYour loca... | [
0,
0
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0001292951_django_forms_python.txt |
Q:
Renaming a HTML file with Python
A bit of background:
When I save a web page from e.g. IE8 as "webpage, complete", the images and such that the page contains are placed in a subfolder with the postfix "_files". This convention allows Windows to synchronize the .htm file and the accompanying folder.
Now, in order t... | Renaming a HTML file with Python | A bit of background:
When I save a web page from e.g. IE8 as "webpage, complete", the images and such that the page contains are placed in a subfolder with the postfix "_files". This convention allows Windows to synchronize the .htm file and the accompanying folder.
Now, in order to keep the synchronization intact, whe... | [
"There is just one easy way: Have IE save the file again under the new name. But if you want to do it later, you must parse the HTML. In this case, BeautifulSoup is your friend.\n",
"If you rename the folder, I'm not sure how you can get around parsing the .htm file and replacing instances of _files with the new ... | [
1,
0,
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0001332876_html_python.txt |
Q:
Problem passing bash output to a python script
I'm fairly new to programming and I searched the internet for a way to pass bash output to a Python script.
I came up with this in bash.
XAS_SVN=`svn info`
ssh hudson@test "python/runtests.py $XAS_SVN"
And this in python.
import sys
print sys.argv[1]
When I echo $S... | Problem passing bash output to a python script | I'm fairly new to programming and I searched the internet for a way to pass bash output to a Python script.
I came up with this in bash.
XAS_SVN=`svn info`
ssh hudson@test "python/runtests.py $XAS_SVN"
And this in python.
import sys
print sys.argv[1]
When I echo $SVN_INFO I get the result.
Path: . URL:
//svn/rnd-... | [
"Since you have spaces in the variable, you need to escape them or read all the arguments in your script:\nprint ' '.join(sys.argv[1:])\n\nBut it might be better to use stdin/stdout to communicate, especially if there can be some characters susceptible to be interpreted by the shell in the output (like \"`$').\nIn ... | [
1,
0
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0001333107_bash_python.txt |
Q:
Python String Cleanup + Manipulation (Accented Characters)
I have a database full of names like:
John Smith
Scott J. Holmes
Dr. Kaplan
Ray's Dog
Levi's
Adrian O'Brien
Perry Sean Smyre
Carie Burchfield-Thompson
Björn Árnason
There are a few foreign names with accents in them that need to be convert... | Python String Cleanup + Manipulation (Accented Characters) | I have a database full of names like:
John Smith
Scott J. Holmes
Dr. Kaplan
Ray's Dog
Levi's
Adrian O'Brien
Perry Sean Smyre
Carie Burchfield-Thompson
Björn Árnason
There are a few foreign names with accents in them that need to be converted to strings with non-accented characters.
I'd like to convert ... | [
"Take a look at this link [redacted]\nHere is the code from the page\ndef latin1_to_ascii (unicrap):\n \"\"\"This replaces UNICODE Latin-1 characters with\n something equivalent in 7-bit ASCII. All characters in the standard\n 7-bit ASCII range are preserved. In the 8th bit range all the Latin-1\n accen... | [
12,
5,
3,
1,
1
] | [] | [] | [
"python",
"regex",
"string",
"unicode"
] | stackoverflow_0000930303_python_regex_string_unicode.txt |
Q:
Guitar Tablature and Music sheet oriented plugins for wordpress or Drupal
I'm familiar with wordpress and cakePHP; however, I'm building a small community website (hobby) that allows users to post music sheet (pdf/image) or guitar tabs ( text files). These music sheets should be organized by artists and songs. I'v... | Guitar Tablature and Music sheet oriented plugins for wordpress or Drupal | I'm familiar with wordpress and cakePHP; however, I'm building a small community website (hobby) that allows users to post music sheet (pdf/image) or guitar tabs ( text files). These music sheets should be organized by artists and songs. I've already built my own cms, but I'm not looking forward to maintain it as i'm s... | [
"It doesn’t sound like you have any music specific needs, you just need to be able to attach text, pdf or images to an item (node in Drupal) and assign tags to it. \nYou can use taxonomy in Drupal to assign artists to the nodes. I should think what you want is pretty simple to do. I would suggest that you try insta... | [
3,
1
] | [] | [] | [
"drupal",
"php",
"python",
"wordpress"
] | stackoverflow_0001328533_drupal_php_python_wordpress.txt |
Q:
Tix and Python 3.0
Has anyone seen anything in Tix work under python 3.0? I've tried to work through the examples but when creating anything it states that cnf is unsubscriptable.
I also noticed that none of the Dir Select stuff (DirList DirTree) works under 2.6.1.
Why doesn't Python either dump Tix or support it... | Tix and Python 3.0 | Has anyone seen anything in Tix work under python 3.0? I've tried to work through the examples but when creating anything it states that cnf is unsubscriptable.
I also noticed that none of the Dir Select stuff (DirList DirTree) works under 2.6.1.
Why doesn't Python either dump Tix or support it? Its got a lot of good... | [
"Likely what happened is that no one noticed the bug. (It's very hard to automatically test GUI libraries like Tix and Tkinter.) You should report bugs as you find them to http://bugs.python.org.\n",
"Generally speaking, if you're using third-party modules, you're better off avoiding Python 3.0 for now. If you'r... | [
1,
0,
0
] | [] | [] | [
"python",
"python_3.x",
"tix"
] | stackoverflow_0000399326_python_python_3.x_tix.txt |
Q:
Tick Python instances from Python
I am interrested in doing a programming game using python, and I would like to do it in the style of GunTactyx (http://apocalyx.sourceforge.net/guntactyx/index.php). Only much simpler, as I am primarily interrested in the parallel execution of python scripts from python.
Gun Tacty... | Tick Python instances from Python | I am interrested in doing a programming game using python, and I would like to do it in the style of GunTactyx (http://apocalyx.sourceforge.net/guntactyx/index.php). Only much simpler, as I am primarily interrested in the parallel execution of python scripts from python.
Gun Tactyx challenges the player to write a prog... | [
"Maybe you should look into fork of python: stackless, it allows concurrently running thousands of micro-threads without much performance penalty - every \"thread\" (these aren't real OS threads) could be one Unit.\nAlso it's very easy to implement Actor model with stackless:\n\nIn the actor model, everything is an... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0001333016_python.txt |
Q:
How can I access the iphone / ipod clipboard using python?
I want to modify a python application written for the ipod/iphone.
It should copy a string into the clipboard so that I can use it in another application.
Is it possible to access the iphone clipboard using python?
Thanks in advance.
UPDATE:
Thanks for rep... | How can I access the iphone / ipod clipboard using python? | I want to modify a python application written for the ipod/iphone.
It should copy a string into the clipboard so that I can use it in another application.
Is it possible to access the iphone clipboard using python?
Thanks in advance.
UPDATE:
Thanks for replying.
A bit of background: The python program is a vocabulary p... | [
"Sorry no, I'm assuming since you mention python that this is a web-based application? If so there is no way you can put something into/take something out of the user's clipboard automatically. However if it is webbased the user will be able to select any text/image and copy to paste elsewhere.\n"
] | [
0
] | [] | [] | [
"clipboard",
"iphone",
"ipod_touch",
"python"
] | stackoverflow_0001332846_clipboard_iphone_ipod_touch_python.txt |
Q:
Delete None values from Python dict
Newbie to Python, so this may seem silly.
I have two dicts:
default = {'a': 'alpha', 'b': 'beta', 'g': 'Gamma'}
user = {'a': 'NewAlpha', 'b': None}
I need to update my defaults with the values that exist in user. But only for those that have a value not equal to None. So I ne... | Delete None values from Python dict | Newbie to Python, so this may seem silly.
I have two dicts:
default = {'a': 'alpha', 'b': 'beta', 'g': 'Gamma'}
user = {'a': 'NewAlpha', 'b': None}
I need to update my defaults with the values that exist in user. But only for those that have a value not equal to None. So I need to get back a new dict:
result = {'a':... | [
"result = default.copy()\nresult.update((k, v) for k, v in user.iteritems() if v is not None)\n\n",
"With the update() method, and some generator expression:\nD.update((k, v) for k, v in user.iteritems() if v is not None)\n\n"
] | [
19,
7
] | [] | [] | [
"python"
] | stackoverflow_0001334020_python.txt |
Q:
Python design patterns, cross importing
I am using Python for automating a complex procedure that has few options.
I want to have the following structure in python.
- One "flow-class" containing the flow
- One helper class that contains a lot of "black boxes" (functions that do not often get changed).
99% of the t... | Python design patterns, cross importing | I am using Python for automating a complex procedure that has few options.
I want to have the following structure in python.
- One "flow-class" containing the flow
- One helper class that contains a lot of "black boxes" (functions that do not often get changed).
99% of the time, I modify things in the flow-class so I o... | [
"you need to do helper_class.getUserIinput() in your flow_class. It's not about cross-importing. Once it's fixed you'll get AttributeError that is indeed related to cross-importing.\nAt this stage you'll need to implement logic of getting getUserInput defined before importing flow_class.\nAnd to comment on your las... | [
2,
1,
1
] | [] | [] | [
"design_patterns",
"python",
"python_3.x"
] | stackoverflow_0001334134_design_patterns_python_python_3.x.txt |
Q:
AttributeError: 'NoneType' object has no attribute 'GetDataStore'
I guys, I developing a utility in python and i have 2 object the main class and an database helper for get sqlserver data.
database.py
import _mssql
class sqlserver(object):
global _host, _userid, _pwd, _db
def __new__ (self, host, userid... | AttributeError: 'NoneType' object has no attribute 'GetDataStore' | I guys, I developing a utility in python and i have 2 object the main class and an database helper for get sqlserver data.
database.py
import _mssql
class sqlserver(object):
global _host, _userid, _pwd, _db
def __new__ (self, host, userid, pwd, database):
_host = host
_userid = userid
... | [
"First of all:\n\nThe __new__ method should be named __init__.\nRemove the global _host etc. line\n\nThen change the __init__ method:\nself.host = host\nself.userid = userid\netc.\n\nAnd change GetDataStore:\nconn = _mssql.connect(server=self.host, user=self.userid, etc.)\n\nThat should do the trick.\nI suggest you... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001334607_python.txt |
Q:
Aggregate photos from various services into one Stream
Helllo All,
I'm looking to aggregate photos from various streams into one stream in a similar manner as to friend feed.
I'd like to be able to watch flickr and picasa and other sites with RSS feeds of my choosing and then create a timeline of top photos.
F... | Aggregate photos from various services into one Stream | Helllo All,
I'm looking to aggregate photos from various streams into one stream in a similar manner as to friend feed.
I'd like to be able to watch flickr and picasa and other sites with RSS feeds of my choosing and then create a timeline of top photos.
For example, assume that X's below are photos:
Event Name -- ... | [
"I suggest using YQL.\n\nThe Yahoo! Query Language is an expressive SQL-like language that lets you query, filter, and join data across Web services.\n\nWith it you can do things like the following:\nselect * from query.multi where queries=\"select enclosure from rss where url='http://picasaweb.google.com/data/feed... | [
2,
1
] | [] | [] | [
"javascript",
"php",
"python"
] | stackoverflow_0001334477_javascript_php_python.txt |
Q:
How can I mass-assign SA ORM object attributes?
I have an ORM mapped object, that I want to update. I have all attributes validated and secured in a dictionary (keyword arguments). Now I would like to update all object attributes as in the dictionary.
for k,v in kw.items():
setattr(myobject, k, v)
doesnt work... | How can I mass-assign SA ORM object attributes? | I have an ORM mapped object, that I want to update. I have all attributes validated and secured in a dictionary (keyword arguments). Now I would like to update all object attributes as in the dictionary.
for k,v in kw.items():
setattr(myobject, k, v)
doesnt work (AttributeError Exception), thrown from SQLAlchemy.
... | [
"myobject.__dict__.update(**kw)\n\n",
"You are trying to assign a unicode string to a relation attribute. Say you have:\n class ClassA(Base):\n ...\n b_id = Column(None, ForeignKey('b.id'))\n b = relation(ClassB)\n\nAnd you are trying to do:\n my_object = ClassA()\n my_object.b = \"foo\"\n\nWhen you s... | [
4,
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0001334171_python_sqlalchemy.txt |
Q:
How to change baseclass
I have a class which is derived from a base class, and have many many lines of code
e.g.
class AutoComplete(TextCtrl):
.....
What I want to do is change the baseclass so that it works like
class AutoComplete(PriceCtrl):
.....
I have use for both type of AutoCompletes and may be wo... | How to change baseclass | I have a class which is derived from a base class, and have many many lines of code
e.g.
class AutoComplete(TextCtrl):
.....
What I want to do is change the baseclass so that it works like
class AutoComplete(PriceCtrl):
.....
I have use for both type of AutoCompletes and may be would like to add more base cla... | [
"You could have a factory for your classes:\ndef completefactory(baseclass):\n class AutoComplete(baseclass):\n pass\n return AutoComplete\n\nAnd then use:\nTextAutoComplete = completefactory(TextCtrl)\nPriceAutoComplete = completefactory(PriceCtrl)\n\nOn the other hand depending on what you want to ac... | [
7,
2,
1
] | [] | [] | [
"class",
"dynamic",
"python"
] | stackoverflow_0001334222_class_dynamic_python.txt |
Q:
Python urllib.urlopen() call doesn't work with a URL that a browser accepts
If I point Firefox at http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes, I get a page of HTML. But if I try this in Python:
import urllib
site = 'http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes'
req = urllib.url... | Python urllib.urlopen() call doesn't work with a URL that a browser accepts | If I point Firefox at http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes, I get a page of HTML. But if I try this in Python:
import urllib
site = 'http://bitbucket.org/tortoisehg/stable/wiki/Home/ReleaseNotes'
req = urllib.urlopen(site)
text = req.read()
I get the following:
500 Internal Server Error
The ... | [
"You're doing nothing wrong, on the surface, and as the error page says you should contact the site's administrators because they're the ones with the server logs which may explain what's happening. Fortunately, bitbucket's site admins are a friendly bunch!\nNo doubt there is some header or combination of headers t... | [
3,
3
] | [
"I don't think you're doing anything wrong -- it looks like this server was just down? Your script worked fine for me ('text' contained the same data as that displayed in the browser).\n"
] | [
-2
] | [
"bitbucket",
"python",
"urllib"
] | stackoverflow_0001335439_bitbucket_python_urllib.txt |
Q:
Is it a good idea to hash a Python class?
For example, suppose I do this:
>>> class foo(object):
... pass
...
>>> class bar(foo):
... pass
...
>>> some_dict = { foo : 'foo',
... bar : 'bar'}
>>>
>>> some_dict[bar]
'bar'
>>> some_dict[foo]
'foo'
>>> hash(bar)
165007700
>>> id(bar)
165007700
Based on tha... | Is it a good idea to hash a Python class? | For example, suppose I do this:
>>> class foo(object):
... pass
...
>>> class bar(foo):
... pass
...
>>> some_dict = { foo : 'foo',
... bar : 'bar'}
>>>
>>> some_dict[bar]
'bar'
>>> some_dict[foo]
'foo'
>>> hash(bar)
165007700
>>> id(bar)
165007700
Based on that, it looks like the class is getting hashed as... | [
"Yes, any object that doesn't implement a __hash__() function will return its id when hashed. From Python Language Reference: Data Model - Basic Customization:\n\nUser-defined classes have __cmp__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() ... | [
8,
6
] | [] | [] | [
"class",
"dictionary",
"hash",
"inheritance",
"python"
] | stackoverflow_0001335556_class_dictionary_hash_inheritance_python.txt |
Q:
Python: ZODB file size growing - not updating?
I am using ZODB to store some data that exists in memory for the sake of persistence. If the service with the data in memory every crashes, restarting will load the data from ZODB rather than querying 100s of thousands of rows in a MySQL db.
It seems that every tim... | Python: ZODB file size growing - not updating? | I am using ZODB to store some data that exists in memory for the sake of persistence. If the service with the data in memory every crashes, restarting will load the data from ZODB rather than querying 100s of thousands of rows in a MySQL db.
It seems that every time I save, say 500K of data to my database file, my .... | [
"When the data in ZODB changes, it's appended to the end of the file. Old data is left there. To reduce the filesize, you need to manually \"pack\" the database.\nGoogle came up with this mailing list post.\n",
"Since you asked about another storage system in a comment, you might want to look into SQLite.\nEven... | [
2,
1
] | [] | [] | [
"python",
"zodb"
] | stackoverflow_0001335615_python_zodb.txt |
Q:
Using python scipy.weave inline with ctype variables?
I am trying to pass a ctype variable to inline c code using scipy.weave.inline. One would think this would be simple. Documentation is good when doing it with normal python object types, however, they have a lot more features than I need, and It makes more sens... | Using python scipy.weave inline with ctype variables? | I am trying to pass a ctype variable to inline c code using scipy.weave.inline. One would think this would be simple. Documentation is good when doing it with normal python object types, however, they have a lot more features than I need, and It makes more sense to me to use ctypes when working with C. I am unsure, how... | [
"scipy.weave does not know anything about ctypes. Inputs are restricted to most of the basic builtin types, numpy arrays, wxPython objects, VTK objects, and SWIG wrapped objects. You can add your own converter code, though. There is currently not much documentation on this, but you can look at the SWIG implementati... | [
4
] | [] | [] | [
"inline_code",
"python",
"scipy"
] | stackoverflow_0001137852_inline_code_python_scipy.txt |
Q:
How to find the compiled extensions modules in numpy
I am compiling numpy myself on Windows. The build and install runs fine; but how do I list the currently enabled modules .. and modules that are not made available (due to maybe compilation failure or missing libraries)?
A:
numpy does not have optional compone... | How to find the compiled extensions modules in numpy | I am compiling numpy myself on Windows. The build and install runs fine; but how do I list the currently enabled modules .. and modules that are not made available (due to maybe compilation failure or missing libraries)?
| [
"numpy does not have optional components. Either the build is successful, or it fails. You can run the test suite to see if the build works.\n$ python -c \"import numpy;numpy.test()\"\nRunning unit tests for numpy\nNumPy version 1.4.0.dev\nNumPy is installed in /Users/rkern/svn/numpy/numpy\nPython version 2.5.4 (r2... | [
2
] | [] | [] | [
"numpy",
"python",
"windows"
] | stackoverflow_0001262783_numpy_python_windows.txt |
Q:
How do I set sys.excepthook to invoke pdb globally in python?
From Python docs:
sys.excepthook(type, value, traceback)
This function prints out a given traceback and exception to sys.stderr.
When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, e... | How do I set sys.excepthook to invoke pdb globally in python? | From Python docs:
sys.excepthook(type, value, traceback)
This function prints out a given traceback and exception to sys.stderr.
When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive sessio... | [
"Here's what you need\nhttp://ynniv.com/blog/2007/11/debugging-python.html\nThree ways, the first is simple but crude (Thomas Heller) - add the following to site-packages/sitecustomize.py:\nimport pdb, sys, traceback\ndef info(type, value, tb):\n traceback.print_exception(type, value, tb)\n pdb.pm()\nsys.exce... | [
21,
1,
0
] | [] | [] | [
"configuration",
"debugging",
"pdb",
"python"
] | stackoverflow_0001237379_configuration_debugging_pdb_python.txt |
Q:
Example of subclassing string.Template in Python?
I haven't been able to find a good example of subclassing string.Template in Python, even though I've seen multiple references to doing so in documentation.
Are there any examples of this on the web?
I want to change the $ to be a different character and maybe chan... | Example of subclassing string.Template in Python? | I haven't been able to find a good example of subclassing string.Template in Python, even though I've seen multiple references to doing so in documentation.
Are there any examples of this on the web?
I want to change the $ to be a different character and maybe change the regex for identifiers.
| [
"From python docs:\n\nAdvanced usage: you can derive\n subclasses of Template to customize\n the placeholder syntax, delimiter\n character, or the entire regular\n expression used to parse template\n strings. To do this, you can override\n these class attributes:\n\ndelimiter – This is the literal string desc... | [
31
] | [] | [] | [
"python",
"stringtemplate"
] | stackoverflow_0001336786_python_stringtemplate.txt |
Q:
Python: Alternatives to pickling a module
I am working on my program, GarlicSim, in which a user creates a simulation, then he is able to manipulate it as he desires, and then he can save it to file.
I recently tried implementing the saving feature. The natural thing that occured to me is to pickle the Project obj... | Python: Alternatives to pickling a module | I am working on my program, GarlicSim, in which a user creates a simulation, then he is able to manipulate it as he desires, and then he can save it to file.
I recently tried implementing the saving feature. The natural thing that occured to me is to pickle the Project object, which contains the entire simulation.
Prob... | [
"If the project somehow has a reference to a module with stuff you need, it sounds like you might want to refactor the use of that module into a class within the module. This is often better anyway, because the use of a module for stuff smells of a big fat global. In my experience, such an application structure wil... | [
2,
1
] | [] | [] | [
"module",
"pickle",
"python"
] | stackoverflow_0001336908_module_pickle_python.txt |
Q:
Python dateutil.rrule is incredibly slow
I'm using the python dateutil module for a calendaring application which supports repeating events. I really like the ability to parse ical rrules using the rrulestr() function. Also, using rrule.between() to get dates within a given interval is very fast.
However, as soo... | Python dateutil.rrule is incredibly slow | I'm using the python dateutil module for a calendaring application which supports repeating events. I really like the ability to parse ical rrules using the rrulestr() function. Also, using rrule.between() to get dates within a given interval is very fast.
However, as soon as I try doing any other operations (ie: lis... | [
"My guess is probably not. The last date before datetime.max means you have to calculate all the recurrences up until datetime.max, and that will reasonably be a LOT of recurrences. It might be possible to add shortcuts for some of the simpler recurrences. If it is every year on the same date for example, you don't... | [
4
] | [] | [] | [
"calendar",
"icalendar",
"python",
"python_dateutil"
] | stackoverflow_0001336824_calendar_icalendar_python_python_dateutil.txt |
Q:
Performance - Python vs. C#/C++/C reading char-by-char
So I have these giant XML files (and by giant, I mean like 1.5GB+) and they don't have CRLFs. I'm trying to run a diff-like program to find the differences between these files.
Since I've yet to find a diff program that won't explode due to memory exhaustion, ... | Performance - Python vs. C#/C++/C reading char-by-char | So I have these giant XML files (and by giant, I mean like 1.5GB+) and they don't have CRLFs. I'm trying to run a diff-like program to find the differences between these files.
Since I've yet to find a diff program that won't explode due to memory exhaustion, I've decided the best bet was to add CRLFs after closing tag... | [
"Reading and writing a single character at a time is almost always going to be slow, because disks are block-based devices, rather than character-based devices - it will read a lot more than just the one byte you're after, and the surplus parts need to be discarded.\nTry reading and writing more at a time, say, 819... | [
11,
3,
1,
1,
0,
0,
0,
0
] | [] | [] | [
"c#",
"character",
"performance",
"python"
] | stackoverflow_0001336259_c#_character_performance_python.txt |
Q:
Email integration
I was wondering if someone could help me out. In some web application, the app will send out emails, say when a new message has been posted. Then instead of signing into the application to post a reply you can just simply reply to the email and it will automatically update the web app with your... | Email integration | I was wondering if someone could help me out. In some web application, the app will send out emails, say when a new message has been posted. Then instead of signing into the application to post a reply you can just simply reply to the email and it will automatically update the web app with your response.
My question ... | [
"Generally:\n1) Set up a dedicated email account for the purpose.\n2) Have a programm monitor the mailbox (let's say fetchmail, since that's what I do).\n3) When an email arrives at the account, fetchmail downloads the email, writes it to disk, and calls script or program you have written with the email file as an ... | [
7,
5,
4,
3,
2,
1
] | [] | [] | [
"django",
"email",
"python"
] | stackoverflow_0000640970_django_email_python.txt |
Q:
Python: Set with only existence check?
I have a set of lots of big long strings that I want to do existence lookups for. I don't need the whole string ever to be saved. As far as I can tell, the set() actually stored the string which is eating up a lot of my memory.
Does such a data structure exist?
done = hash_on... | Python: Set with only existence check? | I have a set of lots of big long strings that I want to do existence lookups for. I don't need the whole string ever to be saved. As far as I can tell, the set() actually stored the string which is eating up a lot of my memory.
Does such a data structure exist?
done = hash_only_set()
while len(queue) > 0 :
item = qu... | [
"It's certainly possible to keep a set of only hashes:\ndone = set()\nwhile len(queue) > 0 :\n item = queue.pop()\n h = hash(item)\n if h not in done :\n process(item)\n done.add(h)\n\nNotice that because of hash collisions, there is a chance that you consider an item done even though it isn't. \nIf... | [
10,
4,
4,
3,
2,
0
] | [] | [] | [
"data_structures",
"hash",
"python",
"set"
] | stackoverflow_0001333381_data_structures_hash_python_set.txt |
Q:
What's the fastest way to fixup line-endings for SMTP sending?
I'm coding a email application that produces messages for sending via SMTP. That means I need to change all lone \n and \r characters into the canonical \r\n sequence we all know and love. Here's the code I've got now:
CRLF = '\r\n'
msg = re.sub(r'(?... | What's the fastest way to fixup line-endings for SMTP sending? | I'm coding a email application that produces messages for sending via SMTP. That means I need to change all lone \n and \r characters into the canonical \r\n sequence we all know and love. Here's the code I've got now:
CRLF = '\r\n'
msg = re.sub(r'(?<!\r)\n', CRLF, msg)
msg = re.sub(r'\r(?!\n)', CRLF, msg)
The probl... | [
"This regex helped:\nre.sub(r'\\r\\n|\\r|\\n', '\\r\\n', msg)\nBut this code ended up winning:\nmsg.replace('\\r\\n','\\n').replace('\\r','\\n').replace('\\n','\\r\\n')\nThe original regexes took .6s to convert /usr/share/dict/words from \\n to \\r\\n, the new regex took .3s, and the replace()s took .08s. \n",
"... | [
2,
1,
1,
0
] | [
"Something like this? Compile your regex.\nCRLF = '\\r\\n'\ncr_or_lf_regex = re.compile(r'(?:(?<!\\r)\\n)|(?:\\r(?!\\n))')\n\nThen, when you want to replace stuff use this:\ncr_or_lf_regex.sub(CRLF, msg)\n\nEDIT: Since the above is actually slower, let me take another stab at it.\nlast_chr = ''\n\ndef fix_crlf(inpu... | [
-1
] | [
"performance",
"python",
"smtp"
] | stackoverflow_0001336524_performance_python_smtp.txt |
Q:
SQLAlchemy Inheritance
I'm a bit confused about inheritance under sqlalchemy, to the point where I'm not even sure what type of inheritance (single table, joined table, concrete) I should be using here. I've got a base class with some information that's shared amongst the subclasses, and some data that are complet... | SQLAlchemy Inheritance | I'm a bit confused about inheritance under sqlalchemy, to the point where I'm not even sure what type of inheritance (single table, joined table, concrete) I should be using here. I've got a base class with some information that's shared amongst the subclasses, and some data that are completely separate. Sometimes, I'l... | [
"Choosing how to represent the inheritance is mostly a database design issue. For performance single table inheritance is usually best. From a good database design point of view, joined table inheritance is better. Joined table inheritance enables you to have foreign keys to subclasses enforced by the database, it'... | [
109,
19
] | [] | [] | [
"inheritance",
"python",
"sqlalchemy"
] | stackoverflow_0001337095_inheritance_python_sqlalchemy.txt |
Q:
Python object @property
I'm trying to create a point class which defines a property called "coordinate". However, it's not behaving like I'd expect and I can't figure out why.
class Point:
def __init__(self, coord=None):
self.x = coord[0]
self.y = coord[1]
@property
def coordinate(s... | Python object @property | I'm trying to create a point class which defines a property called "coordinate". However, it's not behaving like I'd expect and I can't figure out why.
class Point:
def __init__(self, coord=None):
self.x = coord[0]
self.y = coord[1]
@property
def coordinate(self):
return (self.x,... | [
"The property method (and by extension, the @property decorator) requires a new-style class i.e. a class that subclasses object.\nFor instance,\nclass Point:\n\nshould be\nclass Point(object):\n\nAlso, the setter attribute (along with the others) was added in Python 2.6.\n",
"It will work if you derive Point from... | [
10,
4
] | [] | [] | [
"new_style_class",
"python"
] | stackoverflow_0001337935_new_style_class_python.txt |
Q:
Can I write Python applications using PyObjC that target NON-jailbroken iPhones?
Is it currently possible to compile Python and PyObjC for the iPhone such that AppStore applications can written in Python?
If not, is this a purely technical issue or a deliberate policy decision by Apple?
A:
No: it's Apple's delib... | Can I write Python applications using PyObjC that target NON-jailbroken iPhones? | Is it currently possible to compile Python and PyObjC for the iPhone such that AppStore applications can written in Python?
If not, is this a purely technical issue or a deliberate policy decision by Apple?
| [
"No: it's Apple's deliberate policy decision (no doubt with some technical underpinnings) to not support interpreters/runtimes on iPhone for most languages -- ObjC (and Javascript within Safari) is what Apple wants you to use, not Python, Java, Ruby, and so forth.\n",
"no, apple strictly forbids running any kind ... | [
1,
0
] | [] | [] | [
"iphone",
"pyobjc",
"python"
] | stackoverflow_0001338095_iphone_pyobjc_python.txt |
Q:
Executing Python Scripts in Android
This link says that Android support Python, Lua and BeanShell Scripts, subsequently for Perl too. If it is so, is it possible for developers to write python scripts and call them in their standard Java based android applications?
A:
I remember reading about this awhile back as... | Executing Python Scripts in Android | This link says that Android support Python, Lua and BeanShell Scripts, subsequently for Perl too. If it is so, is it possible for developers to write python scripts and call them in their standard Java based android applications?
| [
"I remember reading about this awhile back as well.\nIt's not on the android dev site.\nIt's a separate project, android-scripting.\nPython API:\nAPI Reference\nSL4A API Help\n",
"I think I have read somewhere that ASE with Python was a huge library ( several Mo), and so was completely unpractical for a public ap... | [
5,
0
] | [] | [] | [
"android",
"python",
"scripting"
] | stackoverflow_0001326169_android_python_scripting.txt |
Q:
Configure Django project in a subdirectory using mod_python. Admin not working
HI guys. I was trying to configure my django project in a subdirectory of the root, but didn't get things working.(LOcally it works perfect). I followed the django official django documentarion to deploy a project with mod_python. The r... | Configure Django project in a subdirectory using mod_python. Admin not working | HI guys. I was trying to configure my django project in a subdirectory of the root, but didn't get things working.(LOcally it works perfect). I followed the django official django documentarion to deploy a project with mod_python. The real problem is that I am getting "Page not found" errors, whenever I try to go to th... | [
"I'm using mod_wsgi, so I'm not sure if it's all the same. But in my urls.py, I have:\n(r'^admin/(.*)', admin.site.root),\n\nIn my Apache config, I have this:\nAlias /admin/media/ /usr/lib/python2.5/site-packages/django/contrib/admin/media\n\nYour path may vary.\n",
"If your settings.py is correct and has your c... | [
0,
0
] | [] | [] | [
"deployment",
"django",
"mod_python",
"python"
] | stackoverflow_0001338101_deployment_django_mod_python_python.txt |
Q:
How to sort digits in a number?
I'm trying to make an easy script in Python which takes a number and saves in a variable, sorting the digits in ascending and descending orders and saving both in separate variables. Implementing Kaprekar's constant.
It's probably a pretty noobish question. But I'm new to this and I... | How to sort digits in a number? | I'm trying to make an easy script in Python which takes a number and saves in a variable, sorting the digits in ascending and descending orders and saving both in separate variables. Implementing Kaprekar's constant.
It's probably a pretty noobish question. But I'm new to this and I couldn't find anything on Google tha... | [
"Sort the digits in ascending and descending orders:\nascending = \"\".join(sorted(str(number)))\n\ndescending = \"\".join(sorted(str(number), reverse=True))\n\nLike this:\n>>> number = 5896\n>>> ascending = \"\".join(sorted(str(number)))\n>>>\n>>> descending = \"\".join(sorted(str(number), reverse=True))\n>>> asce... | [
19,
4,
4,
1
] | [
"Here's an answer to the title question in Perl, with a bias toward sorting 4-digit numbers for the Kaprekar algorithm. In the example, replace 'shift' with the number to sort. It sorts digits in a 4-digit number with leading 0's ($asc is sorted in ascending order, $dec is descending), and outputs a number with l... | [
-1
] | [
"numbers",
"python"
] | stackoverflow_0001301156_numbers_python.txt |
Q:
BDB Python Interface Error when Reading BDB
bsddb.db.DBInvalidArgError: (22, 'Invalid argument -- /dbs/supermodels.db: unexpected file type or format')
Is this error a result of incompatible BDB versions (1.85 or 3+)? If so, how do I check the versions, trouble-shoot and solve this error?
A:
Yes, this certainly ... | BDB Python Interface Error when Reading BDB | bsddb.db.DBInvalidArgError: (22, 'Invalid argument -- /dbs/supermodels.db: unexpected file type or format')
Is this error a result of incompatible BDB versions (1.85 or 3+)? If so, how do I check the versions, trouble-shoot and solve this error?
| [
"Yes, this certainly could be due to older versions of the db file, but it would help if you posted the code that generated this exception and the full traceback.\nIn the absence of this, are you sure that the database file that you're opening is of the correct type? For example, attempting to open a btree file as ... | [
1
] | [] | [] | [
"berkeley_db",
"python"
] | stackoverflow_0001336617_berkeley_db_python.txt |
Q:
Parameter binding using GQL in Google App Engine
Okay so I have this mode:
class Posts(db.Model):
rand1 = db.FloatProperty()
#other models here
and this controller:
class Random(webapp.RequestHandler):
def get(self):
rand2 = random.random()
posts_query = db.GqlQuery("SELECT * FROM Posts WHER... | Parameter binding using GQL in Google App Engine | Okay so I have this mode:
class Posts(db.Model):
rand1 = db.FloatProperty()
#other models here
and this controller:
class Random(webapp.RequestHandler):
def get(self):
rand2 = random.random()
posts_query = db.GqlQuery("SELECT * FROM Posts WHERE rand1 > :rand2 ORDER BY rand LIMIT 1")
#Assign... | [
"Substitute:\n \"...WHERE rand1 > :rand2 ORDER BY rand LIMIT 1\")\n\nwith:\n \"...WHERE rand1 > :rand2 ORDER BY rand LIMIT 1\", rand2=rand2)\n\nOr\n \"...WHERE rand1 > :1 ORDER BY rand LIMIT 1\", rand2)\n\nSee for more information: \"The Gql query class\"\n The funny thing is that I have just learned this about 2... | [
3
] | [] | [] | [
"binding",
"django",
"google_app_engine",
"gql",
"python"
] | stackoverflow_0001338704_binding_django_google_app_engine_gql_python.txt |
Q:
python variable scope
I have started to learn about python and is currently reading through a script written by someone else. I noticed that globals are scattered throughout the script (and I don't like it).. Besides that, I also noticed that when I have code like this
def some_function():
foo.some_method()
... | python variable scope | I have started to learn about python and is currently reading through a script written by someone else. I noticed that globals are scattered throughout the script (and I don't like it).. Besides that, I also noticed that when I have code like this
def some_function():
foo.some_method()
# some other code
if __n... | [
"That script has really serious issues with style and organization -- for example, if somebody imports it they have to somehow divine the fact that they have to set thescript.foo to an instance of Some_Object before calling some_function... yeurgh!-)\nIt's unfortunate that you're having to learn Python from a badly... | [
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0001338590_python.txt |
Q:
Is it crazy to not rely on a caching system like memcached nowadays ( for dynamic sites )?
I was just reviewing one of my client's applications which uses some old outdated php framework that doesn't rely on caching at all and is pretty much completely database dependent.
I figure I'll just rewrite it from scratch... | Is it crazy to not rely on a caching system like memcached nowadays ( for dynamic sites )? | I was just reviewing one of my client's applications which uses some old outdated php framework that doesn't rely on caching at all and is pretty much completely database dependent.
I figure I'll just rewrite it from scratch because it's really outdated and in this rewrite I want to implement a caching system. It'd be ... | [
"Caching, when it works right (==high hit rate), is one of the few general-purpose techniques that can really help with latency -- the harder part of problems generically describes as \"performance\". You can enhance QPS (queries per second) measures of performance just by throwing more hardware at the problem -- b... | [
10,
6,
3,
0
] | [] | [] | [
"memcached",
"php",
"python",
"scalability"
] | stackoverflow_0001338777_memcached_php_python_scalability.txt |
Q:
What wrong when SimpleXMLRPC and DBusGMainLoop working in the same time
In python I try create a service that maintain calling event between SflPhone(dbus service) and external app, when I start SimpleXMLRPCServer my service no longer response for any calling event, such as on_call_state_changed function was not c... | What wrong when SimpleXMLRPC and DBusGMainLoop working in the same time | In python I try create a service that maintain calling event between SflPhone(dbus service) and external app, when I start SimpleXMLRPCServer my service no longer response for any calling event, such as on_call_state_changed function was not called.
When I comment out thread.start_new_thread(start_server(s,)) everyth... | [
"Try adding after ifmain trick:\ngobject.threads_init()\ndbus.glib.init_threads()\n\n"
] | [
0
] | [] | [] | [
"dbus",
"python",
"sip",
"voip",
"xml_rpc"
] | stackoverflow_0001339003_dbus_python_sip_voip_xml_rpc.txt |
Q:
How to fetch rows from below table using google app engine GQL query (python)?
List_name Email
========== ==================
andrew adam@gmail.com
adam adam@gmail.com
smith adam@gmail.com
john adam@gmail.com
andrew andrew@gmail.com
adam andrew@gmail.com
smith andrew@gm... | How to fetch rows from below table using google app engine GQL query (python)? | List_name Email
========== ==================
andrew adam@gmail.com
adam adam@gmail.com
smith adam@gmail.com
john adam@gmail.com
andrew andrew@gmail.com
adam andrew@gmail.com
smith andrew@gmail.com
john andrew@gmail.com
andrew john@gmail.com
adam john@gma... | [
"If you're accustomed to working with a relational database, Google App Engine can seem unusual. The query syntax is very limited. Instead of putting everything into a simple table and writing complicated queries, you have to put everything into complicated data structures and then write simple queries.\nYou shou... | [
4,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001339346_google_app_engine_python.txt |
Q:
accessing base class primitive type in python
I am trying to derive a class from a python primitive, the float, for the purpose of printing a different repr string when it's printed out.
How do I access the underlying data from the derived class when I do this?
Here's a simplified example of what I am trying to do... | accessing base class primitive type in python | I am trying to derive a class from a python primitive, the float, for the purpose of printing a different repr string when it's printed out.
How do I access the underlying data from the derived class when I do this?
Here's a simplified example of what I am trying to do:
class efloat(float):
def __repr__(self):
... | [
"If you don't override __str__, that will still access the underlying method, so:\nclass efloat(float):\n def __repr__(self):\n return \"here's my number: %s\" % self\n\nwill work. More generally, you could use self+0, self*1, or any other identity manipulation that you did not explicitly override; if you... | [
4,
2
] | [] | [] | [
"class",
"floating_point",
"python"
] | stackoverflow_0001338858_class_floating_point_python.txt |
Q:
Accessing dictionary with class attribute
now I am working with python. So one question about dict ....
suppose I have a dict that
config = {'account_receivable': '4', 'account_payable': '5', 'account_cogs': '8', 'accoun
t_retained_earning': '9', 'account_income': '6', 'account_expense': '31', 'durat
ion': 2, 'fi... | Accessing dictionary with class attribute | now I am working with python. So one question about dict ....
suppose I have a dict that
config = {'account_receivable': '4', 'account_payable': '5', 'account_cogs': '8', 'accoun
t_retained_earning': '9', 'account_income': '6', 'account_expense': '31', 'durat
ion': 2, 'financial_year_month': 9, 'financial_year_day': 1... | [
"For that purpose, lo that many years ago, I invented the simple Bunch idiom; one simple way to implement Bunch is:\nclass Bunch(object):\n def __init__(self, adict):\n self.__dict__.update(adict)\n\nIf config is a dict, you can't use config.account_receivable -- that's absolutely impossible, because a dict doe... | [
13,
7,
3,
2,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0001338714_dictionary_python.txt |
Q:
Python: Persistent shell variables in subprocess
I'm trying to execute a series of commands using Pythons subprocess module, however I need to set shell variables with export before running them. Of course the shell doesn't seem to be persistent so when I run a command later those shell variables are lost.
Is ther... | Python: Persistent shell variables in subprocess | I'm trying to execute a series of commands using Pythons subprocess module, however I need to set shell variables with export before running them. Of course the shell doesn't seem to be persistent so when I run a command later those shell variables are lost.
Is there any way to go about this? I could create a /bin/sh p... | [
"subprocess.Popen takes an optional named argument env that's a dictionary to use as the subprocess's environment (what you're describing as \"shell variables\"). Prepare a dict as you need it (you may start with a copy of os.environ and alter that as you need) and pass it to all the subprocess.Popen calls you perf... | [
13,
5
] | [] | [] | [
"persistent",
"python",
"shell",
"subprocess",
"variables"
] | stackoverflow_0001126116_persistent_python_shell_subprocess_variables.txt |
Q:
Why do I get 'service unavailable' with multiple chat sends when using XMPP?
I have made a simple IM client in both Python and C#, using a few different XMPP libraries for each.
They work very well as simple autoresponders, or trivial bots, but when I turn them into chat rooms (ie, a message gets reflected to many... | Why do I get 'service unavailable' with multiple chat sends when using XMPP? | I have made a simple IM client in both Python and C#, using a few different XMPP libraries for each.
They work very well as simple autoresponders, or trivial bots, but when I turn them into chat rooms (ie, a message gets reflected to many other JIDs), I suddenly start getting 503 service-unavailable responses from the ... | [
"Do you have all people you try to send messages to in your rooster?\nOtherwise GTalk won't allow the message to be sent and instead return Error 503.\nThere was a pidgin bug tracker describing a similar problem:\nPidgin #4236 \nIf you're sure you have all the JIDs in your rooster you should also check how manny me... | [
2,
1
] | [] | [] | [
"c#",
"python",
"xmpp"
] | stackoverflow_0001323693_c#_python_xmpp.txt |
Q:
Attribute Error in Python
I'm trying to add a unittest attribute to an object in Python
class Boy:
def run(self, args):
print("Hello")
class BoyTest(unittest.TestCase)
def test(self)
self.assertEqual('2' , '2')
def self_test():
suite = unittest.TestSuite()
loader = unittest.Tes... | Attribute Error in Python | I'm trying to add a unittest attribute to an object in Python
class Boy:
def run(self, args):
print("Hello")
class BoyTest(unittest.TestCase)
def test(self)
self.assertEqual('2' , '2')
def self_test():
suite = unittest.TestSuite()
loader = unittest.TestLoader()
suite.addTest(loa... | [
"As the argument of loadTestsFromTestCase, you're trying to access Boy.BoyTest, i.e., the BoyTest attribute of class object Boy, which just doesn't exist, as the error msg is telling you. Why don't you just use BoyTest there instead?\n"
] | [
3
] | [
"As Alex has stated you are trying to use BoyTest as an attibute of Boy:\nclass Boy:\n\n def run(self, args):\n print(\"Hello\")\n\nclass BoyTest(unittest.TestCase)\n\n def test(self)\n self.assertEqual('2' , '2')\n\ndef self_test():\n suite = unittest.TestSuite()\n loader = unittest.Test... | [
-1
] | [
"attributeerror",
"python"
] | stackoverflow_0001338847_attributeerror_python.txt |
Q:
Regexp to literally interpret \t as \t and not tab
I'm trying to match a sequence of text with backslashed in it, like a windows path.
Now, when I match with regexp in python, it gets the match, but the module interprets all backslashes followed by a valid escape char (i.e. t) as an escape sequence, which is not w... | Regexp to literally interpret \t as \t and not tab | I'm trying to match a sequence of text with backslashed in it, like a windows path.
Now, when I match with regexp in python, it gets the match, but the module interprets all backslashes followed by a valid escape char (i.e. t) as an escape sequence, which is not what I want.
How do I get it not to do that?
Thanks
/m
ED... | [
"Use double backslashes with r like this\n>>> re.match(r\"\\\\t\", r\"\\t\")\n<_sre.SRE_Match object at 0xb7ce5d78>\n\nFrom python docs:\n\nWhen one wants to match a literal\n backslash, it must be escaped in the\n regular expression. With raw string\n notation, this means r\"\\\". Without\n raw string notation... | [
11,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001340162_python_regex.txt |
Q:
back-to-back histograms in matplotlib
There is a nice function that draws back to back histograms in Matlab. I need to create a similar graph in matplotlib. Can anyone show a working code example?
A:
Thanks to the link pointed by Mark Rushakoff, following is what I finally did
import numpy as np
from matplotlib ... | back-to-back histograms in matplotlib | There is a nice function that draws back to back histograms in Matlab. I need to create a similar graph in matplotlib. Can anyone show a working code example?
| [
"Thanks to the link pointed by Mark Rushakoff, following is what I finally did\nimport numpy as np\nfrom matplotlib import pylab as pl\n\ndataOne = get_data_one()\ndataTwo = get_data_two()\n\nhN = pl.hist(dataTwo, orientation='horizontal', normed=0, rwidth=0.8, label='ONE')\nhS = pl.hist(dataOne, bins=hN[1], orient... | [
6,
2
] | [] | [] | [
"histogram",
"matplotlib",
"python"
] | stackoverflow_0001340338_histogram_matplotlib_python.txt |
Q:
Python equivalent to "php -s"
As you may or may not know, you can generate a color syntax-higlighted HTML file from a PHP source file using php -s.
I know about the syntaxhighlighter that Stackoverflow uses and that's not really what I'm looking for. I'm looking for something will generate HTML output without Jav... | Python equivalent to "php -s" | As you may or may not know, you can generate a color syntax-higlighted HTML file from a PHP source file using php -s.
I know about the syntaxhighlighter that Stackoverflow uses and that's not really what I'm looking for. I'm looking for something will generate HTML output without Javascript.
Does anyone know of someth... | [
"$ pygmentize -O full -O style=native -o test.html test.py\n\nTo install Pygments:\n$ easy_install Pygments\n\nYou can use it as a library.\nfrom pygments import highlight\nfrom pygments.lexers import guess_lexer\nfrom pygments.formatters import HtmlFormatter\n\ncode = '#!/usr/bin/python\\nprint \"Hello World!\"'\n... | [
12,
1,
0,
0
] | [] | [] | [
"php",
"python",
"syntax_highlighting"
] | stackoverflow_0000658939_php_python_syntax_highlighting.txt |
Q:
Should Python unittests be in a separate module?
Is there a consensus about the best place to put Python unittests?
Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (if __name__ == '__main__', etc.)), or is it better to include th... | Should Python unittests be in a separate module? | Is there a consensus about the best place to put Python unittests?
Should the unittests be included within the same module as the functionality being tested (executed when the module is run on its own (if __name__ == '__main__', etc.)), or is it better to include the unittests within different modules?
Perhaps a combin... | [
"YES, do use a separate module.\nIt does not really make sense to use the __main__ trick. Just assume that you have several files in your module, and it does not work anymore, because you don't want to run each source file separately when testing your module.\nAlso, when installing a module, most of the time you do... | [
15,
13,
10,
4,
3,
1,
0
] | [] | [] | [
"python",
"testing",
"unit_testing"
] | stackoverflow_0001340892_python_testing_unit_testing.txt |
Q:
Django equivalent for count and group by
I have a model that looks like this:
class Category(models.Model):
name = models.CharField(max_length=60)
class Item(models.Model):
name = models.CharField(max_length=60)
category = models.ForeignKey(Category)
I want select count (just the count) of items for ... | Django equivalent for count and group by | I have a model that looks like this:
class Category(models.Model):
name = models.CharField(max_length=60)
class Item(models.Model):
name = models.CharField(max_length=60)
category = models.ForeignKey(Category)
I want select count (just the count) of items for each category, so in SQL it would be as simple... | [
"Here, as I just discovered, is how to do this with the Django 1.1 aggregation API:\nfrom django.db.models import Count\ntheanswer = Item.objects.values('category').annotate(Count('category'))\n\n",
"(Update: Full ORM aggregation support is now included in Django 1.1. True to the below warning about using private... | [
136,
58,
58,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000327807_django_python.txt |
Q:
python: dictionaries of lists are somehow coupled
I wrote a small python program to iterate over data file (input_file) and perform calculations. If calculation result reaches certain states (stateA or stateB), information (hits) are extracted from the results. The hits to extract depend on parameters from three p... | python: dictionaries of lists are somehow coupled | I wrote a small python program to iterate over data file (input_file) and perform calculations. If calculation result reaches certain states (stateA or stateB), information (hits) are extracted from the results. The hits to extract depend on parameters from three parameter sets.
I used a dictionary of dictionaries to s... | [
"Your line:\nhits = dict.fromkeys(param_sets, [])\n\nis equivalent to:\nhits = dict()\nonelist = []\nfor k in param_sets:\n hits[k] = onelist\n\nThat is, every entry in hits has as its value the SAME list object, initially empty, no matter what key it has. Remember that assignment does NOT perform implicit copie... | [
8,
4
] | [] | [] | [
"dictionary",
"python",
"variables"
] | stackoverflow_0001341208_dictionary_python_variables.txt |
Q:
Locally Hosted Google App Engine (WebApp Framework / BigTable)
I have been playing with Google App engine a lot lately, from home on personal projects, and I have been really enjoying it. I've converted a few of my coworkers over and we are interested in using GAE for a few of our projects at work.
Our work has to... | Locally Hosted Google App Engine (WebApp Framework / BigTable) | I have been playing with Google App engine a lot lately, from home on personal projects, and I have been really enjoying it. I've converted a few of my coworkers over and we are interested in using GAE for a few of our projects at work.
Our work has to be hosted locally on our own servers. I've done some searching arou... | [
"Webapp is a fine choice for a simple web framework but there are plenty of other simple python web frameworks that have instructions for setting them up in your use case (cherrypy, web.py, etc). Since google developed webapp for gae I don't believe they published instructions for setting it up behind apache.\nBigT... | [
4
] | [] | [] | [
"google_app_engine",
"mod_wsgi",
"python"
] | stackoverflow_0001340887_google_app_engine_mod_wsgi_python.txt |
Q:
Problem with python and __import__
Sorry for the generic title, will change it once I understand the source of my problem
I have the following structure:
foo/
foo/__init__.py
foo/bar/
foo/bar/__init__.py
foo/bar/some_module.py
When I try to import some_module by doing so:
from foo.bar import some_module
it works... | Problem with python and __import__ | Sorry for the generic title, will change it once I understand the source of my problem
I have the following structure:
foo/
foo/__init__.py
foo/bar/
foo/bar/__init__.py
foo/bar/some_module.py
When I try to import some_module by doing so:
from foo.bar import some_module
it works like a charm.
But this is no good for m... | [
"I believe the proper way to do this is:\nmod = __import__('foo.bar', fromlist = ['some_module'])\n\nThis way even the 'foo.bar' part can be changed at runtime. \nAs a result some_modulewill be available as mod.some_module; use getattr if you want it in a separate variable:\nthe_module = getattr(mod, 'some_module')... | [
7,
1,
0
] | [] | [] | [
"import",
"python"
] | stackoverflow_0001342128_import_python.txt |
Q:
Specifying constraints for fmin_cobyla in scipy
I use Python 2.5.
I am passing bounds to the cobyla optimisation:
import numpy
from numpy import asarray
Initial = numpy.asarray [2, 4, 5, 3] # Initial values to start with
#bounding limits (lower,upper) - for visualizing
#bounds = [(1, 5000), (1, 6000), (2... | Specifying constraints for fmin_cobyla in scipy | I use Python 2.5.
I am passing bounds to the cobyla optimisation:
import numpy
from numpy import asarray
Initial = numpy.asarray [2, 4, 5, 3] # Initial values to start with
#bounding limits (lower,upper) - for visualizing
#bounds = [(1, 5000), (1, 6000), (2, 100000), (1, 50000)]
# actual passed bounds
b1 =... | [
"fmin_cobyla() is not an interior point method. That is, it will pass points that are outside of the bounds (\"infeasible points\") to the function during the course of the optmization run.\nOn thing that you will need to fix is that b9 and b10 are not in the form that fmin_cobyla() expects. The bound functions nee... | [
3,
2
] | [] | [] | [
"function",
"lambda",
"python",
"scipy",
"specifications"
] | stackoverflow_0001336777_function_lambda_python_scipy_specifications.txt |
Q:
Slow regex in Python?
I'm trying to match these kinds of strings
{@csm.foo.bar}
without matching any of these
{@csm.foo.bar-@csm.ooga.booga}
{@csm.foo.bar-42}
The regex I use is
r"\{@csm.((?:[a-zA-Z0-9_]+\.?)+)\}"
It gets dog slow if the string contains multiple matches. Why? It runs very fast if I take away th... | Slow regex in Python? | I'm trying to match these kinds of strings
{@csm.foo.bar}
without matching any of these
{@csm.foo.bar-@csm.ooga.booga}
{@csm.foo.bar-42}
The regex I use is
r"\{@csm.((?:[a-zA-Z0-9_]+\.?)+)\}"
It gets dog slow if the string contains multiple matches. Why? It runs very fast if I take away the brace matching, like this... | [
"Can you supply a test case of a string for which the first match is \"dog slow\"? BTW, though I don't know if that matters to performance, there's an imprecision in the RE -- it matches any single character after the {@csm start, not just a dot; maybe a better expression (possibly faster as it doesn't make any dot... | [
4,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001342589_python_regex.txt |
Q:
How can I force subtraction to be signed in Python?
You can skip to the bottom line if you don't care about the background:
I have the following code in Python:
ratio = (point.threshold - self.points[0].value) / (self.points[1].value - self.points[0].value)
Which is giving me wrong values. For instance, for:
thr... | How can I force subtraction to be signed in Python? | You can skip to the bottom line if you don't care about the background:
I have the following code in Python:
ratio = (point.threshold - self.points[0].value) / (self.points[1].value - self.points[0].value)
Which is giving me wrong values. For instance, for:
threshold: 25.0
self.points[0].value: 46
self.points[1].va... | [
"Well, the obvious solution would probably be to cast to floats:\nratio = (float(point.threshold) - float(self.points[0].value)) / (float(self.points[1].value) - float(self.points[0].value))\n\nOr I suppose you could cast to one of the numpy signed types.\n",
"Almost anything but uints will work here, so just cas... | [
2,
2,
0
] | [] | [] | [
"python",
"sign",
"subtraction",
"uint"
] | stackoverflow_0001342782_python_sign_subtraction_uint.txt |
Q:
Python Packages?
Ok, I think whatever I'm doing wrong, it's probably blindingly obvious, but I can't figure it out. I've read and re-read the tutorial section on packages and the only thing I can figure is that this won't work because I'm executing it directly. Here's the directory setup:
eulerproject/
__init__.... | Python Packages? | Ok, I think whatever I'm doing wrong, it's probably blindingly obvious, but I can't figure it out. I've read and re-read the tutorial section on packages and the only thing I can figure is that this won't work because I'm executing it directly. Here's the directory setup:
eulerproject/
__init__.py
euler1.py
euler... | [
"I had the same problem. I now use nose to run my tests, and relative imports are correctly handled.\nYeah, this whole relative import thing is confusing.\n",
"Generally you would have a directory, the name of which is your package name, somewhere on your PYTHONPATH. For example:\neulerproject/\n euler/\n ... | [
10,
8
] | [] | [] | [
"package",
"python",
"unit_testing"
] | stackoverflow_0001342975_package_python_unit_testing.txt |
Q:
Can you really use the Visual Studio 2008 IDE to code in Python?
I have a friend who I am trying to teach how to program. He comes from a very basic PHP background, and for some reason is ANTI C#, I guess because some of his PHP circles condemn anything that comes from Microsoft.
Anyways - I've told him its possib... | Can you really use the Visual Studio 2008 IDE to code in Python? | I have a friend who I am trying to teach how to program. He comes from a very basic PHP background, and for some reason is ANTI C#, I guess because some of his PHP circles condemn anything that comes from Microsoft.
Anyways - I've told him its possible to use either Ruby or Python with the VS2008 IDE, because I've read... | [
"If you want to use Python together with the .NET Common Language Runtime, then you want one of:\n\nPython.NET (extension to vanilla Python that adds .NET support)\nIronPython (re-implementation of Python as a .NET language)\nBoo (Python-like language that compiles down to C#-equivalent MSIL code)\n\nUsing Python i... | [
8,
2,
1,
1,
1,
0
] | [] | [] | [
"ironpython",
"python",
"visual_studio"
] | stackoverflow_0001342377_ironpython_python_visual_studio.txt |
Q:
In Django, how to control which DB connection and cursor a queryset will use
I'm trying to get a queryset to issue its query over a different DB connection, using a different cursor class. Does anyone know if that's possible and if so how it might be done? In psuedo-code:
# setup a new db connection:
db = db... | In Django, how to control which DB connection and cursor a queryset will use | I'm trying to get a queryset to issue its query over a different DB connection, using a different cursor class. Does anyone know if that's possible and if so how it might be done? In psuedo-code:
# setup a new db connection:
db = db_connect(cursorclass=AlternateCursor)
# setup a generic queryset
qset = blah.... | [
"This is possible from Django 1.0 on - the trick is to use a custom manager for your model and replace the manager's connection object. See the code at Eric Florenzano's post at http://www.eflorenzano.com/blog/post/easy-multi-database-support-django/\n"
] | [
3
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0001342594_database_django_python.txt |
Q:
How to make this method non-recursive?
Hey. This example is pretty specific but I think it could apply to a broad range of functions.
It's taken from some online programming contest.
There is a game with a simple winning condition. Draw is not possible. Game cannot go on forever because every move takes you closer... | How to make this method non-recursive? | Hey. This example is pretty specific but I think it could apply to a broad range of functions.
It's taken from some online programming contest.
There is a game with a simple winning condition. Draw is not possible. Game cannot go on forever because every move takes you closer to the terminating condition. The function ... | [
"In general, it is only possible to convert recursive functions into loops when they are primitive-recursive; this basically means that they call themselves only once in the body. Your function calls itself multiple times. Such a function really needs a stack. It is possible to make the stack explicit, e.g. with li... | [
5,
3,
0,
0
] | [] | [] | [
"python",
"recursion",
"refactoring"
] | stackoverflow_0001339215_python_recursion_refactoring.txt |
Q:
Basic tree in Python with a Django QuerySet
Here's where I'm exposed as the fraud of a programmer I am.
I've never created a data tree.
Basically, I have a table with four fields: A, B, C, and D. I need to create a tree of unordered lists based on these fields. Ultimately, it would look something like this:
A1
... | Basic tree in Python with a Django QuerySet | Here's where I'm exposed as the fraud of a programmer I am.
I've never created a data tree.
Basically, I have a table with four fields: A, B, C, and D. I need to create a tree of unordered lists based on these fields. Ultimately, it would look something like this:
A1
B1
C1
D1
D2
C2
D3
D4
B2
C2
D5
D6
C... | [
"I am not sure of your question, is there something specific you are asking?\nHere are a few reusable applications for storing hierarchical data:\n\ndjango-mptt\ndjango-treebeard\n\nWhat's your reasoning behind using the 4 separate fields?\n"
] | [
4
] | [] | [] | [
"django",
"django_queryset",
"iteration",
"python",
"tree"
] | stackoverflow_0001343845_django_django_queryset_iteration_python_tree.txt |
Q:
Condensing code in Python with Mappings
I seem to be using this block of code alot in Python.
if Y is not None:
obj[X][0]=Y
How do I establish a mapping from X=>Y and then iterate through this entire mapping while calling that block of code on X and Y
A:
mapping = {X1: Y1, X2: Y2, X3: Y3}
mapping[X4] = Y4
m... | Condensing code in Python with Mappings | I seem to be using this block of code alot in Python.
if Y is not None:
obj[X][0]=Y
How do I establish a mapping from X=>Y and then iterate through this entire mapping while calling that block of code on X and Y
| [
"mapping = {X1: Y1, X2: Y2, X3: Y3}\nmapping[X4] = Y4\nmapping[X5] = Y5\n\nfor X,Y in mapping.items():\n if Y is not None:\n obj[X][0] = Y\n\n",
"If Y is None, you can do something like:\ndefault_value = 0\nobj[X][0] = Y if not None else default_value\n\n"
] | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0001344208_python.txt |
Q:
How can you read keystrokes when the python program isn't in the foreground?
I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comforta... | How can you read keystrokes when the python program isn't in the foreground? | I'm trying to analyze my keystrokes over the next month and would like to throw together a simple program to do so. I don't want to exactly log the commands but simply generate general statistics on my key presses.
I am the most comfortable coding this in python, but am open to other suggestions. Is this possible, and... | [
"It looks like you need http://patorjk.com/keyboard-layout-analyzer/\nThis handy program will analyze a block of text and tell you how far your fingers had to travel to type it, then recommend your optimal layout.\nTo answer your original question, on Linux you can read from /dev/event* for local keyboard, mouse an... | [
4,
2,
2,
0
] | [] | [] | [
"background",
"keyboard",
"keylogger",
"python"
] | stackoverflow_0001054380_background_keyboard_keylogger_python.txt |
Q:
nose tests of Pylons app with models in init_model?
I have a stock Pylons app created using paster create -t pylons with one controller and matched functional test, added using paster controller, and a SQLAlchemy table and mapped ORM class. The SQLAlchemy stuff is defined in the init_model() function rather than i... | nose tests of Pylons app with models in init_model? | I have a stock Pylons app created using paster create -t pylons with one controller and matched functional test, added using paster controller, and a SQLAlchemy table and mapped ORM class. The SQLAlchemy stuff is defined in the init_model() function rather than in module scope (and needs to be there).
Running python se... | [
"I would try debugging your nosetest run. Why not put:\nimport pdb;pdb.set_trace()\n\nin the init_model() function and see how it is getting invoked more than once.\nWith PDB running you can see the stack trace using the where command:\nw(here)\nPrint a stack trace, with the most recent frame at the bottom.\nAn arr... | [
3
] | [] | [] | [
"nose",
"nosetests",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0001342232_nose_nosetests_pylons_python_sqlalchemy.txt |
Q:
How to find Title case phrases from a passage or bunch of paragraphs
How do I parse sentence case phrases from a passage.
For example from this passage
Conan Doyle said that the character of Holmes was inspired by Dr. Joseph Bell, for whom Doyle had worked as a clerk at the Edinburgh Royal Infirmary. Like Holmes, ... | How to find Title case phrases from a passage or bunch of paragraphs | How do I parse sentence case phrases from a passage.
For example from this passage
Conan Doyle said that the character of Holmes was inspired by Dr. Joseph Bell, for whom Doyle had worked as a clerk at the Edinburgh Royal Infirmary. Like Holmes, Bell was noted for drawing large conclusions from the smallest observation... | [
"This kind of processing can be very tricky. This simple code does almost the right thing:\nfor s in re.finditer(r\"([A-Z][a-z]+[. ]+)+([A-Z][a-z]+)?\", text):\n print s.group(0)\n\nproduces:\nConan Doyle\nHolmes\nDr. Joseph Bell\nDoyle\nEdinburgh Royal Infirmary. Like Holmes\nBell\nMichael Harrison\nEllery Que... | [
5,
2
] | [] | [] | [
"nlp",
"parsing",
"python",
"text_parsing"
] | stackoverflow_0001343479_nlp_parsing_python_text_parsing.txt |
Q:
Replacing leading and trailing hyphens with spaces?
What is the best way to replace each occurrence of a leading or trailing hyphen with a space?
For example, I want
---ab---c-def--
to become
000ab---c-def00
(where the zeros are spaces)
I'm trying to do this in Python, but I can't seem to come up with a regex that... | Replacing leading and trailing hyphens with spaces? | What is the best way to replace each occurrence of a leading or trailing hyphen with a space?
For example, I want
---ab---c-def--
to become
000ab---c-def00
(where the zeros are spaces)
I'm trying to do this in Python, but I can't seem to come up with a regex that will do the substitution. I'm wondering if there is anot... | [
"re.sub(r'^-+|-+$', lambda m: ' '*len(m.group()), '---ab---c-def--')\n\nExplanation: the pattern matches 1 or more leading or trailing dashes; the substitution is best performed by a callable, which receives each match object -- so m.group() is the matched substring -- and returns the string that must replace it (a... | [
5,
3,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0001345025_python_regex.txt |
Q:
How to efficiently determine if webpage comes from a website
I have some unknown webpages and I want to determine which websites they come from. I have example webpages from each website and I assume each website has a distinctive template.
I do not need complete certainty, and don't want to use too much resources... | How to efficiently determine if webpage comes from a website | I have some unknown webpages and I want to determine which websites they come from. I have example webpages from each website and I assume each website has a distinctive template.
I do not need complete certainty, and don't want to use too much resources matching each webpage. So crawling each website for the webpage i... | [
"You could do this via Bayes classification. Feed a few pages from each site into the classifier first, then future pages can be tested against them to see how closely they match.\nBayes classifier library available here: reverend (LGPL)\nSimplified example:\n# initialisation\nfrom reverend.thomas import Bayes\ngue... | [
4,
0
] | [] | [] | [
"dom",
"python",
"web",
"webpage"
] | stackoverflow_0001345341_dom_python_web_webpage.txt |
Q:
What's the most Pythonic way of determining endianness?
I'm trying to find the best way of working out whether the machine my code is running on is big-endian or little-endian. I have a solution that works (although I haven't tested it on a big-endian machine) but it seems a bit clunky:
import struct
little_endian... | What's the most Pythonic way of determining endianness? | I'm trying to find the best way of working out whether the machine my code is running on is big-endian or little-endian. I have a solution that works (although I haven't tested it on a big-endian machine) but it seems a bit clunky:
import struct
little_endian = (struct.pack('@h', 1) == struct.pack('<h', 1))
This is ju... | [
"The answer is in the sys module:\n>>> import sys\n>>> sys.byteorder\n'little'\n\nOf course depending on your machine it may return 'big'. Your method should certainly work too though.\n"
] | [
106
] | [] | [] | [
"endianness",
"python"
] | stackoverflow_0001346034_endianness_python.txt |
Q:
How does python decide whether a parameter is a reference or a value?
In C++, void somefunction(int) passes a value, while void somefunction(int&) passes a reference. In Java, primitives are passed by value, while objects are passed by reference. How does python make this decision?
Edit: Since everything is passed... | How does python decide whether a parameter is a reference or a value? | In C++, void somefunction(int) passes a value, while void somefunction(int&) passes a reference. In Java, primitives are passed by value, while objects are passed by reference. How does python make this decision?
Edit: Since everything is passed by reference, why does this:
def foo(num):
num *= 2
a = 4
foo(a)
pri... | [
"It passes everything by reference. Even when you specify a numeric value, it is a reference against a table containing that value. This is the difference between static and dynamic languages. The type stays with the value, not with the container, and variables are just references towards a \"value space\" where al... | [
11,
9,
3,
3,
1,
1
] | [] | [] | [
"pointers",
"python",
"reference"
] | stackoverflow_0001342953_pointers_python_reference.txt |
Q:
Threaded Django task doesn't automatically handle transactions or db connections?
I've got Django set up to run some recurring tasks in their own threads, and I noticed that they were always leaving behind unfinished database connection processes (pgsql "Idle In Transaction").
I looked through the Postgres logs an... | Threaded Django task doesn't automatically handle transactions or db connections? | I've got Django set up to run some recurring tasks in their own threads, and I noticed that they were always leaving behind unfinished database connection processes (pgsql "Idle In Transaction").
I looked through the Postgres logs and found that the transactions weren't being completed (no ROLLBACK). I tried using the ... | [
"After weeks of testing and reading the Django source code, I've found the answer to my own question:\nTransactions\nDjango's default autocommit behavior still holds true for my threaded function. However, it states in the Django docs:\n\nAs soon as you perform an action that needs to write to the database, Django ... | [
111
] | [] | [] | [
"database",
"django",
"multithreading",
"python",
"transactions"
] | stackoverflow_0001303654_database_django_multithreading_python_transactions.txt |
Q:
How to find out whether computer is connected to internet?
How to find out whether computer is connected to internet in python?
A:
If you have python2.6 you can set a timeout. Otherwise the connection might block for a long time.
try:
urllib2.urlopen("http://example.com", timeout=2)
except urllib2.URLError:
... | How to find out whether computer is connected to internet? | How to find out whether computer is connected to internet in python?
| [
"If you have python2.6 you can set a timeout. Otherwise the connection might block for a long time.\ntry:\n urllib2.urlopen(\"http://example.com\", timeout=2)\nexcept urllib2.URLError:\n # There is no connection\n\n",
"Try\nimport urllib\nfile = urllib.urlopen(\"http://stackoverflow.com/\")\nhtml = file.rea... | [
16,
7
] | [] | [] | [
"internet_connection",
"python"
] | stackoverflow_0001346575_internet_connection_python.txt |
Q:
Haskell equivalent of Python's "Construct"
Construct is a DSL implemented in Python used to describe data structures (binary and textual). Once you have the data structure described, construct can parse and build it for you. Which is good ("DRY", "Declarative", "Denotational-Semantics"...)
Usage example:
# code fr... | Haskell equivalent of Python's "Construct" | Construct is a DSL implemented in Python used to describe data structures (binary and textual). Once you have the data structure described, construct can parse and build it for you. Which is good ("DRY", "Declarative", "Denotational-Semantics"...)
Usage example:
# code from construct.formats.graphics.png
itxt_info = St... | [
"I'd say it depends what you want to do, and if you need to comply with any existing format.\nData.Binary will (surprise!) help you with binary data, both reading and writing.\nYou can either write the code to read/write yourself, or let go of the details and generate the required code for your data structures usin... | [
1,
0
] | [
"I don't know anything about Python or Construct, so this is probably not what you are searching for, but for simple data structures you can always just derive read:\ndata Test a = I Int | S a deriving (Read,Show)\n\nNow, for the expression\nread \"S 123\" :: Test Double\n\nGHCi will emit: S 123.0\nFor anything mor... | [
-1
] | [
"construct",
"dsl",
"haskell",
"parsing",
"python"
] | stackoverflow_0001225053_construct_dsl_haskell_parsing_python.txt |
Q:
command line arg parsing through introspection
I'm developing a management script that does a fairly large amount of work via a plethora of command-line options. The first few iterations of the script have used optparse to collect user input and then just run down the page, testing the value of each option in the ... | command line arg parsing through introspection | I'm developing a management script that does a fairly large amount of work via a plethora of command-line options. The first few iterations of the script have used optparse to collect user input and then just run down the page, testing the value of each option in the appropriate order, and doing the action if necessary... | [
"Don't waste time on \"introspection\". \nEach \"Command\" or \"Option\" is an object with two sets of method functions or attributes.\n\nProvide setup information to optparse.\nActually do the work.\n\nHere's the superclass for all commands\nclass Command( object ):\n name= \"name\"\n def setup_opts( self, ... | [
4,
0
] | [] | [] | [
"command_line",
"parsing",
"python"
] | stackoverflow_0001345448_command_line_parsing_python.txt |
Q:
Nice exception handling when re-trying code
I have some test cases. The test cases rely on data which takes time to compute. To speed up testing, I've cached the data so that it doesn't have to be recomputed.
I now have foo(), which looks at the cached data. I can't tell ahead of time what it will look at, as that... | Nice exception handling when re-trying code | I have some test cases. The test cases rely on data which takes time to compute. To speed up testing, I've cached the data so that it doesn't have to be recomputed.
I now have foo(), which looks at the cached data. I can't tell ahead of time what it will look at, as that depends a lot on the test case.
If a test case f... | [
"I disagree with the key suggestion in the existing answers, which basically boils down to treating exceptions in Python as you would in, say, C++ or Java -- that's NOT the preferred style in Python, where often the good old idea that \"it's better to ask forgiveness than permission\" (attempt an operation and deal... | [
4,
1,
1,
1,
0
] | [] | [] | [
"code_formatting",
"exception",
"exception_handling",
"python"
] | stackoverflow_0001343541_code_formatting_exception_exception_handling_python.txt |
Q:
Is there a FileIO in Python?
I know there is a StringIO stream in Python, but is there such a thing as a file stream in Python? Also is there a better way for me to look up these things? Documentation, etc...
I am trying to pass a "stream" to a "writer" object I made. I was hoping that I could pass a file handle/s... | Is there a FileIO in Python? | I know there is a StringIO stream in Python, but is there such a thing as a file stream in Python? Also is there a better way for me to look up these things? Documentation, etc...
I am trying to pass a "stream" to a "writer" object I made. I was hoping that I could pass a file handle/stream to this writer object.
| [
"I am guessing you are looking for open(). http://docs.python.org/library/functions.html#open\noutfile = open(\"/path/to/file\", \"w\")\n[...]\noutfile.write([...])\n\nDocumentation on all the things you can do with streams (these are called \"file objects\" or \"file-like objects\" in Python): http://docs.python.o... | [
8,
5,
1
] | [] | [] | [
"file_io",
"python",
"stream"
] | stackoverflow_0001343666_file_io_python_stream.txt |
Q:
Use QAction without adding to menu (or toolbar)
I'm trying to develop an application with a very modular approach to commands and thought it would be nice, sind I'm using pyqt, to use QAction's to bind shortcuts to the commands.
However, it seems that actions shortcuts only works when the action is visible in a me... | Use QAction without adding to menu (or toolbar) | I'm trying to develop an application with a very modular approach to commands and thought it would be nice, sind I'm using pyqt, to use QAction's to bind shortcuts to the commands.
However, it seems that actions shortcuts only works when the action is visible in a menu or toolbar. Does anyone know a way to get this act... | [
"You need to add your action to a widget before it will be processed. From the QT documentation for QAction:\n\nActions are added to widgets using\n QWidget::addAction() or\n QGraphicsWidget::addAction(). Note\n that an action must be added to a\n widget before it can be used; this is\n also true when the shor... | [
7
] | [] | [] | [
"pyqt",
"python",
"qt"
] | stackoverflow_0001346964_pyqt_python_qt.txt |
Q:
Django hitting MySQL even after select_related()?
I'm trying to optimize the database calls coming from a fairly small Django app. At current I have a couple of models, Inquiry and InquiryStatus. When selecting all of the records from MySQL, I get a nice JOIN statement on the two tables, followed by many request... | Django hitting MySQL even after select_related()? | I'm trying to optimize the database calls coming from a fairly small Django app. At current I have a couple of models, Inquiry and InquiryStatus. When selecting all of the records from MySQL, I get a nice JOIN statement on the two tables, followed by many requests to the InquiryStatus table. Why is Django still maki... | [
"I believe this has to do with lazy evaluation. Django only hits the DB if and when necessary, not when you invoke models.Inquiry.objects.select_related('status').all()\nhttp://docs.djangoproject.com/en/dev/topics/db/queries/#id3\n",
"The code you've shown shouldn't actually generate any queries at all - QuerySet... | [
0,
0,
0
] | [] | [] | [
"django",
"django_models",
"django_select_related",
"python"
] | stackoverflow_0001344016_django_django_models_django_select_related_python.txt |
Q:
creating class instances from a list
Using python.....I have a list that contain names. I want to use each item in the list to create instances of a class. I can't use these items in their current condition (they're strings). Does anyone know how to do this in a loop.
class trap(movevariables):
def __init__(se... | creating class instances from a list | Using python.....I have a list that contain names. I want to use each item in the list to create instances of a class. I can't use these items in their current condition (they're strings). Does anyone know how to do this in a loop.
class trap(movevariables):
def __init__(self):
movevariables.__init__(self)
... | [
"You could use a dict, like:\nclasses = {\"foo\" : foo, \"bar\" : bar}\n\nthen you could do:\nmyvar = classes[somestring]()\n\nthis way you'll have to initialize and keep the dict, but will have control on which classes can be created.\n",
"The getattr approach seems right, a bit more detail:\ndef forname(modname... | [
2,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001346969_python.txt |
Q:
Moving to Python 2.6.x
My stuff is developed and running on Python 2.5.2
I want to move some code to 3.x, but that isn't feasible because so many of the external packages I use are not there yet. (Like numpy for instance).
So, I'll do the intermediate step and go to 2.6.2.
My question: If an external module ru... | Moving to Python 2.6.x | My stuff is developed and running on Python 2.5.2
I want to move some code to 3.x, but that isn't feasible because so many of the external packages I use are not there yet. (Like numpy for instance).
So, I'll do the intermediate step and go to 2.6.2.
My question: If an external module runs on 2.5.2, but doesn't exp... | [
"Most likely they will work just fine. Some things might cause DeprecationWarnings, for example sha module, but they can be ignored safely. This is my gut feeling, of course you can hit some specific thing causing problems. Anyway, a quick look over these should tell pretty fast whether your code needs work or not:... | [
8,
3,
2,
1
] | [] | [] | [
"python",
"python_2.6"
] | stackoverflow_0001347168_python_python_2.6.txt |
Q:
Generate test coverage information from pyunit unittests?
I have some pyunit unit tests for a simple command line programme I'm writing. Is it possible for me to generate test coverage numbers? I want to see what lines aren't being covered by my tests.
A:
I regularly use Ned Batchelder's coverage.py tool for exa... | Generate test coverage information from pyunit unittests? | I have some pyunit unit tests for a simple command line programme I'm writing. Is it possible for me to generate test coverage numbers? I want to see what lines aren't being covered by my tests.
| [
"I regularly use Ned Batchelder's coverage.py tool for exactly this purpose.\n",
"If you run your tests with testoob you can get a coverage report with --coverage. Can install with easy_install. No changes to your tests necessary:\ntestoob alltests.py --coverage\n\n"
] | [
9,
1
] | [] | [] | [
"code_coverage",
"python",
"python_unittest",
"testing",
"unit_testing"
] | stackoverflow_0001347727_code_coverage_python_python_unittest_testing_unit_testing.txt |
Q:
Improving Python list slicing
I've wondered why extend/append methods of Python don't return a reference to result list.
To build string of all combination of list with last element, I would like to write simple:
for i in range(l, 0, -1):
yield " ".join(src[0:i-1].append(src[-1]))
But I've got: TypeError. Ins... | Improving Python list slicing | I've wondered why extend/append methods of Python don't return a reference to result list.
To build string of all combination of list with last element, I would like to write simple:
for i in range(l, 0, -1):
yield " ".join(src[0:i-1].append(src[-1]))
But I've got: TypeError. Instead following code with intermedia... | [
"The reason mutating methods in Python do NOT return a reference to the object they've mutated can be found in the Command-Query Separation principle (CQS for short). Python does not apply CQS as thoroughly as Meyer's Eiffel language does (since -- as per the Zen of Python, aka import this, \"practicality beats pur... | [
8,
7,
1,
0
] | [
"To operate on the list and then return it, you can use the or construction:\ndef append_and_return(li, x):\n \"\"\"silly example\"\"\"\n return (li.append(x) or li)\n\nHere it is so that X or Y evaluates X, if X is true, returns X, else evaluates and returns Y. X needs to be always negative.\nHowever, if you are... | [
-1
] | [
"list",
"python"
] | stackoverflow_0001347085_list_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.