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: Not able to pass multiple override parameters using nose-testconfig 0.6 plugin in nosetests I am able to override multiple config parameters using the nose-testconfig plugin only if I pass the overriding parameters on the command line, e.g. nosetests -c nose.cfg -s --tc=jack.env1:asl --tc=server2.env2:abc But whe...
Not able to pass multiple override parameters using nose-testconfig 0.6 plugin in nosetests
I am able to override multiple config parameters using the nose-testconfig plugin only if I pass the overriding parameters on the command line, e.g. nosetests -c nose.cfg -s --tc=jack.env1:asl --tc=server2.env2:abc But when I define the same thing inside nose.cfg, than only the value for the last parameter is modified...
[ "Please find my nose.cfg file below:\n[nosetests]\nverbosity=2\n\ntc-file = setup_config.py\n\ntc-format = python\n\nall-modules = True\n\ntc = server2.env2:abc\n\ntc = jack.env1:asl\n\n\nand my config file looks like:\n[server2]\n\nenv2=server2\n\n[jack]\n\nenv1=server1\n\n\nIn the above example only jack.env1:as...
[ 0 ]
[]
[]
[ "nosetests", "python" ]
stackoverflow_0002886590_nosetests_python.txt
Q: Queue remote calls to a Python Twisted perspective broker? The strength of Twisted (for python) is its asynchronous framework (I think). I've written an image processing server that takes requests via Perspective Broker. It works great as long as I feed it less than a couple hundred images at a time. However, some...
Queue remote calls to a Python Twisted perspective broker?
The strength of Twisted (for python) is its asynchronous framework (I think). I've written an image processing server that takes requests via Perspective Broker. It works great as long as I feed it less than a couple hundred images at a time. However, sometimes it gets spiked with hundreds of images at virtually the sa...
[ "One ready-made option that might help with this is twisted.internet.defer.DeferredSemaphore. This is the asynchronous version of the normal (counting) semaphore you might already know if you've done much threaded programming.\nA (counting) semaphore is a lot like a mutex (a lock). But where a mutex can only be a...
[ 29 ]
[ "You might also like the txRDQ (Resizable Dispatch Queue) I wrote. Google it, it's in the tx collection on LaunchPad. Sorry I don't have more time to reply - about to go onstage.\nTerry\n" ]
[ -2 ]
[ "asynchronous", "python", "twisted" ]
stackoverflow_0002861858_asynchronous_python_twisted.txt
Q: What mock object framework should I use when developing in Python on the Google App Engine? I am developing an application on the Google App Engine using Python (and Django, if that matters). Which mock object framework should I help to assist with unit tests? I see there are a number of standalone projects (i.e. ...
What mock object framework should I use when developing in Python on the Google App Engine?
I am developing an application on the Google App Engine using Python (and Django, if that matters). Which mock object framework should I help to assist with unit tests? I see there are a number of standalone projects (i.e. http://python-mock.sourceforge.net), but I'm not sure if there's something built-in that I can us...
[ "We use this mock library extensively and very happy with it. It is small, simple and expressive.\nAnd yes, there is no mock-framework in the standard Python library.\n" ]
[ 4 ]
[]
[]
[ "django", "google_app_engine", "mocking", "python" ]
stackoverflow_0002899303_django_google_app_engine_mocking_python.txt
Q: Python problem with resize animate GIF I'm want to resize animated GIF with save animate. I'm try use PIL and PythonMagickWand (ImageMagick) and with some GIF's get bad frame. When I'm use PIL, it mar frame in read frame. For test, I'm use this code: from PIL import Image im = Image.open('d:/box_opens_closes.g...
Python problem with resize animate GIF
I'm want to resize animated GIF with save animate. I'm try use PIL and PythonMagickWand (ImageMagick) and with some GIF's get bad frame. When I'm use PIL, it mar frame in read frame. For test, I'm use this code: from PIL import Image im = Image.open('d:/box_opens_closes.gif') im.seek(im.tell()+1) im.seek(im.tell()+...
[ "I'm complete this. Must use:\n\nwand2 = MagickCoalesceImages(wand)\nMagickWriteImages(wand2, 'save_path', 1)\n\n" ]
[ 0 ]
[]
[]
[ "animation", "gif", "python", "python_imaging_library" ]
stackoverflow_0002896031_animation_gif_python_python_imaging_library.txt
Q: Getting rid of the encoding in lxml I am trying to print a XML file using lxml and Python. Here is the code: >>> from lxml import etree >>> root = etree.Element('root') >>> child = etree.SubElement(root, 'child') >>> print etree.tostring(root, pretty_print = True, xml_declaration = True, encoding = None) Output: ...
Getting rid of the encoding in lxml
I am trying to print a XML file using lxml and Python. Here is the code: >>> from lxml import etree >>> root = etree.Element('root') >>> child = etree.SubElement(root, 'child') >>> print etree.tostring(root, pretty_print = True, xml_declaration = True, encoding = None) Output: <?xml version='1.0' encoding='ASCII'?> <...
[ "It shouldn't matter what lxml.etree outputs as long as it's valid XML. If you really want to, you can glue strings together:\n'<?xml version=\"1.0\"?>\\n' + etree.tostring(root, pretty_print = True, encoding = 'ASCII')\n\nIt's unclear why you want to remove it, since ultimately XML needs to know what charset it's ...
[ -3 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0002899425_lxml_python.txt
Q: Constructor does weird things with optional parameters Possible Duplicate: least astonishment in python: the mutable default argument I want to understand of the behavior and implications of the python __init__ constructor. It seems like when there is an optional parameter and you try and set an existing object...
Constructor does weird things with optional parameters
Possible Duplicate: least astonishment in python: the mutable default argument I want to understand of the behavior and implications of the python __init__ constructor. It seems like when there is an optional parameter and you try and set an existing object to a new object the optional value of the existing object ...
[ "The problem is, the default value of an optional argument is only a single instance. So for example, if you say def __init__(self, value, c=[]):, that same list [] will be passed into the method each time an optional argument is used by calling code. \nSo basically you should only use immutable date types such as ...
[ 17, 3 ]
[]
[]
[ "constructor", "optional_parameters", "python" ]
stackoverflow_0002899643_constructor_optional_parameters_python.txt
Q: Inlines in Django Admin I have two models, Order and UserProfile. Each Order has a ForeignKey to UserProfile, to associate it with that user. On the django admin page for each Order, I'd like to display the UserProfile associated with it, for easy processing of information. I have tried inlines: class UserInline(...
Inlines in Django Admin
I have two models, Order and UserProfile. Each Order has a ForeignKey to UserProfile, to associate it with that user. On the django admin page for each Order, I'd like to display the UserProfile associated with it, for easy processing of information. I have tried inlines: class UserInline(admin.TabularInline): mod...
[ "How about making the UserProfile read only? Django Foreign Keys Read Only\nThere are other ideas in this post also. \n" ]
[ 1 ]
[]
[]
[ "admin", "django", "inlines", "python" ]
stackoverflow_0002898547_admin_django_inlines_python.txt
Q: Python - Strange Behavior in re.sub Here's the code I'm running: import re FIND_TERM = r'C:\\Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec\.exe' rfind_term = re.compile(FIND_TERM,re.I) REPLACE_TERM = 'C:\\Program Files\\Microsoft SQL Server\\100\\DTS\\Binn\\DTExec.exe' test = r'something C:\Program...
Python - Strange Behavior in re.sub
Here's the code I'm running: import re FIND_TERM = r'C:\\Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\DTExec\.exe' rfind_term = re.compile(FIND_TERM,re.I) REPLACE_TERM = 'C:\\Program Files\\Microsoft SQL Server\\100\\DTS\\Binn\\DTExec.exe' test = r'something C:\Program Files\Microsoft SQL Server\90\DTS\Binn\D...
[ "You're mixing raw ( r'' ) and normal strings.\n>>> FIND_TERM = r'C:\\\\Program Files\\\\Microsoft SQL Server\\\\90\\\\DTS\\\\Binn\\\\DTExec\\.exe'\n>>> REPLACE_TERM = r'C:\\\\Program Files\\\\Microsoft SQL Server\\\\100\\\\DTS\\\\Binn\\\\DTExec.exe' \n>>> rfind_term = re.compile(FIND_TERM,re.I)\n>>> test = r'somet...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002899805_python_regex.txt
Q: cherrypy keeps object between page update i'm writing web-server that responds me with a list of files in some folder: test_folder = 'somefolder' class TestLoader(object): data = [] index = 0 def __init__(self, dir): for sub in os.listdir(dir): self.data.append(sub) class TesterSer...
cherrypy keeps object between page update
i'm writing web-server that responds me with a list of files in some folder: test_folder = 'somefolder' class TestLoader(object): data = [] index = 0 def __init__(self, dir): for sub in os.listdir(dir): self.data.append(sub) class TesterServer(object): @cherrypy.expose def index...
[ "You've made data a class attribute. Assign in __init__() instead.\nself.data = []\n\n" ]
[ 1 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0002900437_cherrypy_python.txt
Q: how to set MATLABPATH in Python and using mlabwrap? I tried to use mlab.path(path,'/my/path') but failed. Got NameError: name 'path' is not defined in python. Anyone has an idea? A: Never mind. I found out how. Use mlab.addpath().
how to set MATLABPATH in Python and using mlabwrap?
I tried to use mlab.path(path,'/my/path') but failed. Got NameError: name 'path' is not defined in python. Anyone has an idea?
[ "Never mind. I found out how. Use mlab.addpath().\n" ]
[ 3 ]
[]
[]
[ "matlab", "mlabwrap", "python" ]
stackoverflow_0002900358_matlab_mlabwrap_python.txt
Q: How to find links and modify an Html using BeautifulSoup in Python Starting from an Html input like this: <p> <a href="http://www.foo.com">this if foo</a> <a href="http://www.bar.com">this if bar</a> </p> using BeautifulSoup, i would like to change this Html in: <p> <a href="http://www.foo.com">this if foo[1]</a>...
How to find links and modify an Html using BeautifulSoup in Python
Starting from an Html input like this: <p> <a href="http://www.foo.com">this if foo</a> <a href="http://www.bar.com">this if bar</a> </p> using BeautifulSoup, i would like to change this Html in: <p> <a href="http://www.foo.com">this if foo[1]</a> <a href="http://www.bar.com">this if bar[2]</a> </p> saving parsed lin...
[ "This should be easy in Beautiful Soup.\nSomething like:\nfrom BeautifulSoup import BeautifulSoup\nfrom BeautifulSoup import Tag\n\ncount = 1\nlinks_dict = {}\nsoup = BeautifulSoup(text)\nfor link_tag in soup.findAll('a'):\n  if link_tag['href'] and len(link_tag['href']) > 0:\n    links_dict[count]  = link_tag['hre...
[ 4 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002900373_beautifulsoup_python.txt
Q: Ctypes "symbol not found" for dynamic library in OSX I have made a C++ library and have built a .dylib dynamic library from it. However when I load it with ctypes, it fails. Something doesn't seem to have linked properly. I have no idea why. The error (The relevant part): cscalelib.setup_framebuffer(flip,surfa...
Ctypes "symbol not found" for dynamic library in OSX
I have made a C++ library and have built a .dylib dynamic library from it. However when I load it with ctypes, it fails. Something doesn't seem to have linked properly. I have no idea why. The error (The relevant part): cscalelib.setup_framebuffer(flip,surface.frame_buffer,surface.texture,surface._scale[0],surface....
[ "The problem is most likely the fact that you are using C++, and hence the function name will be mangled and use C++ calling conventions. If you declare the function with extern \"C\" then it should be exported in such a way as to callable from C code (and from Python's CTypes module).\n" ]
[ 3 ]
[]
[]
[ "c++", "ctypes", "g++", "linker", "python" ]
stackoverflow_0002900512_c++_ctypes_g++_linker_python.txt
Q: File Sharing Site in Python I wanted to design a simple site where one person can upload a file, and pass off the random webaddress to someone, who can then download it. At this point, I have a webpage where someone can successfully upload a file which gets stored under /files/ on my webserver. The python script a...
File Sharing Site in Python
I wanted to design a simple site where one person can upload a file, and pass off the random webaddress to someone, who can then download it. At this point, I have a webpage where someone can successfully upload a file which gets stored under /files/ on my webserver. The python script also generates a unique, random 5 ...
[ "How do you serve the file-upload page, and how do you let your users upload files?\nIf you are using Python's built-in HTTP server modules you shouldn't have any problems.\nAnyway, here's how the file serving part is done using Python's built-in modules (just the basic idea).\nRegarding your second question, if yo...
[ 2, 0 ]
[]
[]
[ "cgi", "file_upload", "python" ]
stackoverflow_0002900514_cgi_file_upload_python.txt
Q: running a python script where dependencies are not avail: distributed computing I have access to a grid (running condor) that would (potentially) allow to very substantially reduce how long by nltk based nlp tasks take. unfortunately, i dont have root access on the cluster so cannot install new packages, only run ...
running a python script where dependencies are not avail: distributed computing
I have access to a grid (running condor) that would (potentially) allow to very substantially reduce how long by nltk based nlp tasks take. unfortunately, i dont have root access on the cluster so cannot install new packages, only run whatever is available on the linux boxes. python is of course available, but nltk isn...
[ "If you can get a standard user account, you could use virtualenv to create a sandbox in that user-account, where you can install nltk.\n" ]
[ 2 ]
[]
[]
[ "distributed", "python" ]
stackoverflow_0002900660_distributed_python.txt
Q: How do I encode Unicode strings using pyodbc to save to a SAS dataset? I'm using Python to read and write SAS datasets, using pyodbc and the SAS ODBC drivers. I can load the data perfectly well, but when I save the data, using something like: cursor.execute('insert into dataset.test VALUES (?)', u'testing') ... ...
How do I encode Unicode strings using pyodbc to save to a SAS dataset?
I'm using Python to read and write SAS datasets, using pyodbc and the SAS ODBC drivers. I can load the data perfectly well, but when I save the data, using something like: cursor.execute('insert into dataset.test VALUES (?)', u'testing') ... I get a pyodbc.Error: ('HY004', '[HY004] [Microsoft][ODBC Driver Manager] SQ...
[ "Do you know what character encoding your database is expecting? If so, you could try encoding your Unicode string before executing the query. So if your database is expecting utf-8 strings, you could try something like:\nencoding = 'utf-8' # or latin1 or cp1252 or something\ns = u'testing'.encode(encoding)\ncurs...
[ 1, 0 ]
[]
[]
[ "odbc", "pyodbc", "python", "sas" ]
stackoverflow_0002900214_odbc_pyodbc_python_sas.txt
Q: speed up calling lot of entities, and getting unique values, google app engine python OK this is a 2 part question, I've seen and searched for several methods to get a list of unique values for a class and haven't been practically happy with any method so far. So anyone have a simple example code of getting unique...
speed up calling lot of entities, and getting unique values, google app engine python
OK this is a 2 part question, I've seen and searched for several methods to get a list of unique values for a class and haven't been practically happy with any method so far. So anyone have a simple example code of getting unique values for instance for this code. Here is my super slow example. class LinkRating2(db.Mo...
[ "1) One trick to make this query fast is to denormalize your data. Specifically, create another model which simply stores a link as the key. Then you can get a list of unique links by simply reading everything in that table. Assuming that you have many LinkRating2 entities for each link, then this will save you ...
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002900362_google_app_engine_python.txt
Q: manage.py runserver throws an ImportError with my appname, MacPorts issue on OSX? I've been developing a Django app for weeks locally on OSX 10.6.3. Recently, I rebooted my machine and went to start my development environment up. Here's the error: cm:myApp cm$ python manage.py runserver Traceback (most recent c...
manage.py runserver throws an ImportError with my appname, MacPorts issue on OSX?
I've been developing a Django app for weeks locally on OSX 10.6.3. Recently, I rebooted my machine and went to start my development environment up. Here's the error: cm:myApp cm$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 11, in execute_manager(settings) File "/Libr...
[ "To tell where you're currently running Django from, open up a Python shell and do:\nimport django\nprint django.__path__\n\nwhich should show you the path to the Django directory.\nYou might also want to do this from with the Python shell:\nimport sys\nprint sys.path\n\nThis should show you all the directories on ...
[ 0, 0 ]
[]
[]
[ "django", "macos", "python" ]
stackoverflow_0002894344_django_macos_python.txt
Q: Best practice for string substitution with gettext using Python Looking for best practice advice on what string substitution technique to use when using gettext(). Or do all techniques apply equally? I can think of at least 3 string techniques: 1) Classic "%" based formatting: "My name is %(name)s" % locals() 2) ....
Best practice for string substitution with gettext using Python
Looking for best practice advice on what string substitution technique to use when using gettext(). Or do all techniques apply equally? I can think of at least 3 string techniques: 1) Classic "%" based formatting: "My name is %(name)s" % locals() 2) .format() based formatting: "My name is {name}".format( locals() ) 3) ...
[ "Actually I would prefer to get an exception during my tests, to fix the error as soon as possible -- \"errors should not pass silently\". So I consider that approach (2) is the best one in modern Python (which supports the readable and flexible format), and approach (1) a probably inevitable fall-back if you're s...
[ 3, 2 ]
[]
[]
[ "gettext", "python", "string", "string_formatting" ]
stackoverflow_0002901082_gettext_python_string_string_formatting.txt
Q: In Python, can an object have another object as an attribute? In Python, can an object have another object as an attribute? For example, can a class called car have a class called tire as an attribute? A: Do you mean a class tire or an instance of class tire? It can have both although the latter is probably mor...
In Python, can an object have another object as an attribute?
In Python, can an object have another object as an attribute? For example, can a class called car have a class called tire as an attribute?
[ "Do you mean a class tire or an instance of class tire? It can have both although the latter is probably more useful. If you're looking for an object of class Mary to has-a object of type Fred you'd want the classinst variety of assignment: \nPython 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n>>> class Fred(object)...
[ 3, 2, 2, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002900821_oop_python.txt
Q: regex numeric data processing: match a series of numbers greater than X Say I have some data like this: number_stream = [0,0,0,7,8,0,0,2,5,6,10,11,10,13,5,0,1,0,...] I want to process it looking for "bumps" that meet a certain pattern. Imagine I have my own customized regex language for working on numbers, where ...
regex numeric data processing: match a series of numbers greater than X
Say I have some data like this: number_stream = [0,0,0,7,8,0,0,2,5,6,10,11,10,13,5,0,1,0,...] I want to process it looking for "bumps" that meet a certain pattern. Imagine I have my own customized regex language for working on numbers, where [[ >=5 ]] represents any number >= 5. I want to capture this case: ([[ >=5 ]]...
[ "State machines (enriched with quite a few extras, since regexes can match a broader range of languages than FSMs can) are a typical approach to implementing regular expression engines, so why shouldn't similar approaches emerge in looking for good implementations of your desired \"regex-like\" constructs?\nIndeed,...
[ 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002901101_python_regex.txt
Q: is there a facebook user login framework for gae I want to enable someone login using facebook, Is there a framework that you have used to do this? Thanks A: Coincidentally, I gave an answer to a similar question just a couple of hours ago. Please use Rpx, which requires minimal work from your part. how to make...
is there a facebook user login framework for gae
I want to enable someone login using facebook, Is there a framework that you have used to do this? Thanks
[ "Coincidentally, I gave an answer to a similar question just a couple of hours ago. Please use Rpx, which requires minimal work from your part.\nhow to make it easy for users to register at my site?\n" ]
[ 1 ]
[]
[]
[ "facebook", "google_app_engine", "python" ]
stackoverflow_0002901397_facebook_google_app_engine_python.txt
Q: The "correct" way to define an exception in Python without PyLint complaining I'm trying to define my own (very simple) exception class in Python 2.6, but no matter how I do it I get some warning. First, the simplest way: class MyException(Exception): pass This works, but prints out a warning at runtime: Depr...
The "correct" way to define an exception in Python without PyLint complaining
I'm trying to define my own (very simple) exception class in Python 2.6, but no matter how I do it I get some warning. First, the simplest way: class MyException(Exception): pass This works, but prints out a warning at runtime: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 OK, so t...
[ "When you call super, you need the subclass/derived class as the first argument, not the main/base class.\nFrom the Python online documentation:\nclass C(B):\n def method(self, arg):\n super(C, self).method(arg)\n\nSo your exception would be defined as follows:\nclass MyException(Exception):\n def __in...
[ 44, 7, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0002901000_exception_python.txt
Q: Multiple python scripts sending messages to a single central script I have a number of scripts written in Python 2.6 that can be run arbitrarily. I would like to have a single central script that collects the output and displays it in a single log. Ideally it would satisfy these requirements: Every script sends i...
Multiple python scripts sending messages to a single central script
I have a number of scripts written in Python 2.6 that can be run arbitrarily. I would like to have a single central script that collects the output and displays it in a single log. Ideally it would satisfy these requirements: Every script sends its messages to the same "receiver" for display. If the receiver is not ru...
[ "I'd consider using logging.handlers.SocketHandler for the message passing parts of this, it sounds like you have a logging type use case in mind already.\nThe standard libraries logging facilities are very flexible and configuration driven so you should be able to adapt them to your requirements.\nThis doesn't han...
[ 5, 1, 0 ]
[]
[]
[ "interprocess", "multiprocessing", "python" ]
stackoverflow_0002853682_interprocess_multiprocessing_python.txt
Q: Python DictReader - Skipping rows with missing columns? I have a Excel .CSV file I'm attempting to read in with DictReader. All seems to be well, except it seems to omit rows, specifically those with missing columns. Our input looks like: mail,givenName,sn,lorem,ipsum,dolor,telephoneNumber ian.bay@blah.com,ian,bay...
Python DictReader - Skipping rows with missing columns?
I have a Excel .CSV file I'm attempting to read in with DictReader. All seems to be well, except it seems to omit rows, specifically those with missing columns. Our input looks like: mail,givenName,sn,lorem,ipsum,dolor,telephoneNumber ian.bay@blah.com,ian,bay,3424,8403,2535,+65(2)34523534545 mike.gibson@blah.com,mike,g...
[ "Can't reproduce your problem -- when I save that data and then assign list(gd_extract), I see:\n[{'telephoneNumber': '+65(2)34523534545', 'ipsum': '8403', 'sn': 'bay', 'dolor': '2535', 'mail': 'ian.bay@blah.com', 'givenName': 'ian', 'lorem': '3424'}, {'telephoneNumber': '+65(2)34523534545', 'ipsum': '8403', 'sn': ...
[ 1, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0002901422_csv_python.txt
Q: Difficulty using stackless python, cannot write to a dict I have simple map-reduce type algorithm, which I want to implement in python and make use of multiple cores. I read somewhere that threads using native thread module in 2.6 dont make use of multiple cores. is that true? I even implemented it using stackless...
Difficulty using stackless python, cannot write to a dict
I have simple map-reduce type algorithm, which I want to implement in python and make use of multiple cores. I read somewhere that threads using native thread module in 2.6 dont make use of multiple cores. is that true? I even implemented it using stackless python however i am getting into weird errors [Update: a quic...
[ "Use the multiprocessing module of the standard library -- it mimics the interface of the threading module (to ease porting of existing multithreaded code) and can fully use all the cores you have. threading and stackless are both single-core (and indeed, stackless is non-preemptive, so programming for it is quite...
[ 1 ]
[]
[]
[ "multithreading", "python", "python_stackless", "stackless" ]
stackoverflow_0002901633_multithreading_python_python_stackless_stackless.txt
Q: Confusion Matrix with number of classified/misclassified instances on it (Python/Matplotlib) I am plotting a confusion matrix with matplotlib with the following code: from numpy import * import matplotlib.pyplot as plt from pylab import * conf_arr = [[33,2,0,0,0,0,0,0,0,1,3], [3,31,0,0,0,0,0,0,0,0,0], [0,4,41,0,0...
Confusion Matrix with number of classified/misclassified instances on it (Python/Matplotlib)
I am plotting a confusion matrix with matplotlib with the following code: from numpy import * import matplotlib.pyplot as plt from pylab import * conf_arr = [[33,2,0,0,0,0,0,0,0,1,3], [3,31,0,0,0,0,0,0,0,0,0], [0,4,41,0,0,0,0,0,0,0,1], [0,1,0,30,0,6,0,0,0,0,1], [0,0,0,0,38,10,0,0,0,0,0], [0,0,0,3,1,39,0,0,0,0,4], [0,2...
[ "You can use text to put arbitrary text in your plot. For example, inserting the following lines into your code will write the numbers (note the first and last lines are from your code to show you where to insert my lines):\nres = ax.imshow(array(norm_conf), cmap=cm.jet, interpolation='nearest')\nfor i, cas in enu...
[ 10, 1 ]
[]
[]
[ "confusion_matrix", "matplotlib", "python" ]
stackoverflow_0002897826_confusion_matrix_matplotlib_python.txt
Q: Do you have suggestions for these assembly mnemonics? Last semester in college, my teacher in the Computer Languages class taught us the esoteric language named Whitespace. In the interest of learning the language better with a very busy schedule (midterms), I wrote an interpreter and assembler in Python. An assem...
Do you have suggestions for these assembly mnemonics?
Last semester in college, my teacher in the Computer Languages class taught us the esoteric language named Whitespace. In the interest of learning the language better with a very busy schedule (midterms), I wrote an interpreter and assembler in Python. An assembly language was designed to facilitate writing programs ea...
[ "I think the first change I'd propose is changing hold and drop to push and pop respectively.\nThen maybe I'd rename copy to dup (I think that's the most common name for this operation in stack oriented languages).\nI'm a little puzzled why often you have short one word explanations that are different to the mnemon...
[ 4, 3, 1 ]
[]
[]
[ "assembly", "esoteric_languages", "mnemonics", "python", "whitespace" ]
stackoverflow_0002901274_assembly_esoteric_languages_mnemonics_python_whitespace.txt
Q: What's the best way to send user-inputted text via AJAX to Google App Engine? I'm developing in Google App Engine (python sdk) and I want to use jQuery to send an Ajax request to store an answer to a question. What is the best way to send this data to the server? Currently I have: function storeItem(question_id) ...
What's the best way to send user-inputted text via AJAX to Google App Engine?
I'm developing in Google App Engine (python sdk) and I want to use jQuery to send an Ajax request to store an answer to a question. What is the best way to send this data to the server? Currently I have: function storeItem(question_id) { var answerInputControl = ".input_answer_"+question_id; var answer...
[ "The data in your ajax call must include all the data you want to send -- posting a few hundred characters is absolutely no problem and it's most definitely the recommended approach.\nDo not use a GET in lieu of POST -- that (which I suspect is what you mean by \"send as a query string\") would only buy you trouble...
[ 2, 1 ]
[]
[]
[ "ajax", "google_app_engine", "jquery", "python" ]
stackoverflow_0002901793_ajax_google_app_engine_jquery_python.txt
Q: Internal Server Error with mod_wsgi [django] on windows xp when i run development server it works very well, even an empty project runing in mod_wsgi i have no problem but when i want to put my own project i get an Internal Server Error (500) in my apache conf i put WSGIScriptAlias /codevents C:/django/apache/COD...
Internal Server Error with mod_wsgi [django] on windows xp
when i run development server it works very well, even an empty project runing in mod_wsgi i have no problem but when i want to put my own project i get an Internal Server Error (500) in my apache conf i put WSGIScriptAlias /codevents C:/django/apache/CODEvents.wsgi <Directory "C:/django/apache"> Order allow,deny All...
[ "The error says that Python module for PostgreSQL client isn't found or failed to import. Where did you install it? Are the files accessible by Apache service, which runs as a distinct user to yourself?\n", "Well in fact my problem was pyscopg2 windows version, i was using the latest (2.2.1) and i just downgrade ...
[ 1, 0 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0002901631_apache_django_mod_wsgi_python.txt
Q: programs hangs during socket interaction I have two programs, sendfile.py and recvfile.py that are supposed to interact to send a file across the network. They communicate over TCP sockets. The communication is supposed to go something like this: sender =====filename=====> receiver sender <===== 'ok' ======= rece...
programs hangs during socket interaction
I have two programs, sendfile.py and recvfile.py that are supposed to interact to send a file across the network. They communicate over TCP sockets. The communication is supposed to go something like this: sender =====filename=====> receiver sender <===== 'ok' ======= receiver or sender <===== 'no' ====...
[ "With blocking sockets, which are the default and I assume are what you're using (can't be sure since you're using a mysterious module jmm_sockets), the recv method is blocking -- it will not return an empty string when it has \"nothing more to return for the moment\", as you seem to assume.\nYou could work around ...
[ 3, 2 ]
[]
[]
[ "communication_protocol", "network_programming", "python", "sockets" ]
stackoverflow_0002901350_communication_protocol_network_programming_python_sockets.txt
Q: python read utf8 text file problem I have a problem with python about reading and print utf8 text file. I have a test.txt in utf8 encoding without BOM. This file has two characters in it: 大声 The first character "大" is Chinese and the second "声" is Japanese. Now, When I use Ulipad (a python editor) to run the foll...
python read utf8 text file problem
I have a problem with python about reading and print utf8 text file. I have a test.txt in utf8 encoding without BOM. This file has two characters in it: 大声 The first character "大" is Chinese and the second "声" is Japanese. Now, When I use Ulipad (a python editor) to run the following code to read the txt file, and pri...
[ "You get the error when you are printing because:\n(1) Ulipad is printing to sys.stdout which is the stdout of the legacy MS-DOS Command Prompt window.\n(2) Your traditional chinese Windows XP uses cp950 encoding, which is big5 plus Microsoftian fiddling.\n(3) You say your 2nd character is Japanese by which you pro...
[ 7, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0002896786_python_unicode.txt
Q: Python doctests / sphinx : style guide, how to use those and have a readable code? I love doctests, it is the only testing framwork I use, because it is so quick to write, and because used with sphinx it makes such great documentations with almost no effort... However, very often, I end-up doing things like this :...
Python doctests / sphinx : style guide, how to use those and have a readable code?
I love doctests, it is the only testing framwork I use, because it is so quick to write, and because used with sphinx it makes such great documentations with almost no effort... However, very often, I end-up doing things like this : """ Descriptions ============= bla bla bla ... >>> test 1 bla bla bla + tests...
[ "I think there are two sorts of doctest.\n\nYou can put something in the docstring for the function, but if so keep it short and simple.\nThe other option is full documentation/tutorial, and I do that as a separate file.\n\nUnlike ordinary documentation, the beauty of doctesting is that you can be sure they are goi...
[ 3 ]
[]
[]
[ "doctest", "python", "python_sphinx", "readability" ]
stackoverflow_0002902476_doctest_python_python_sphinx_readability.txt
Q: Using Memcached in Python/Django - questions I am starting use Memcached to make my website faster. For constant data in my database I use this: from django.core.cache import cache cache_key = 'regions' regions = cache.get(cache_key) if result is None: """Not Found in Cache""" regions = Regions.obj...
Using Memcached in Python/Django - questions
I am starting use Memcached to make my website faster. For constant data in my database I use this: from django.core.cache import cache cache_key = 'regions' regions = cache.get(cache_key) if result is None: """Not Found in Cache""" regions = Regions.objects.all() cache.set(cache_key, regio...
[ "For second question (about django-memcached-0.1.2 status):\nhttp://effbot.org/zone/django-memcached-view.htm#more-statistics\nhttp://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt\n" ]
[ 1 ]
[]
[]
[ "database", "django", "memcached", "python", "templates" ]
stackoverflow_0002899178_database_django_memcached_python_templates.txt
Q: Doing a count over a filter query efficiently in django Django newbie here, I need to do a count over a certain filter in a django model. If I do it like so: my_model.objects.filter(...).count() I'm guessing it does the SQL query that retrieves all the rows and only afterwards does the count. To my knowledge it's ...
Doing a count over a filter query efficiently in django
Django newbie here, I need to do a count over a certain filter in a django model. If I do it like so: my_model.objects.filter(...).count() I'm guessing it does the SQL query that retrieves all the rows and only afterwards does the count. To my knowledge it's much more efficient to do the count without retrieving those ...
[ "\nI'm guessing it does the SQL query that retrieves all the rows and only afterwards does the count\n\nThis is wrong assumption. From Django query set API reference for count()\n\ncount() performs a SELECT COUNT(*) behind the scenes\n\nIn general, QuerySets are lazy -- the act of creating a QuerySet doesn't involv...
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002903047_django_django_models_python.txt
Q: django sync db question In django models say this model exist in details/models.py class OccDetails(models.Model): title = models.CharField(max_length = 255) occ = models.ForeignKey(Occ) So when sync db is made the following fields get created and later to this of two more fields are added and ...
django sync db question
In django models say this model exist in details/models.py class OccDetails(models.Model): title = models.CharField(max_length = 255) occ = models.ForeignKey(Occ) So when sync db is made the following fields get created and later to this of two more fields are added and sync db is made the new field...
[ "\nsyncdb creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created. \nSyncdb will not alter existing tables\nsyncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class af...
[ 7, 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002902800_django_django_models_python.txt
Q: python private attribute class A(): def __init__(self): self.__var = 5 def get_var(self): return self.__var def set_var(self, value): self.__var = value var = property(get_var, set_var) a = A() a.var = 10 print a.var == a._A__var Can anyone explain why result is False?...
python private attribute
class A(): def __init__(self): self.__var = 5 def get_var(self): return self.__var def set_var(self, value): self.__var = value var = property(get_var, set_var) a = A() a.var = 10 print a.var == a._A__var Can anyone explain why result is False?
[ "The property decorator only works on new-style classes. In Python 2.x, you have to extend the object class:\nclass A(object):\n\n def __init__(self):\n self.__var = 5\n\n def get_var(self):\n return self.__var\n\n def set_var(self, value):\n self.__var = value\n\n var = property(ge...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0002903217_python.txt
Q: Base class deleted before subclass during python __del__ processing Context I am aware that if I ask a question about Python destructors, the standard argument will be to use contexts instead. Let me start by explaining why I am not doing that. I am writing a subclass to logging.Handler. When an instance is closed...
Base class deleted before subclass during python __del__ processing
Context I am aware that if I ask a question about Python destructors, the standard argument will be to use contexts instead. Let me start by explaining why I am not doing that. I am writing a subclass to logging.Handler. When an instance is closed, it posts a sentinel value to a Queue.Queue. If it doesn't, a second thr...
[ "Your code is slightly misleading, I tried it and it failed just as you described. But then I wrote something like this:\nimport threading\n\nclass Base( object ):\n def __del__(self):\n print \"Base class cleaning up.\"\n\nclass Sub(Base):\n def __del__(self):\n print \"Sub-class cleaning up.\"...
[ 2, 1 ]
[]
[]
[ "destructor", "python" ]
stackoverflow_0002902853_destructor_python.txt
Q: Checking for membership inside nested dict This is a followup questions to this one: Python DictReader - Skipping rows with missing columns? Turns out I was being silly, and using the wrong ID field. I'm using Python 3.x here, btw. I have a dict of employees, indexed by a string, "directory_id". Each value is a ne...
Checking for membership inside nested dict
This is a followup questions to this one: Python DictReader - Skipping rows with missing columns? Turns out I was being silly, and using the wrong ID field. I'm using Python 3.x here, btw. I have a dict of employees, indexed by a string, "directory_id". Each value is a nested dict with employee attributes (phone number...
[ "You probably will need to do some iteration to get the data. I assume you don't want an extra dict that can get out of date, so it won't be worth it trying to store everything keyed on internal ids.\nTry this on for size:\ndef lookup_supervisor(manager_internal_id, employees):\n if manager_internal_id is not No...
[ 2, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002901872_dictionary_python.txt
Q: How would you solve this graph theory handshake problem in python? I graduated college last year with a degree in Psychology, but I also took a lot of math for fun. I recently got the book "Introductory Graph Theory" by Gary Chartrand to brush up on my math and have some fun. Here is an exercise from the book that...
How would you solve this graph theory handshake problem in python?
I graduated college last year with a degree in Psychology, but I also took a lot of math for fun. I recently got the book "Introductory Graph Theory" by Gary Chartrand to brush up on my math and have some fun. Here is an exercise from the book that I'm finding particularly befuddling: Suppose you and your husband atte...
[ "I think this adjacency list represents a solution:\n1 -> {}\n2 -> {3, 4, 5, 6, 7, 8}\n3 -> {2, 5, 6, 7, 8}\n4 -> {2}\n5 -> {2, 3, 7, 8}\n6 -> {2, 3}\n7 -> {2, 3, 5}\n8 -> {2, 3, 5}\nNote that each even vertex is married to the vertex one less than itself. You are 8.\nI kind of intuited the solution. Thou...
[ 1, 1 ]
[]
[]
[ "discrete_mathematics", "graph_theory", "math", "python" ]
stackoverflow_0002902660_discrete_mathematics_graph_theory_math_python.txt
Q: KeyError this says that key(partner) is not in dict? I am trying to make an chat application using python and django. I almost complete it and its working fine for 8-10 minutes when two persons are chatting after that certain time it shows an error. here is the traceback : - Traceback (most recent call last): ...
KeyError this says that key(partner) is not in dict?
I am trying to make an chat application using python and django. I almost complete it and its working fine for 8-10 minutes when two persons are chatting after that certain time it shows an error. here is the traceback : - Traceback (most recent call last): File "\Django_chat\django_chat\chat\views.py", line 55, in...
[ "I assume that the user's session got timed-out and hence the request.session doesn't have partner or uid values in it. \nSessions get timed out based on the (lack of) activity on them. Reading a session is not considered activity for expiration purposes. Session expiration is computed from the last time the sessio...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002903329_django_python.txt
Q: An unhandled exception was thrown by the application I've created my new site using DjANGO AT FIRST Everything is okay startapp,syncdb......Etc but the problems its this massage Unhandled Exception An unhandled exception was thrown by the application. you can see http://www.daqiqten.com/ this is my index.fsgi and...
An unhandled exception was thrown by the application
I've created my new site using DjANGO AT FIRST Everything is okay startapp,syncdb......Etc but the problems its this massage Unhandled Exception An unhandled exception was thrown by the application. you can see http://www.daqiqten.com/ this is my index.fsgi and .htacces index.fcgi #!/usr/bin/python import sys, os # A...
[ "Do you have 'DEBUG' turned on in your app's settings? Maybe you will get some more information about the Exception that was raised.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002901649_django_python.txt
Q: installing Python application with Python under windows My application uses many Python libraries (Django, Twisted, xmlrpc). I cannot expect that the end user has the Python installed with all needed libraries. I've created a fancy installer for my application using Inno Setup, but I don't think that it is a good...
installing Python application with Python under windows
My application uses many Python libraries (Django, Twisted, xmlrpc). I cannot expect that the end user has the Python installed with all needed libraries. I've created a fancy installer for my application using Inno Setup, but I don't think that it is a good solution to execute 5 other setup programs from my installer...
[ "May be you should try to make your application running standalone with py2exe or pyInstaller.\nIt will generate an application which doesn't expect anything from the target machine. You 'll have an exe file that the user can execute without knowing that Python is used. The Python interpreter and the needed libs wi...
[ 1, 0 ]
[]
[]
[ "deployment", "python" ]
stackoverflow_0002903507_deployment_python.txt
Q: Handling text menu in Python I am trying to create a text based menu in Python. Here is the code: #!/usr/bin/env python def testcaseOutput(): print '1. Add. 2. Subtract. 3. Divide. 4. Multiply' try: answer = int(raw_input('Enter a value (1 - 4) >. ')) except ValueError: print 'Inva...
Handling text menu in Python
I am trying to create a text based menu in Python. Here is the code: #!/usr/bin/env python def testcaseOutput(): print '1. Add. 2. Subtract. 3. Divide. 4. Multiply' try: answer = int(raw_input('Enter a value (1 - 4) >. ')) except ValueError: print 'Invalid input. Enter a value between 1...
[ "One possible refactoring is to use a loop, that continues to print the instructions and read input until acceptable input has been given:\ndef testcaseOutput():\n while True:\n print '1. Add. 2. Subtract. 3. Divide. 4. Multiply'\n\n try:\n answer = int(raw_input('Enter a value (1 - 4) >. '...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002903617_python.txt
Q: python-like Java IO library? Java is not my main programming language so I might be asking the obvious. But is there a simple file-handling library in Java, like in python? For example I just want to say: File f = Open('file.txt', 'w') for(String line:f){ //do something with the line from file } Thanks! UPD...
python-like Java IO library?
Java is not my main programming language so I might be asking the obvious. But is there a simple file-handling library in Java, like in python? For example I just want to say: File f = Open('file.txt', 'w') for(String line:f){ //do something with the line from file } Thanks! UPDATE: Well, the stackoverflow auto-...
[ "I was thinking something more along the lines of:\nFile f = File.open(\"C:/Users/File.txt\");\n\nfor(String s : f){\n System.out.println(s);\n}\n\nHere is my source code for it:\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io...
[ 19, 11, 4, 4, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "file_io", "java", "python" ]
stackoverflow_0002802711_file_io_java_python.txt
Q: in python how to remove this \n from string or list this is my main string "action","employee_id","name" "absent","pritesh",2010/09/15 00:00:00 so after name coolumn its goes to new line but here i append to list a new line character is added and make it like this way data_list***** ['"action","employee_id","na...
in python how to remove this \n from string or list
this is my main string "action","employee_id","name" "absent","pritesh",2010/09/15 00:00:00 so after name coolumn its goes to new line but here i append to list a new line character is added and make it like this way data_list***** ['"action","employee_id","name"\n"absent","pritesh",2010/09/15 00:00:00\n'] here its ...
[ "Davide's answer can be written even simpler as:\ndata_list = [word.strip() for word in data_list]\n\nBut I'm not sure it's what you want. Please write some sample in python.\n", "replaces = inString.replace(\"\\n\", \"\");\n\n", "First, you can use strip() to get rid of '\\n':\n>>> data = line.strip().split(',...
[ 9, 8, 3, 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002903523_python_string.txt
Q: Receiving XML document with python via HTTP I want to do a very simple webserver in python able to receive XML document over HTTP and then to send as response XML document. Do you have any example? just to understand How arrange the work... many thanks! UPDATE: I need something like this: a client do a post with a...
Receiving XML document with python via HTTP
I want to do a very simple webserver in python able to receive XML document over HTTP and then to send as response XML document. Do you have any example? just to understand How arrange the work... many thanks! UPDATE: I need something like this: a client do a post with an xml document: < request > < name>plus< /name> <...
[ "You can use XMLRPC :\nSimpleXMLRPCServer Example (from the Python Docs)\nServer code:\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer\nfrom SimpleXMLRPCServer import SimpleXMLRPCRequestHandler\n\n# Restrict to a particular path.\nclass RequestHandler(SimpleXMLRPCRequestHandler):\n rpc_paths = ('/RPC2',)\n\n#...
[ 1, 0 ]
[]
[]
[ "http", "python", "xml" ]
stackoverflow_0002903952_http_python_xml.txt
Q: A problem with assertRaises function in Python I am trying to run the following test self.assertRaises(Exception,lambda: unit_test.testBasic()) where test.testBasic() is class IsPrimeTest(unittest.TestCase): def assertRaises(self,exception,callable,*args,**kwargs): print('dfdf') temp = ca...
A problem with assertRaises function in Python
I am trying to run the following test self.assertRaises(Exception,lambda: unit_test.testBasic()) where test.testBasic() is class IsPrimeTest(unittest.TestCase): def assertRaises(self,exception,callable,*args,**kwargs): print('dfdf') temp = callable super().assertRaises(exception,temp,*...
[ "Do I understand you correctly in that you're asking why the testBasic_helper method doesn't raise an exception when the test runs?\nI don't see why it should, the is_prime should return a bool value against which the test checks for failure. If the test fails, it simply fails, neither your code nor the unittest fr...
[ 1 ]
[]
[]
[ "assertraises", "python" ]
stackoverflow_0002904073_assertraises_python.txt
Q: First parameter of os.exec* From the python docs: The various exec*() functions take a list of arguments for the new program loaded into the process. In each case, the first of these arguments is passed to the new program as its own name rather than as an argument a user may have typed on a command li...
First parameter of os.exec*
From the python docs: The various exec*() functions take a list of arguments for the new program loaded into the process. In each case, the first of these arguments is passed to the new program as its own name rather than as an argument a user may have typed on a command line. For the C programmer, this ...
[ "UNIX, where all these exec things come from, separated the program executable file from the program name, so that your process could have any arbitrary name.\nThe first argument is the program that will run. This must exist. The next argument is what your process running the program will be called, what will be in...
[ 21 ]
[]
[]
[ "command_line_arguments", "exec", "python" ]
stackoverflow_0002904171_command_line_arguments_exec_python.txt
Q: python dict update diff Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this: >>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'} >>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} >>> a.diff(b...
python dict update diff
Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this: >>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'} >>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} >>> a.diff(b) {'c':'pepsi', 'd':'ice crea...
[ "No, but you can subclass dict to provide notification on change. \nclass ObservableDict( dict ):\n def __init__( self, *args, **kw ):\n self.observers= []\n super( ObservableDict, self ).__init__( *args, **kw )\n def observe( self, observer ):\n self.observers.append( observer )\n de...
[ 11, 9, 2, 2, 1, 0 ]
[]
[]
[ "dictionary", "diff", "python" ]
stackoverflow_0000715234_dictionary_diff_python.txt
Q: How exactly can Python complement your C# skills for windows based development? I'm looking for a fun challenge, and am thinking about learning Python. I've heard really good things about the language. My question is, how (if at all) can Python complement the skills of a typical C# developer working mainly with MS...
How exactly can Python complement your C# skills for windows based development?
I'm looking for a fun challenge, and am thinking about learning Python. I've heard really good things about the language. My question is, how (if at all) can Python complement the skills of a typical C# developer working mainly with MS technologies on a Windows Platform. Some examples of typical C# dev on windows woul...
[ "At first, if you don't know a dymanic, non static-typed language, it will certainly help you to learn one. You will find out new programming paradigms and will affect your coding style and even if you don't use for a proper project, there are benefits in it for you. This of course applies for any new language you ...
[ 4 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0002904299_c#_python.txt
Q: How to turn a list of tuples into a string? I have a list of tuples that I'm trying to incorporate into a SQL query but I can't figure out how to join them together without adding slashes. My like this: list = [('val', 'val'), ('val', 'val'), ('val', 'val')] If I turn each tuple into a string and try to join them...
How to turn a list of tuples into a string?
I have a list of tuples that I'm trying to incorporate into a SQL query but I can't figure out how to join them together without adding slashes. My like this: list = [('val', 'val'), ('val', 'val'), ('val', 'val')] If I turn each tuple into a string and try to join them with a a comma I'll get something like ' (\'val\...
[ "Like this?\n>>> l=[('val', 'val'), ('val', 'val'), ('val', 'val')]\n>>> ','.join(map(','.join,l))\n'val,val,val,val,val,val'\n\n", "Using MySQLdb, executemany does this.\ncursor = db.cursor()\nvals = [(1,2,3), (4,5,6), (7,8,9), (2,5,6)]\nq = \"\"\"INSERT INTO first (comments, feed, keyword) VALUES (%s, %s, %s)\"...
[ 4, 2, 1, 1, 1 ]
[]
[]
[ "formatting", "python", "sql" ]
stackoverflow_0002897082_formatting_python_sql.txt
Q: just-in-time list I'd like to know if there is a class available, either in the standard library or in pypi, that fits this description. The constructor would take an iterator. It would implement the container protocol (ie __getitem__, __len__, etc), so that slices, length, etc., would work. In doing so, it would...
just-in-time list
I'd like to know if there is a class available, either in the standard library or in pypi, that fits this description. The constructor would take an iterator. It would implement the container protocol (ie __getitem__, __len__, etc), so that slices, length, etc., would work. In doing so, it would iterate and retain jus...
[ "import itertools\nclass Indexable(object):\n def __init__(self,it):\n self.it=it\n self.already_computed=[]\n def __iter__(self):\n for elt in self.it:\n self.already_computed.append(elt)\n yield elt\n def __getitem__(self,index):\n try:\n max_i...
[ 2 ]
[]
[]
[ "iterator", "list", "python" ]
stackoverflow_0002904459_iterator_list_python.txt
Q: Django models & Python class attributes The tutorial on the django website shows this code for the models: from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.For...
Django models & Python class attributes
The tutorial on the django website shows this code for the models: from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(m...
[ "Have a look at the Model class under django/db/models.py. There the class attributes are turned to instance attributes via something like\nsetattr(self, field.attname, val)\n\nOne might recommend the whole file (ModelBase and Model class) as an excellent hands-on example on metaclasses.\n", "It's done with metac...
[ 7, 2, 2, 0 ]
[]
[]
[ "attributes", "django", "python" ]
stackoverflow_0002903671_attributes_django_python.txt
Q: python: multiline regular expression I have a piece of text and I've got to parse usernames and hashes out of it. Right now I'm doing it with two regular expressions. Could I do it with just one multiline regular expression? #!/usr/bin/env python import re test_str = """ Hello, UserName. Please read this loooooo...
python: multiline regular expression
I have a piece of text and I've got to parse usernames and hashes out of it. Right now I'm doing it with two regular expressions. Could I do it with just one multiline regular expression? #!/usr/bin/env python import re test_str = """ Hello, UserName. Please read this looooooooooooooooong text. hash Now, write down t...
[ "Try this:\nre.findall(r'Hello, (?P<login>[^.]+)\\..+?hash: (?P<hash>[^.]+)', test_str, re.S)\n\n", "name_hash_pair = re.findall('Hello, ([^.]+).*?hash: ([^.]+)', test_str, re.DOTALL)\n#gives [('UserName', 'fdaf9399jef9qw0j'), ('UserName2', 'gtwnhton340gjr2g')]\n\n", "A simple pyparsing version:\nfrom pyparsing...
[ 5, 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002903309_python_regex.txt
Q: Find out 20th, 30th, nth prime number. (I'm getting 20th but not 30th?) [Python] The question is to find the 1000th prime number. I wrote the following python code for this. The problem is, I get the right answer for the 10th , 20th prime but after that each increment of 10 leaves me one off the mark. I can't catc...
Find out 20th, 30th, nth prime number. (I'm getting 20th but not 30th?) [Python]
The question is to find the 1000th prime number. I wrote the following python code for this. The problem is, I get the right answer for the 10th , 20th prime but after that each increment of 10 leaves me one off the mark. I can't catch the bug here :( count=1 #to keep count of prime numbers primes=() ...
[ "There is a nice Sieve of Eratosthenes generator implementation in test_generators.py:\ndef intsfrom(i):\n while 1:\n yield i\n i += 1\n\ndef firstn(g, n):\n return [g.next() for i in range(n)]\n\ndef exclude_multiples(n, ints):\n for i in ints:\n if i % n:\n yield i ...
[ 8, 5, 3, 2, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "primes", "python" ]
stackoverflow_0001995890_primes_python.txt
Q: web2py external libraries how can i import other external libraries in web2py? is it possible to load up libs in the static file? can somebody give me an example? thanks peter A: If the library is shipped with python, then you can just use import as you would do in regular python script. You can place your impo...
web2py external libraries
how can i import other external libraries in web2py? is it possible to load up libs in the static file? can somebody give me an example? thanks peter
[ "If the library is shipped with python, then you can just use import as you would do in regular python script. You can place your import statements into your models, controllers and views, as well as your own python modules (stored in modules folder). For example, I often use traceback module to log stack traces in...
[ 5, 0 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0002904498_python_web2py.txt
Q: How can I convert data encoded in WE8MSWIN1252 to utf8 for use in Python scripts? This data comes from an Oracle database and is extracted to flatfiles in encoding 'WE8MSWIN1252'. I want to parse the data and do some analysis. I want to see the text fields but do not need to publish the results to any other system...
How can I convert data encoded in WE8MSWIN1252 to utf8 for use in Python scripts?
This data comes from an Oracle database and is extracted to flatfiles in encoding 'WE8MSWIN1252'. I want to parse the data and do some analysis. I want to see the text fields but do not need to publish the results to any other system so if some characters do not get converted perfectly I do not have a problem with that...
[ "From the last few characters, I'd guess that this encoding is what the rest of the world calls windows-1252. So try:\ninputFile = codecs.open(dataFileName, \"r\", \"windows-1252\")\n\n" ]
[ 2 ]
[]
[]
[ "oracle", "python", "utf_8" ]
stackoverflow_0002904873_oracle_python_utf_8.txt
Q: What the heck kind of timestamp is this: 1267488000000 And how do I convert it to a datetime.datetime instance in python? It's the output from the New York State Senate's API: http://open.nysenate.gov/legislation/. A: It looks like Unix time, but with milliseconds instead of seconds? >>> import time >>> time.gmt...
What the heck kind of timestamp is this: 1267488000000
And how do I convert it to a datetime.datetime instance in python? It's the output from the New York State Senate's API: http://open.nysenate.gov/legislation/.
[ "It looks like Unix time, but with milliseconds instead of seconds?\n>>> import time\n>>> time.gmtime(1267488000000 / 1000)\ntime.struct_time(tm_year=2010, tm_mon=3, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=61, tm_isdst=0)\n\nMarch 2nd, 2010?\nAnd if you want a datetime object:\n>>> import datet...
[ 15, 5, 4, 3, 3, 2, 2, 1, 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002904847_datetime_python.txt
Q: How to tell process id within Python I am working with a cluster system over linux (www.mosix.org) that allows me to run jobs and have the system run them on different computers. Jobs are run like so: mosrun ls & This will naturally create the process and run it on the background, returning the process id, like s...
How to tell process id within Python
I am working with a cluster system over linux (www.mosix.org) that allows me to run jobs and have the system run them on different computers. Jobs are run like so: mosrun ls & This will naturally create the process and run it on the background, returning the process id, like so: [1] 29199 Later it will return. I am w...
[ "Use subprocess module. Popen instances have a pid attribute.\n", "Looks like you want to ensure the child process is daemonized -- PEP 3143, which I'm pointing to, documents and points to a reference implementation for that, and points to others too.\nOnce your process (still running Python code) is daemonized, ...
[ 3, 2, 0 ]
[]
[]
[ "mosix", "process", "python" ]
stackoverflow_0002884711_mosix_process_python.txt
Q: Is it possibile to modify a link value with Beautifulsoup without recreating the all link? Starting from an Html input like this: <p> <a href="http://www.foo.com" rel="nofollow">this is foo</a> <a href="http://www.bar.com" rel="nofollow">this is bar</a> </p> is it possible to modify the <a> node values ("this i f...
Is it possibile to modify a link value with Beautifulsoup without recreating the all link?
Starting from an Html input like this: <p> <a href="http://www.foo.com" rel="nofollow">this is foo</a> <a href="http://www.bar.com" rel="nofollow">this is bar</a> </p> is it possible to modify the <a> node values ("this i foo" and "this is bar") adding the suffix "PARSED" to the value without recreating the all link? ...
[ "If I understand you correctly then you're nearly there.\nChange your code to \nfor link_tag in soup.findAll('a'):\n link_tag.string = link_tag.string + '_PARSED'\nhtml_out = soup.renderContents()\n\nIf we print out html_out we get:\n>>> print html_out\n<p>\n<a href=\"http://www.foo.com\" rel=\"nofollow\">this i...
[ 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002904542_beautifulsoup_python.txt
Q: python c extension, problems with dlopen on mac os I've taken a library that is distributed as a binary lib (.a) and header, written some c++ code against it, and want to wrap the results up in a python module. I've done this here. The problem is that when importing this module on Mac OSX (I've tried 10.5 and 10....
python c extension, problems with dlopen on mac os
I've taken a library that is distributed as a binary lib (.a) and header, written some c++ code against it, and want to wrap the results up in a python module. I've done this here. The problem is that when importing this module on Mac OSX (I've tried 10.5 and 10.6), I get the following error: dlopen(/Library/Python/2....
[ "You're going to kick yourself when you see the answer to this! Try changing this:\nlink_args = ['-framework Carbon'] if platform == 'Darwin' else []\n\nto this:\nlink_args = ['-framework', 'Carbon'] if platform == 'Darwin' else []\n\nOnce I made this change I was able to do a clean build and import the module str...
[ 4 ]
[]
[]
[ "dlopen", "linker", "python", "python_c_extension", "setup.py" ]
stackoverflow_0002790186_dlopen_linker_python_python_c_extension_setup.py.txt
Q: httplib2 giving internal server error 500 with proxy Following is the code and error it throws. It works fine without the proxy http = httplib2.Http() . When I try the same http proxy in Firefox, it works fine. Any pointers are highly appreciated! Usage : http = httplib2.Http(proxy_info = httplib2.ProxyInfo(sock...
httplib2 giving internal server error 500 with proxy
Following is the code and error it throws. It works fine without the proxy http = httplib2.Http() . When I try the same http proxy in Firefox, it works fine. Any pointers are highly appreciated! Usage : http = httplib2.Http(proxy_info = httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, '68.48.25.158', 25681)) main_url = 'ht...
[ "Make sure the proxy isn't transparent. I don't know too much about this, but evidently a transparent proxy enables the server to see you're using a proxy, and perhaps even access your IP. Some websites will definitely shut down any requests that appear to originate from a proxy (for fear of bots). That may mean ei...
[ 1, 0 ]
[]
[]
[ "httplib2", "proxy", "python", "socks" ]
stackoverflow_0002905505_httplib2_proxy_python_socks.txt
Q: Perfom python unit tests via a web interface Is it possible to perform unittest tests via a web interface...and if so how? EDIT: For now I want the results...for the tests I want them to be automated...possibly every time I make a change to the code. Sorry I forgot to make this more clear A: EDIT: This answer ...
Perfom python unit tests via a web interface
Is it possible to perform unittest tests via a web interface...and if so how? EDIT: For now I want the results...for the tests I want them to be automated...possibly every time I make a change to the code. Sorry I forgot to make this more clear
[ "EDIT:\nThis answer is outdated at this point:\n\nUse Jenkins instead of Hudson (same thing, new name).\nUse django-jenkins instead of xmlrunner.py.\n\nThe link to django-jenkins goes to a nice tutorial on how to use Jenkins with Django. I'll leave the text below since it still has some nice information.\n\nAs Bry...
[ 8, 4 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0002904997_python_unit_testing.txt
Q: How do I convert a base 10 float to hex in Python 2.4? I trying to convert numbers from decimal to hex. How do I convert float values to hex or char in Python 2.4.3? I would then like to be able to print it as ("\xa5\x (new hex number here)"). How do I do that? A: From python 2.6.5 docs in hex(x) definition: To ...
How do I convert a base 10 float to hex in Python 2.4?
I trying to convert numbers from decimal to hex. How do I convert float values to hex or char in Python 2.4.3? I would then like to be able to print it as ("\xa5\x (new hex number here)"). How do I do that?
[ "From python 2.6.5 docs in hex(x) definition:\nTo obtain a hexadecimal string representation for a float, use the float.hex() method.\n", "Judging from this comment:\n\nwould you mind please to give an\n example of its use? I am trying to\n convert this 0.554 to hex by using\n float.hex(value)? and how can I w...
[ 1, 1, 0 ]
[]
[]
[ "decimal", "floating_point", "python", "python_2.4" ]
stackoverflow_0002904189_decimal_floating_point_python_python_2.4.txt
Q: Can I use Blender to create 3D wall image viewer application under Linux? Is that possible to use Blender to create Cooliris-like 3D wall image viewer application under Linux? I don't see many people use Blender (BGE) to create desktop application, so I am wondering if this is possible. People normally use Blender...
Can I use Blender to create 3D wall image viewer application under Linux?
Is that possible to use Blender to create Cooliris-like 3D wall image viewer application under Linux? I don't see many people use Blender (BGE) to create desktop application, so I am wondering if this is possible. People normally use Blender for modeling/movie and game engine. I can not find a good way to create 3D ap...
[ "There's always Clutter. Looks like it has Python bindings.\n" ]
[ 1 ]
[]
[]
[ "blender", "opengl", "python", "user_interface" ]
stackoverflow_0002902933_blender_opengl_python_user_interface.txt
Q: What are the differences between Perl, Python, AWK and sed? What are the main differences among them? And in which typical scenarios is it better to use each language? A: In order of appearance, the languages are sed, awk, perl, python. The sed program is a stream editor and is designed to apply the actions from...
What are the differences between Perl, Python, AWK and sed?
What are the main differences among them? And in which typical scenarios is it better to use each language?
[ "In order of appearance, the languages are sed, awk, perl, python.\nThe sed program is a stream editor and is designed to apply the actions from a script to each line (or, more generally, to specified ranges of lines) of the input file or files. Its language is based on ed, the Unix editor, and although it has cond...
[ 594, 102, 22, 18, 16 ]
[]
[]
[ "awk", "language_comparisons", "perl", "python", "sed" ]
stackoverflow_0000366980_awk_language_comparisons_perl_python_sed.txt
Q: The confusion on python encoding I retrieved the data encoded in big5 from database,and I want to send the data as email of html content, the code is like this: html += """<tr><td>""" html += unicode(rs[0], 'big5') # rs[0] is data encoded in big5 I run the script, but the error raised: UnicodeDecodeError:...
The confusion on python encoding
I retrieved the data encoded in big5 from database,and I want to send the data as email of html content, the code is like this: html += """<tr><td>""" html += unicode(rs[0], 'big5') # rs[0] is data encoded in big5 I run the script, but the error raised: UnicodeDecodeError: 'ascii' codec can't decode byte.........
[ "If html is not already a unicode object but a normal string, it is converted to unicode when it is concatenated with the converted version of rs[0]. If html now contains special characters you can get a unicode error.\nSo the other contents of html also need to be correctly decoded to unicode. If the special chara...
[ 2, 1 ]
[]
[]
[ "ascii", "encoding", "python", "unicode" ]
stackoverflow_0002904037_ascii_encoding_python_unicode.txt
Q: AppEngine dev_appserver.py not showing any outputs I installed Python2.6 and Google App Engine (GAE). I realized that GAE does not run on 2.6, so I installed 2.5 as well. Now I have a very basic code as follows and it does not show on the localhost:8080 I typed the following in cmd.exe under my dir testapps. c:\U...
AppEngine dev_appserver.py not showing any outputs
I installed Python2.6 and Google App Engine (GAE). I realized that GAE does not run on 2.6, so I installed 2.5 as well. Now I have a very basic code as follows and it does not show on the localhost:8080 I typed the following in cmd.exe under my dir testapps. c:\Users\myname\testapps>"\Program Files\Google\google_appen...
[]
[]
[ "I would suggest that you take a look at the guestbook sample program that is included with the SDK. It is located in the demos directory, and I think that looking at the structure of guestbook.py will go a long way towards helping you get a working app.\n" ]
[ -1 ]
[ "google_app_engine", "python" ]
stackoverflow_0002903300_google_app_engine_python.txt
Q: Adding anchors to h2 in text using python and regexp I'm trying to add anchors to all h2's in my html, using python. This code will add those anchors, but I need to fill the name of the anchors too. Any idea if the name can be the number of the match in the loop or a slugified version of the text between the h2 t...
Adding anchors to h2 in text using python and regexp
I'm trying to add anchors to all h2's in my html, using python. This code will add those anchors, but I need to fill the name of the anchors too. Any idea if the name can be the number of the match in the loop or a slugified version of the text between the h2 tags? Here's the code so far: regex = '(?P<name><h2>.*?</h2...
[ "You can take advantage of the fact that the second argument to re.sub can be a function to do pretty much anything you'd like. Here's an example that will slugify the text inside the <h2> element:\nregex = '(?P<name><h2>(.*?)</h2>)' # Note the extra group inside the <h2>\n\ndef slugify(s):\n return s.replace('...
[ 1, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0002905993_html_python.txt
Q: SVN hook script conflict I am trying to write a pre-commit hook script that will alter a specific svn-property of a folder/file. The script looks fairly similar to the one that is documented in the svn book. I figured out how to set/change the property of a node and when executing the binding function svn.fs.commi...
SVN hook script conflict
I am trying to write a pre-commit hook script that will alter a specific svn-property of a folder/file. The script looks fairly similar to the one that is documented in the svn book. I figured out how to set/change the property of a node and when executing the binding function svn.fs.commit_txn the property of the node...
[ "After updating a property on a directory you are required to update that directory before committing.\n", "You should never change data in a hook script. You lose the synchronization of the client and the subversion repository.\n" ]
[ 1, 0 ]
[]
[]
[ "conflict", "pre_commit_hook", "python", "svn", "svn_hooks" ]
stackoverflow_0002905573_conflict_pre_commit_hook_python_svn_svn_hooks.txt
Q: What is the difference between "a is b" and "id(a) == id(b)" in Python? The id() inbuilt function gives... an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. The is operator, instead, gives... object identity So why is it possible to have two objects...
What is the difference between "a is b" and "id(a) == id(b)" in Python?
The id() inbuilt function gives... an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. The is operator, instead, gives... object identity So why is it possible to have two objects that have the same id but return False to an is check? Here is an example: ...
[ ">>> b.test is a.test\nFalse\n>>> a.test is a.test\nFalse\n\nMethods are created on-the-fly each time you look them up. The function object (which is always the same object) implements the descriptor protocol and its __get__ creates the bound method object. No two bound methods would normally be the same object.\n>...
[ 64 ]
[]
[]
[ "identity", "python" ]
stackoverflow_0002906177_identity_python.txt
Q: Capturing Mac OS X System Audio output with Python I've been trying to "hijack" the Mac OS X system audio using PyAudio and save to a wav in python. That is, I do not want to record from an input device such as a microphone. I want to grab the sound output from any or all applications. I have followed the tutorial...
Capturing Mac OS X System Audio output with Python
I've been trying to "hijack" the Mac OS X system audio using PyAudio and save to a wav in python. That is, I do not want to record from an input device such as a microphone. I want to grab the sound output from any or all applications. I have followed the tutorials on the PyAudio site but these do not appear to cover m...
[ "I found that an open-source project called SoundFlower got me quickly to the place I needed to be.\n\nI installed the SoundFlower package from Google Code.\nOpened System Preferences -> Sound\nChose Soundflower as my Output device\nChose Soundflower as my Input device\n\nI was then able to record system audio from...
[ 8 ]
[]
[]
[ "audio", "macos", "python" ]
stackoverflow_0002883090_audio_macos_python.txt
Q: Emacs: pass arguments to inferior Python shell during buffer evaluation recently I started using Emacs as a Python IDE, and it not quite intuitive... The problem I am struggling with right now is how to pass command line arguments to the inferior python shell when the buffer is evaluated with C-c C-c. Thanks for h...
Emacs: pass arguments to inferior Python shell during buffer evaluation
recently I started using Emacs as a Python IDE, and it not quite intuitive... The problem I am struggling with right now is how to pass command line arguments to the inferior python shell when the buffer is evaluated with C-c C-c. Thanks for help.
[ "This doesn't appear to be easily possible; the inferior process managed by the python.el module is designed to persist across many invocations of python-send-buffer (and friends). One solution I've found is to write your own function that sets sys.argv programmatically from within the inferior process:\n(defun py...
[ 7 ]
[]
[]
[ "emacs", "ide", "python" ]
stackoverflow_0002905575_emacs_ide_python.txt
Q: Gmail mail server I used use Google’s slick interface to get my mail and It’s always going to be here: https://mail.google.com/a/yourdomainhere.com I want to write python script that send mail so i failed to configure server settings smtp = smtplib.SMTP('mail server should be what?', what is the port) smtp.login('...
Gmail mail server
I used use Google’s slick interface to get my mail and It’s always going to be here: https://mail.google.com/a/yourdomainhere.com I want to write python script that send mail so i failed to configure server settings smtp = smtplib.SMTP('mail server should be what?', what is the port) smtp.login('username@yourdomainhere...
[ "All on gmail's support site, see http://mail.google.com/support/bin/answer.py?hl=en&answer=13287\n", "Look at the help:\nhttp://mail.google.com/support/bin/answer.py?hl=en&answer=13287\nIts smtp.gmail.com\n", "The preferred method for SMTP message forwarding is using your ISP's SMTP server. The job of locating...
[ 6, 0, 0 ]
[]
[]
[ "gmail", "python" ]
stackoverflow_0002905987_gmail_python.txt
Q: [Python]Xml add a node from another xml document I have two xml file: 1)model.xml 2)projectionParametersTemplate.xml I want to extract from 1) Algorithm Node with his child and put it in 2) I have wrote this code but it doesn't function. from xml.dom.minidom import Document from xml.dom import minidom xmlmo...
[Python]Xml add a node from another xml document
I have two xml file: 1)model.xml 2)projectionParametersTemplate.xml I want to extract from 1) Algorithm Node with his child and put it in 2) I have wrote this code but it doesn't function. from xml.dom.minidom import Document from xml.dom import minidom xmlmodel=minidom.parse("/home/michele/Scrivania/d/model.xml...
[ "For me it works, e.g. the algorithm-node from xmlmodel is added to the ProjectionParameters-node from xmltemplate.\nMy guess is that you want to change the actual file. With your code, only the object in memory is modified, not the file on disk. If you want to change the file, add this line at the end:\nxmltemplat...
[ 0 ]
[]
[]
[ "add", "python", "xml" ]
stackoverflow_0002905659_add_python_xml.txt
Q: Correct way to do timer function in Python I have a GUI application that needs to do something simple in the background (update a wx python progress bar, but that doesn't really matter). I see that there is a threading.timer class.. but there seems to be no way to make it repeat. So if I use the timer, I end up ha...
Correct way to do timer function in Python
I have a GUI application that needs to do something simple in the background (update a wx python progress bar, but that doesn't really matter). I see that there is a threading.timer class.. but there seems to be no way to make it repeat. So if I use the timer, I end up having to make a new thread on every single execut...
[ "A pattern more like this is probably what you should be doing, but it's hard to say because you didn't provide many details.\ndef do_background_work(self):\n # do work on a background thread, posting updates to the\n # GUI thread with CallAfter\n while True:\n # do stuff\n wx.CallAfter(self....
[ 3, 2 ]
[]
[]
[ "multithreading", "python", "timer" ]
stackoverflow_0002906510_multithreading_python_timer.txt
Q: Why is Django testrunner not finding the tests I created? I had been trying to add tests to a project I'm working on. The tests are in forum/tests/ When I run manage.py test it doesn't find any of the tests I created, on the tests in Django 1.2 I started with all my tests in their own package but have simpl...
Why is Django testrunner not finding the tests I created?
I had been trying to add tests to a project I'm working on. The tests are in forum/tests/ When I run manage.py test it doesn't find any of the tests I created, on the tests in Django 1.2 I started with all my tests in their own package but have simplified down to just being in my tests.py file. The current tests...
[ "As noted in the comment, Django 1.6 introduced backwards-incompatibility with discovery of tests in any test module.\nBefore Django 1.6, one would have to do the following:\nCreate file named __init__.py in\nforum/tests/__init__.py\n\nAnd import all test from other moduls inside it.\nfrom test_views import SomeTes...
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002906285_django_python.txt
Q: way to fix number of concurrent sessions allowed at app level. django How can I fix number of concurrent sessions allowed at app level? Basically I want a limit to how many concurrent requests to this url to keep the server from getting congested. I guess some middleware hack? Thanks. A: Don't do this in django...
way to fix number of concurrent sessions allowed at app level. django
How can I fix number of concurrent sessions allowed at app level? Basically I want a limit to how many concurrent requests to this url to keep the server from getting congested. I guess some middleware hack? Thanks.
[ "Don't do this in django, but in Apache / nginx / whatever webserver you have in front of Django. They have specific modules exactly for such tasks.\nA possible solution for Apache would be: mod_limitipconn2 - http://dominia.org/djao/limitipconn2.html\n", "Django stores session information in the database by defa...
[ 1, 0, 0 ]
[]
[]
[ "django", "python", "session" ]
stackoverflow_0002906790_django_python_session.txt
Q: Python command line UI Hey guys/gals I'm writing a python script that fixes some duplicate issues on my database. I would like to display some progress status to the users, currently I just print it like this: print "Merged " + str(idx) + " out of " + str(totalCount); The problem is that it prints that in a new l...
Python command line UI
Hey guys/gals I'm writing a python script that fixes some duplicate issues on my database. I would like to display some progress status to the users, currently I just print it like this: print "Merged " + str(idx) + " out of " + str(totalCount); The problem is that it prints that in a new line for every record and tha...
[ "Check out fish.\n", "If you just want to constantly overwrite the same line, use '\\r' and print foo, to act as a carriage return and a non-endline-printing print.\nwhile doingStuff:\n msg = \"\\rMerged %s out of %s\" % (idx, totalCount)\n print msg,\n\nBut if you're designing a fancier console app, you ma...
[ 4, 4 ]
[]
[]
[ "command_line", "python", "user_interface" ]
stackoverflow_0002907035_command_line_python_user_interface.txt
Q: MD5 hash differences between Python and other file hashers I have been doing a bit of programming in Python (still a n00b at it) and came across something odd. I made a small program to find the MD5 hash of a filename passed to it on the command line. I used a function I found here on SO. When I ran it against ...
MD5 hash differences between Python and other file hashers
I have been doing a bit of programming in Python (still a n00b at it) and came across something odd. I made a small program to find the MD5 hash of a filename passed to it on the command line. I used a function I found here on SO. When I ran it against a file, I got a hash "58a...113". But when I ran Microsoft's FC...
[ "Already resolved in comments, but in case anyone wants to give me points... ;)\nOpen your file in binary mode!\nf = open(path, 'rb')\n\n" ]
[ 8 ]
[]
[]
[ "hash", "md5", "python" ]
stackoverflow_0002906863_hash_md5_python.txt
Q: extra newlines at end of file transported over tcp I have two programs, recvfile.py and sendfile.cpp. They work except that I end up with a bunch of extra newline characters at the end of the new file. I don't know how the extra spaces get there. I know the problem is sender side, because the same doesn't happen w...
extra newlines at end of file transported over tcp
I have two programs, recvfile.py and sendfile.cpp. They work except that I end up with a bunch of extra newline characters at the end of the new file. I don't know how the extra spaces get there. I know the problem is sender side, because the same doesn't happen when I use python's sendall() function to send the file. ...
[ "The reason you're ending up with extra newlines is because you're sending extra newlines across the socket, which is because you try to send more data than you should.\nIf you checked the fail() state of your input file fin, you'd discover that it's failing on the last several calls to fin.get(c), so the value of ...
[ 2 ]
[]
[]
[ "c", "c++", "python", "sockets", "winsockets" ]
stackoverflow_0002907353_c_c++_python_sockets_winsockets.txt
Q: Trouble importing a Python module I have a Python project with 2 files: epic.py site.py in the epic.py I have the lines from site import * bark() in site.py I have the lines def bark(): print('arf!') when I try to run epic.py, it returns "bark is not defined" this is weird. A: Try renaming site.py to mysi...
Trouble importing a Python module
I have a Python project with 2 files: epic.py site.py in the epic.py I have the lines from site import * bark() in site.py I have the lines def bark(): print('arf!') when I try to run epic.py, it returns "bark is not defined" this is weird.
[ "Try renaming site.py to mysite.py or something like that because there is a standard Python site module.\n", "That's because site is also the name of a built-in module. You weren't really importing your custom site module. If you change the name to, say, site_.py and import accordingly, it'll work. \n" ]
[ 5, 1 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0002907620_import_module_python.txt
Q: How do I rename a process on Linux? I'm using Python, for what it's worth, but will accept answers in any applicable language. I've tried writing to /proc/$pid/cmdline, but that's a readonly file. I've tried assigning a new string to sys.argv[0], but that has no perceptible impact. Are there any other possibilitie...
How do I rename a process on Linux?
I'm using Python, for what it's worth, but will accept answers in any applicable language. I've tried writing to /proc/$pid/cmdline, but that's a readonly file. I've tried assigning a new string to sys.argv[0], but that has no perceptible impact. Are there any other possibilities? My program is executing processes via...
[ "Writing to *argv will change it, but you'll need to do that from C or the like; I don't think Python is going to readily give you access to that memory directly.\nI'd also recommend just leaving it alone.\n", "If you use subprocess.Popen instead of os.system you can use the executable argument to specify the pat...
[ 0, 0 ]
[]
[]
[ "linux", "process", "python", "shell" ]
stackoverflow_0002907864_linux_process_python_shell.txt
Q: hierarchical clustering on correlations in Python scipy/numpy? How can I run hierarchical clustering on a correlation matrix in scipy/numpy? I have a matrix of 100 rows by 9 columns, and I'd like to hierarchically cluster by correlations of each entry across the 9 conditions. I'd like to use 1-pearson correlatio...
hierarchical clustering on correlations in Python scipy/numpy?
How can I run hierarchical clustering on a correlation matrix in scipy/numpy? I have a matrix of 100 rows by 9 columns, and I'd like to hierarchically cluster by correlations of each entry across the 9 conditions. I'd like to use 1-pearson correlation as the distances for clustering. Assuming I have a numpy array X ...
[ "Just change the metric to correlation so that the first line becomes:\nY=pdist(X, 'correlation')\n\nHowever, I believe that the code can be simplified to just:\nZ=linkage(X, 'single', 'correlation')\ndendrogram(Z, color_threshold=0)\n\nbecause linkage will take care of the pdist for you.\n" ]
[ 13 ]
[]
[]
[ "cluster_analysis", "machine_learning", "numpy", "python", "scipy" ]
stackoverflow_0002907919_cluster_analysis_machine_learning_numpy_python_scipy.txt
Q: How do I add a custom inline admin widget in Django? This is easy for non-inlines. Just override the following in the your admin.py AdminOptions: def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'photo': kwargs['widget'] = AdminImageWidget() return db_field.formfield(**k...
How do I add a custom inline admin widget in Django?
This is easy for non-inlines. Just override the following in the your admin.py AdminOptions: def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'photo': kwargs['widget'] = AdminImageWidget() return db_field.formfield(**kwargs) return super(NewsOptions,self).formfield_for_db...
[ "It works exactly the same way. The TabularInline and StackedInline classes also have a formfield_for_dbfield method, and you override it the same way in your subclass.\n", "Since Django 1.1, formfield_overrides is also working\nformfield_overrides = {\n models.ImageField: {'widget': AdminImageWidget},\n}\n\n...
[ 11, 8, 3 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0000433251_django_django_admin_python.txt
Q: Django CSRF failure when form posts to a different frame I'm building a page where I want to have a form that posts to an iframe on the same page. The Template looks like this: <form action="form-results" method="post" target="resultspane" > {% csrf_token %} <input name="query"> <input...
Django CSRF failure when form posts to a different frame
I'm building a page where I want to have a form that posts to an iframe on the same page. The Template looks like this: <form action="form-results" method="post" target="resultspane" > {% csrf_token %} <input name="query"> <input type=submit> </form> <iframe src="form-results" name...
[ "Actually, the problem has nothing to do with cross-form POSTing. The template that displays the form needs to be rendered with RequestContext as in\nreturn render_to_response('form_template.html',\n context_instance = RequestContext(request))\n\n" ]
[ 2 ]
[]
[]
[ "django", "django_csrf", "iframe", "python" ]
stackoverflow_0002908284_django_django_csrf_iframe_python.txt
Q: Are there viable alternatives for Web 2.0 apps besides lots of Javascript? If you say find C-style syntax to be in the axis of evil are you just hopelessly condemned to suck it up and deal with it if you want to provide your users with cool web 2.0 applications - for example stuff that's generally done using JQuer...
Are there viable alternatives for Web 2.0 apps besides lots of Javascript?
If you say find C-style syntax to be in the axis of evil are you just hopelessly condemned to suck it up and deal with it if you want to provide your users with cool web 2.0 applications - for example stuff that's generally done using JQuery and Ajax etc? Are there no other choices out there? We're currently building...
[ "Other language supported by \"some\" \"browsers\" is VBScript, but.. you don't want to go there. \nThe support for other languages is still work in progress.\nWhat you can get today is to have a framework or library to translate one language into JavaScript\nHere are some of them along with a small sample:\n\nGWT...
[ 4, 3, 0, 0 ]
[]
[]
[ "ajax", "pylons", "python" ]
stackoverflow_0002908108_ajax_pylons_python.txt
Q: split a string into a list of tuples If i have a string like: "user1:type1,user2:type2,user3:type3" and I want to convert this to a list of tuples like so: [('user1','type1'),('user2','type2'),('user3','type3')] how would i go about doing this? I'm fairly new to python but couldn't find a good example in the d...
split a string into a list of tuples
If i have a string like: "user1:type1,user2:type2,user3:type3" and I want to convert this to a list of tuples like so: [('user1','type1'),('user2','type2'),('user3','type3')] how would i go about doing this? I'm fairly new to python but couldn't find a good example in the documentation to do this. Thanks!
[ ">>> s = \"user1:type1,user2:type2,user3:type3\"\n>>> [tuple(x.split(':')) for x in s.split(',')]\n[('user1', 'type1'), ('user2', 'type2'), ('user3', 'type3')]\n\n", "The cleanest way is two splits with a list comprehension:\nstr = \"user1:type1,user2:type2,user3:type3\"\nres = [tuple(x.split(\":\")) for x in str...
[ 12, 5, 4, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002908308_python.txt
Q: How to run perl script with a few arguments from php My html webpage calls a php script to upload files to the server from a local computer as follows. <form enctype="multipart/form-data" action="upload.php" method="POST"> <p><b><h3> <font color="#003366"> (1) Upload your reading text file. </font> </h3> </b> ...
How to run perl script with a few arguments from php
My html webpage calls a php script to upload files to the server from a local computer as follows. <form enctype="multipart/form-data" action="upload.php" method="POST"> <p><b><h3> <font color="#003366"> (1) Upload your reading text file. </font> </h3> </b> </p> <INPUT type="file" name="uploaded" size="50" > <br/> ...
[ "This is very likely a permissions problem. Try setting the files that the perl script reads to a+rw and see if it works then. If so, then you need to find out the user running php (likely the apache user) and make sure that they can read/write the relevant files.\nAlso make sure the Perl script is executable by th...
[ 1, 0, 0 ]
[]
[]
[ "perl", "php", "python", "shell" ]
stackoverflow_0002908274_perl_php_python_shell.txt
Q: what does "from MODULE import _" do in python? In the Getting things gnome code base I stumbled upon this import statement from GTG import _ and have no idea what it means, never seen this in the documentation and a quick so / google search didn't turn anything up. A: from GTG import _ imports the _ function ...
what does "from MODULE import _" do in python?
In the Getting things gnome code base I stumbled upon this import statement from GTG import _ and have no idea what it means, never seen this in the documentation and a quick so / google search didn't turn anything up.
[ "from GTG import _ imports the _ function from the GTG module into the \"current\" namespace.\nUsually, the _ function is an alias for gettext.gettext(), a function that shows the localized version of a given message. The documentation gives a picture of what is usually going on somewhere else in a module far, far ...
[ 13, 4 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002908444_import_python.txt
Q: Refining data stored in SQLite - how to join several contacts? I'm storing contacts between different elements. I want to eliminate elements of certain type and store new contacts of elements which were interconnected by the eliminated element. Problem background Imagine this problem. You have a water molecule whi...
Refining data stored in SQLite - how to join several contacts?
I'm storing contacts between different elements. I want to eliminate elements of certain type and store new contacts of elements which were interconnected by the eliminated element. Problem background Imagine this problem. You have a water molecule which is in contact with other molecules (if the contact is a hydrogen ...
[ "There's one difficulty with your explanation. \nWhat you start with is a directed graph where each edge represents a connection X=>Y where X is a donor and Y an acceptor. The table atoms is the SQL representation of that graph. \nWhat you seem to want is something that is undirected. So that a link X-Y means that ...
[ 2, 1 ]
[]
[]
[ "algorithm", "bioinformatics", "python", "sql", "sqlite" ]
stackoverflow_0002904205_algorithm_bioinformatics_python_sql_sqlite.txt
Q: Can't import pygame to Netbeans on Mac I am running python 2.6.5 and pygame 1.9.1 It seems to me I've tried everything but it keeps showing 'module not found' errors... Please help! A: Well I've just finished installing it on my Mac - you have to watch out for the Python Platform under Tools and File. The defaul...
Can't import pygame to Netbeans on Mac
I am running python 2.6.5 and pygame 1.9.1 It seems to me I've tried everything but it keeps showing 'module not found' errors... Please help!
[ "Well I've just finished installing it on my Mac - you have to watch out for the Python Platform under Tools and File. The default is Jython, but you want to change it to point to your python version in the Frameworks file of your Library.\nDoes that make sense?\n" ]
[ 1 ]
[]
[]
[ "import", "module", "netbeans", "pygame", "python" ]
stackoverflow_0002541254_import_module_netbeans_pygame_python.txt
Q: append versus resize for numpy array I would like to append a value at the end of my numpy.array. I saw numpy.append function but this performs an exact copy of the original array adding at last my new value. I would like to avoid copies since my arrays are big. I am using resize method and then set the last inde...
append versus resize for numpy array
I would like to append a value at the end of my numpy.array. I saw numpy.append function but this performs an exact copy of the original array adding at last my new value. I would like to avoid copies since my arrays are big. I am using resize method and then set the last index available to the new value. Can you conf...
[ "My simple timing experiment of append vs. resizing showed that resizing is about 3x faster and its the fastest way that I can think of to do this. Also, the answer to this question seems to imply that resizing the array is the way to go because it is in-place.\nVerdict:\nUse resize\nP.S. You also might want to che...
[ 8 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0002908672_arrays_numpy_python.txt
Q: how to fetch more than 1000 entities NON keybased? If I should be approaching this problem through a different method, please suggest so. I am creating an item based collaborative filter. I populate the db with the LinkRating2 class and for each link there are more than a 1000 users that I need to call and colle...
how to fetch more than 1000 entities NON keybased?
If I should be approaching this problem through a different method, please suggest so. I am creating an item based collaborative filter. I populate the db with the LinkRating2 class and for each link there are more than a 1000 users that I need to call and collect their ratings to perform calculations which I then us...
[ "Wooble points out that the 1,000 entity limit is a thing of the past now, so you actually don't need to use cursors to do this - just fetch everything at once (it'll be faster than getting them in 1,000 entity batches too since there will be fewer round-trips to the datastore, etc.)\nThe removal of the 1000 entity...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002907587_google_app_engine_python.txt
Q: Which Python XML library should I use? I am going to handle XML files for a project. I had earlier decided to use lxml but after reading the requirements, I think ElemenTree would be better for my purpose. The XML files that have to be processed are: Small in size. Typically < 10 KB. No namespaces. Simple XML ...
Which Python XML library should I use?
I am going to handle XML files for a project. I had earlier decided to use lxml but after reading the requirements, I think ElemenTree would be better for my purpose. The XML files that have to be processed are: Small in size. Typically < 10 KB. No namespaces. Simple XML structure. Given the small XML size, memory...
[ "As others have pointed out, lxml implements the ElementTree API, so you're safe starting out with ElementTree and migrating to lxml if you need better performance or more advanced features.\nThe big advantage of using ElementTree, if it meets your needs, is that as of Python 2.5 it is part of the Python standard l...
[ 3, 0, 0 ]
[]
[]
[ "celementtree", "lxml", "python" ]
stackoverflow_0002908440_celementtree_lxml_python.txt
Q: Looping through a directory on the web and displaying its contents (files and other directories) via Python In the same vein as Process a set of files from a source directory to a destination directory in Python I'm wondering if it is possible to create a function that when given a web directory it will list out t...
Looping through a directory on the web and displaying its contents (files and other directories) via Python
In the same vein as Process a set of files from a source directory to a destination directory in Python I'm wondering if it is possible to create a function that when given a web directory it will list out the files in said directory. Something like... files[] for file in urllib.listdir(dir): if file.isdir: ...
[ "What is a web directory? \nA web page has links. The page with the links may, or may not be, generated by the web server based on the contents of the directory. \nAn example of automatically generating links is found here, and is possibly the result of something like mod_dir configuration in the Web server, Apache...
[ 2, 1 ]
[]
[]
[ "directory", "file", "loops", "python", "urllib" ]
stackoverflow_0002907728_directory_file_loops_python_urllib.txt
Q: How to append a tag after a link with BeautifulSoup Starting from an Html input like this: <p> <a href="http://www.foo.com">this if foo</a> <a href="http://www.bar.com">this if bar</a> </p> using BeautifulSoup, i would like to change this Html in: <p> <a href="http://www.foo.com">this if foo</a><b>OK</b> <a href=...
How to append a tag after a link with BeautifulSoup
Starting from an Html input like this: <p> <a href="http://www.foo.com">this if foo</a> <a href="http://www.bar.com">this if bar</a> </p> using BeautifulSoup, i would like to change this Html in: <p> <a href="http://www.foo.com">this if foo</a><b>OK</b> <a href="http://www.bar.com">this if bar</a><b>OK</b> </p> Is it...
[ "You can use BeautifulSoup's insert to add the element in the right place:\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(html)\n\nfor link_tag in soup.findAll('a'):\n link_tag_idx = link_tag.parent.contents.index(link_tag)\n link_tag.parent.insert(link_tag_idx + 1, '<b>OK</b>')\n\nThis works ...
[ 8, 5 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002908362_beautifulsoup_python.txt
Q: Extra characters Extracted with XPath and Python (html) I have been using XPath with scrapy to extract text from html tags online, but when I do I get extra characters attached. An example is trying to extract a number, like "204" from a <td> tag and getting [u'204']. In some cases its much worse. For instance try...
Extra characters Extracted with XPath and Python (html)
I have been using XPath with scrapy to extract text from html tags online, but when I do I get extra characters attached. An example is trying to extract a number, like "204" from a <td> tag and getting [u'204']. In some cases its much worse. For instance trying to extract "1 - Mathoverflow" and instead getting [u'\r\n...
[ "What does the line of code look like that returns [u'204']? It looks like what is being returned is a Python list containing a unicode string with the value you want. Nothing wront there--just subscript. As for the carriage returns, linefeeds and tabs, as Wai Yip Tung just answered, strip will take them out.\nP...
[ 2, 2, 1 ]
[]
[]
[ "html", "python", "scrapy" ]
stackoverflow_0002909067_html_python_scrapy.txt
Q: This is my current way of writing to a file. However, I can't do UTF-8? f = open("go.txt", "w") f.write(title) f.close() What if "title" is in japanese/utf-8? How do I modify this code to be able to write "title" without having the ascii error? Edit: Then, how do I read this file in UTF-8? A: How to use UTF-8:...
This is my current way of writing to a file. However, I can't do UTF-8?
f = open("go.txt", "w") f.write(title) f.close() What if "title" is in japanese/utf-8? How do I modify this code to be able to write "title" without having the ascii error? Edit: Then, how do I read this file in UTF-8?
[ "How to use UTF-8:\nimport codecs\n\n# ...\n# title is a unicode string\n# ...\n\nf = codecs.open(\"go.txt\", \"w\", \"utf-8\")\nf.write(title)\n\n# ...\n\nfileObj = codecs.open(\"go.txt\", \"r\", \"utf-8\")\nu = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file\n\n", "It depends on wheth...
[ 2, 2 ]
[]
[]
[ "encoding", "file", "python", "utf_8" ]
stackoverflow_0002909386_encoding_file_python_utf_8.txt
Q: Python adding elements from string I have a string like this "1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 1 1 2 0,5 0,66 2 1 2 1 1 1 ...
Python adding elements from string
I have a string like this "1 1 3 2 1 1 1 2 1 1 1 1 1 1 1 1,5 0,33 0,66 1 0,33 0,66 1 1 2 1 1 2 1 1 2 0,5 0,66 2 1 2 1 1 1 0 1". How to add elements to each ...
[ "print sum(float(x.replace(',', '.')) for x in str.split(' '))\n\noutputs:\n45.64\n\n", "The \"python-esque\" way of doing it:\nsum([float(num) for num in str.replace(',', '.').split(' ')])\n\nMakes a list by splitting the string by spaces, then turn each piece into a float and add them up.\n", "Let's not be so...
[ 7, 4, 4, 2, 2, 1, 1 ]
[]
[]
[ "list", "python", "replace", "string" ]
stackoverflow_0002909395_list_python_replace_string.txt