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: Easiest way of unit testing C code with Python I've got a pile of C code that I'd like to unit test using Python's unittest library (in Windows), but I'm trying to work out the best way of interfacing the C code so that Python can execute it (and get the results back). Does anybody have any experience in the easie...
Easiest way of unit testing C code with Python
I've got a pile of C code that I'd like to unit test using Python's unittest library (in Windows), but I'm trying to work out the best way of interfacing the C code so that Python can execute it (and get the results back). Does anybody have any experience in the easiest way to do it? Some ideas include: Wrapping the c...
[ "Using ctypes would be my first instinct, though I must admit that if I was testing C code that was not going to be interfaced from Python in the first place, I would just use check. Check has the strong advantage of being able to properly report test cases that segfault. This is because it runs each test case in a...
[ 12, 8 ]
[]
[]
[ "c", "python", "swig", "unit_testing" ]
stackoverflow_0002482270_c_python_swig_unit_testing.txt
Q: Performance Wise, Python VS JAVA For File Based Processing I need to create daemon that will monitor certain directory and will process every file that's written to that particular path. My choice is either java or python. Did you guys have any experience using both technology? what is the best one? EDIT 1: files ...
Performance Wise, Python VS JAVA For File Based Processing
I need to create daemon that will monitor certain directory and will process every file that's written to that particular path. My choice is either java or python. Did you guys have any experience using both technology? what is the best one? EDIT 1: files that will be processed is simple text file (one line with tab s...
[ "Performance-wise, for an I/O - syscall bound task such as you're mentioning, it's going to be a wash, most likely, depending a bit on the platform. Java tends to have better CPU usage (partly because a JVM can effectively use multiple cores on a multicore CPU on different threads, with CPython having problems wit...
[ 0 ]
[]
[]
[ "file_io", "java", "python" ]
stackoverflow_0002490291_file_io_java_python.txt
Q: Best/Fastest Way to Test Python CGI locally? Just wondering whats the best way to test Python CGI while developing a site? (I'm used to PHP for web dev so bear with me :P) A: The Python standard library's CGIHTTPServer module is a simple, quick-and-dirty way to locally test CGI scripts! A: There are a number o...
Best/Fastest Way to Test Python CGI locally?
Just wondering whats the best way to test Python CGI while developing a site? (I'm used to PHP for web dev so bear with me :P)
[ "The Python standard library's CGIHTTPServer module is a simple, quick-and-dirty way to locally test CGI scripts!\n", "There are a number of Python web frameworks which make this easier for you. Django, for example, has a built-in web server designed for testing out your application.\nHowever, if you're already ...
[ 6, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0002490150_cgi_python.txt
Q: My method is being recognized within my own program. Newbie mistake probably Here's my code: sentenceToTranslate = raw_input("Please write in the sentence you want to translate: ") words = sentenceToTranslate.split(" ") for word in words: if isVowel(word[0]): print "TEST" def isVowel(letter): if ...
My method is being recognized within my own program. Newbie mistake probably
Here's my code: sentenceToTranslate = raw_input("Please write in the sentence you want to translate: ") words = sentenceToTranslate.split(" ") for word in words: if isVowel(word[0]): print "TEST" def isVowel(letter): if letter.lower() == "a" or letter.lower() == "e" or letter.lower() == "i" or letter...
[ "The function hasn't been defined yet, so the name 'isVowel' doesn't have a function bound to it: that only happens at the time when you say \"def\".\nSolution: move your code below the def isVowel(letter).\n", "\nPut the def isVowel definition at top.\n\nYou defined the function after it had already been called....
[ 5, 2, 1, 1, 0, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0002489273_function_python.txt
Q: Will Python 3 ever catch on? I have been learning a bit of Python 2 and Python 3 and it seems like Python 2 is overall better than Python 3. So that's where my question comes in. Are there any good reasons to actually switch over to python 3? A: On the whole, and even in most details, Python3 is better than Pyth...
Will Python 3 ever catch on?
I have been learning a bit of Python 2 and Python 3 and it seems like Python 2 is overall better than Python 3. So that's where my question comes in. Are there any good reasons to actually switch over to python 3?
[ "On the whole, and even in most details, Python3 is better than Python2.\nThe only area where Python 3 is lagging is with regards to 3rd party libraries. What makes Python great is not only its intrinsic characteristics as a language and its rather extensive standard library, but also the existence of a whole \"ec...
[ 32, 18, 7, 6, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002489299_python_python_3.x.txt
Q: Unit testing in python? Hey - I'm new to python , and I'm having a hard time grasping the concept of Unit testing in python. I'm coming from Java - so unit testing makes sense because - well , there you actually have a unit - A Class. But a Python class is not necessarily the same as a Java class , and the way I u...
Unit testing in python?
Hey - I'm new to python , and I'm having a hard time grasping the concept of Unit testing in python. I'm coming from Java - so unit testing makes sense because - well , there you actually have a unit - A Class. But a Python class is not necessarily the same as a Java class , and the way I use Python - as a scripting la...
[ "Python has a unit test module that I like. You can also read unit test section of Dive Into Python.\nHeres a basic example from the (linked) documentation:\nimport random\nimport unittest\n\nclass TestSequenceFunctions(unittest.TestCase):\n\n def setUp(self):\n self.seq = range(10)\n\n def test_shuffl...
[ 9, 5, 5, 3 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0002490715_python_unit_testing.txt
Q: Python: Retrieve Image from MSSQL I'm working on a Python project that retrieves an image from MSSQL. My code is able to retrieve the images successfully but with a fixed size of 63KB. if the image is greater than that size, it just brings the first 63KB from the image! The following is my code: #!/usr/bin/python ...
Python: Retrieve Image from MSSQL
I'm working on a Python project that retrieves an image from MSSQL. My code is able to retrieve the images successfully but with a fixed size of 63KB. if the image is greater than that size, it just brings the first 63KB from the image! The following is my code: #!/usr/bin/python import _mssql mssql=_mssql.connect('<S...
[ "It's kind of hard to tell what the problem is when you're using a database like this. Your query isn't explicitly selecting any columns, so we have no idea what your table structure is, or what types the columns are. I suspect the table format is not what you're expecting, or the columntype is incorrect for your d...
[ 1, 0 ]
[]
[]
[ "file_io", "python", "sql_server" ]
stackoverflow_0000691288_file_io_python_sql_server.txt
Q: Consecutive, Overlapping Subsets of Array (NumPy, Python) I have a NumPy array [1,2,3,4,5,6,7,8,9,10,11,12,13,14] and want to have an array structured like [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]. Sure this is possible by looping over the large array and adding arrays of length four to the new array,...
Consecutive, Overlapping Subsets of Array (NumPy, Python)
I have a NumPy array [1,2,3,4,5,6,7,8,9,10,11,12,13,14] and want to have an array structured like [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]. Sure this is possible by looping over the large array and adding arrays of length four to the new array, but I'm curious if there is some secret 'magic' Python method ...
[ "You should use stride_tricks. When I first saw this, the word 'magic' did spring to mind. It's simple and is by far the fastest method.\n>>> as_strided = numpy.lib.stride_tricks.as_strided\n>>> a = numpy.arange(1,15)\n>>> a\narray([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])\n>>> b = as_strided(a, (...
[ 31, 17, 4, 1, 1, 0, 0 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0002485669_numpy_python_scipy.txt
Q: Python/Django application with dynamic model name (application reuse) excuse me in advance if this is not the right title for the problem but here it is: You have application that works with pre defined model. What happens if you want to use this application one more time in your project but pointing to different ...
Python/Django application with dynamic model name (application reuse)
excuse me in advance if this is not the right title for the problem but here it is: You have application that works with pre defined model. What happens if you want to use this application one more time in your project but pointing to different model (same structure but differen name). For example - you have a "News"...
[ "This is what abstract models are for. Define once, and all children will acquire the fields in the abstract model, plus be able to define additional fields.\n" ]
[ 2 ]
[]
[]
[ "code_reuse", "django", "models", "python" ]
stackoverflow_0002490759_code_reuse_django_models_python.txt
Q: Use string as input to re.compile I want to use a variable in a regex, like this: variables = ['variableA','variableB'] for i in range(len(variables)): regex = r"'('+variables[i]+')[:|=|\(](-?\d+(?:\.\d+)?)(?:\))?'" pattern_variable = re.compile(regex) match = re.search(pattern_variable, line) The pr...
Use string as input to re.compile
I want to use a variable in a regex, like this: variables = ['variableA','variableB'] for i in range(len(variables)): regex = r"'('+variables[i]+')[:|=|\(](-?\d+(?:\.\d+)?)(?:\))?'" pattern_variable = re.compile(regex) match = re.search(pattern_variable, line) The problem is that python adds an extra back...
[ "No, it only displays extra backslashes so that the string could be read in again and have the correct number of backslashes. Try\nprint regex\n\nand you will see the difference.\n", "There is no problem there. What you're seeing is the output of the repr() of the string. Since the repr is supposed to be more-or...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002491196_python_regex.txt
Q: Enforce "spaces" or "tabs" only in python files? In Python, is there a mean to enforce the use of spaces or tabs indentation with a per file basis ? Well, perhaps "enforce" is too strong, more like a "recommendation". I keep receiving patch files with mixed indentation and this is annoying... (to say the least) P...
Enforce "spaces" or "tabs" only in python files?
In Python, is there a mean to enforce the use of spaces or tabs indentation with a per file basis ? Well, perhaps "enforce" is too strong, more like a "recommendation". I keep receiving patch files with mixed indentation and this is annoying... (to say the least) Python itself can tell when there is a problem, but I a...
[ "Tim Peters has written a nifty script called reindent.py which converts .py files to use 4-space indents and no tabs. It is available here, but check your distribution first -- it may have come bundled in an Examples or Tools directory. (On the latest LTS Ubuntu, it is provided by the python2.7-examples package.)\...
[ 9, 5, 2, 2 ]
[]
[]
[ "indentation", "python", "spaces", "tabs" ]
stackoverflow_0002490686_indentation_python_spaces_tabs.txt
Q: Django Template Error : Template u'base.html' cannot be extended I get this error when I run a django app (dpaste) Template error In template c:\python\projects\mycms\dpaste\templates\dpaste\base.html, error at line 1 Template u'base.html' cannot be extended, because it doesn't exist 1 {% extends "base.html" ...
Django Template Error : Template u'base.html' cannot be extended
I get this error when I run a django app (dpaste) Template error In template c:\python\projects\mycms\dpaste\templates\dpaste\base.html, error at line 1 Template u'base.html' cannot be extended, because it doesn't exist 1 {% extends "base.html" %} But the "base.html" do exist in the template directory and it has ...
[ "Your base.html template cannot extend itself. The problem lies there. Remove that line and replace it with valid html or other Django template tags (or extend some other template).\n", "A template can't extend itself. \n", "If you meant to say that:\n{% extends \"base.html\" %}\n\nis the only line in the incl...
[ 3, 1, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0001138106_django_django_templates_python.txt
Q: why my code print this when i read and write def sss(request): handle=open('b.txt','r+') handle.write("I AM NEW FILE") var=handle.read(); return HttpResponse(var) urlpatterns = patterns('', ('^$',sss), ) 1.my b.txt has nothing 2.when i run my code ,it print this : I AM NEW FILE7 ...
why my code print this when i read and write
def sss(request): handle=open('b.txt','r+') handle.write("I AM NEW FILE") var=handle.read(); return HttpResponse(var) urlpatterns = patterns('', ('^$',sss), ) 1.my b.txt has nothing 2.when i run my code ,it print this : I AM NEW FILE7 ...
[ "The only way I can repro this is to open an existing non-empty file using 'r+' (Are you absolutely sure it's empty?). In any event, opening the file in the 'w+' mode truncates it.\n", "What middle-ware are you using? I guess that you have a lot of middle-ware installed, which explains some of the garbage.\nFor d...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002491511_django_python.txt
Q: Find multiple regex in each line and skip result if one of the regex doesn't match I have a list of variables: variables = ['VariableA', 'VariableB','VariableC'] which I'm going to search for, line by line ifile = open("temp.txt",'r') d = {} match = zeros(len(variables)) for line in ifile: emptyCells=0 ...
Find multiple regex in each line and skip result if one of the regex doesn't match
I have a list of variables: variables = ['VariableA', 'VariableB','VariableC'] which I'm going to search for, line by line ifile = open("temp.txt",'r') d = {} match = zeros(len(variables)) for line in ifile: emptyCells=0 for i in range(len(variables)): regex = r'('+variables[i]+r')[:|=|\(](-?\d+(?:\....
[ "Can you edit your question to give an example of the source file, so we could test our solutions against it?\nAnyway here's a quick hack:\nfrom collections import defaultdict\nimport re\n\nvariables = ['VariableA', 'VariableB', 'VariableC']\nregexes = [re.compile(r'(%s)[:|=|\\(](-?\\d+(?:\\.\\d+)?)(?:\\))?' % (var...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002491778_python_regex.txt
Q: Use URL Fetch of Google App Engine just to call a php script I wanto call a PHP script using Google App Engine. I just want to execute the script. The script updates a couple of databases on my webhost. But I guess Google App waits for the response. Is there a way by which I can start the script. The script takes ...
Use URL Fetch of Google App Engine just to call a php script
I wanto call a PHP script using Google App Engine. I just want to execute the script. The script updates a couple of databases on my webhost. But I guess Google App waits for the response. Is there a way by which I can start the script. The script takes some time and Google App might die during that time.
[ "Can you not modify the PHP script to simply execute a background task, and return a 200 confirmation? In any case, if simply issuing a GET to that script will start a task, you can do that with AppEngine with an asynchronous URLFetch (http://code.google.com/appengine/docs/python/urlfetch/asynchronousrequests.html)...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002490592_google_app_engine_python.txt
Q: How App Engine application can get a list of instance developers How Google App instance can get the list of developers (like in Administration > Developers). Hard-coding developer's email is a bad idea because nothing lasts forever. I would like to get a solution in python (because I don't know java). A: There'...
How App Engine application can get a list of instance developers
How Google App instance can get the list of developers (like in Administration > Developers). Hard-coding developer's email is a bad idea because nothing lasts forever. I would like to get a solution in python (because I don't know java).
[ "There's no way to do this programmatically, currently. If you only need to email all the admins, however, you can use send_mail_to_admins.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002488910_google_app_engine_python.txt
Q: Python XML + Java XML interoperability I need a recommendation for a pythonic library that can marshall python objects to XML(let it be a file). I need to be able read that XML later on with Java (JAXB) and unmarshall it. I know JAXB has some issues that makes it not play nice with .NET XML libraries so a recommen...
Python XML + Java XML interoperability
I need a recommendation for a pythonic library that can marshall python objects to XML(let it be a file). I need to be able read that XML later on with Java (JAXB) and unmarshall it. I know JAXB has some issues that makes it not play nice with .NET XML libraries so a recommendation on something that actually works woul...
[ "As Ignacio says, XML is XML. On the python side, I recommend using lxml, unless you have more specific needs that are better met by another library. If you are restricted to the standard library, look at ElementTree or cElementTree, which are also excellent, and which inspired (and are functionally mostly equiva...
[ 1, 0 ]
[]
[]
[ "interop", "java", "marshalling", "python", "xml" ]
stackoverflow_0002492490_interop_java_marshalling_python_xml.txt
Q: meaning of the returned list of python json I'm new to python so I really don't know the language very well. the following example was taken from here http://docs.python.org/library/json.html >>> import json >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] what d...
meaning of the returned list of python json
I'm new to python so I really don't know the language very well. the following example was taken from here http://docs.python.org/library/json.html >>> import json >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] what does the u mean? and how do i know which elements ...
[ "It's a unicode. Iterating over the dict yields its keys:\nfor k in D:\n print k, D[k]\n\n", "Ignacio's answer a bit more verbose (no upvotes to me)\nu'something' means that 'something' is a unicode string, and not for instance an ascii string. Generally text is encoded as 8-bit characters, and you need an encod...
[ 4, 3, 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0002492099_json_python.txt
Q: django / python get image from url and display on site Given a url to an image is there a way in Django/Python to pull this image in and then display it on my site (resized if possible) Thanks A: If you just want to hotlink it print out the html snippet(<img src="http://example.com/img.png" width="100" height="1...
django / python get image from url and display on site
Given a url to an image is there a way in Django/Python to pull this image in and then display it on my site (resized if possible) Thanks
[ "If you just want to hotlink it print out the html snippet(<img src=\"http://example.com/img.png\" width=\"100\" height=\"100\" />).\nIf you want to store in at your server and resize it on the server-side you might want to look into ImageMagick or PIL for processing and urllib or pycurl for downloading.\n" ]
[ 4 ]
[]
[]
[ "django", "python", "python_imaging_library" ]
stackoverflow_0002492703_django_python_python_imaging_library.txt
Q: Python Daemon Subprocess not working at boot I am attempting to write a python daemon that will launch at boot. The goal of the script is to receive a job from our gearman load balancing server and complete the job. I am using the python-daemon module from pypi (http://pypi.python.org/pypi/python-daemon/). The n...
Python Daemon Subprocess not working at boot
I am attempting to write a python daemon that will launch at boot. The goal of the script is to receive a job from our gearman load balancing server and complete the job. I am using the python-daemon module from pypi (http://pypi.python.org/pypi/python-daemon/). The nature of the job that it is completing is converti...
[ "The issue is not related to python but rather related to the ubuntu init.d daemon. I assumed that the python script was being as a user turns out that it is not. To remedy the problem I added a sudo command to the init.d script and the subprocess starts successfully now.\n" ]
[ 0 ]
[]
[]
[ "daemon", "gearman", "imagemagick", "python" ]
stackoverflow_0002480339_daemon_gearman_imagemagick_python.txt
Q: GAE, Python 2.5, Python 2.6 Side-by-side on windows On my development system, I have Python 2.6, Django 1.1 and GAE. I have three projects running on Python 2.6 and Django 1.1. I have 1 project using GAE, Python 2.6 and Django 1.1. I have heard that my set-up for running GAE using Python 2.6 may create some he...
GAE, Python 2.5, Python 2.6 Side-by-side on windows
On my development system, I have Python 2.6, Django 1.1 and GAE. I have three projects running on Python 2.6 and Django 1.1. I have 1 project using GAE, Python 2.6 and Django 1.1. I have heard that my set-up for running GAE using Python 2.6 may create some head-scratching problems while deploying it on the producti...
[ "Use virtualenv to isolate your development environments, so you can have one running 2.5 and the others running 2.6.\nEdited to add: once 2.5 is installed, you can initialize your virtualenv to use it with the -p option:\nvirtualenv -p /path/to/python2.5/python.exe destination_dir\n\n", "Unless you are using pyt...
[ 1, 0, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002491280_django_google_app_engine_python.txt
Q: GAE AttributeError My GAE app runs fine from my computer, but when I upload it, I start getting an AttributeError, specifically: AttributeError: 'dict' object has no attribute 'item' I am using the pylast interface (an API for last.fm--link). Specifically, I am accessing a list of variables of this type: SimilarI...
GAE AttributeError
My GAE app runs fine from my computer, but when I upload it, I start getting an AttributeError, specifically: AttributeError: 'dict' object has no attribute 'item' I am using the pylast interface (an API for last.fm--link). Specifically, I am accessing a list of variables of this type: SimilarItem = _namedtuple("Simil...
[ "Yep, Python 2.6 is mostly backwards-compatible to 2.5 -- this means that what runs in 2.5 will mostly run in 2.6. But you seem to misunderstand what backwards means -- it's the antonym of forwards, meaning that it's perfectly possible that what runs in 2.6 (if it uses new features that are in 2.6 but were not in ...
[ 4, 3 ]
[]
[]
[ "attributeerror", "google_app_engine", "python" ]
stackoverflow_0002493072_attributeerror_google_app_engine_python.txt
Q: Renaming a pylons controller Is there an automatic way I can use to rename a pylons controller? If I have to rename the controller manually which all files and filenames do I have to change. Thank you much! A: You need to rename the file containing the controller, as well as the name of the controller class itse...
Renaming a pylons controller
Is there an automatic way I can use to rename a pylons controller? If I have to rename the controller manually which all files and filenames do I have to change. Thank you much!
[ "You need to rename the file containing the controller, as well as the name of the controller class itself within the file. As far as I know there is no automatic way to do this, although if you have many controllers to rename it might be worth the time to write a special script to do it for you.\nAs discussed on t...
[ 1 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0002492692_pylons_python.txt
Q: download mbox files over https using python I was trying to find the right module for downloading kernel patches from kernel.org site For example,to download the file at https://patchwork.kernel.org/patch/62948/mbox/ I understand urlgrabber has a problem with https on debian. urllib2 seems to have problem with th...
download mbox files over https using python
I was trying to find the right module for downloading kernel patches from kernel.org site For example,to download the file at https://patchwork.kernel.org/patch/62948/mbox/ I understand urlgrabber has a problem with https on debian. urllib2 seems to have problem with this url as well (says getaddrinfo failed, even tho...
[ "Curious, this url should work fine (though I've tried it on Mac OS X only). I used this very simple test in my code:\nimport urllib\nget_url = lambda url : urllib.urlopen(url).read()\ndata = get_url('https://patchwork.kernel.org/patch/62948/mbox/')\n\nOf course, this loads the result into memory - but it does work...
[ 1, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0002493394_python_urllib2.txt
Q: Dictionaries with tuples that have lists as values How can i have a tuple that has a list as a value. F.x. if i want to have a structure like this. ( Somechar , Somelist[] ) And how would i iterate through a dictionary of these things? A: You can add a list to a tuple just like any other element. From a dictiona...
Dictionaries with tuples that have lists as values
How can i have a tuple that has a list as a value. F.x. if i want to have a structure like this. ( Somechar , Somelist[] ) And how would i iterate through a dictionary of these things?
[ "You can add a list to a tuple just like any other element. From a dictionary, you can access each element of the tuple by indexing it like so: d[key][0] and d[key][1]. Here is an example:\n\n>>> d = {}\n>>> d[\"b\"] = ('b', [2])\n>>> d[\"a\"] = ('a', [1])\n>>> for k in d:\n... print(d[k][0], d[k][1])\n...\n('a...
[ 2, 0, 0 ]
[]
[]
[ "dictionary", "list", "python", "tuples" ]
stackoverflow_0002493425_dictionary_list_python_tuples.txt
Q: How to make Twisted use Python logging? I've got a project where I'm using Twisted for my web server. When exceptions occur (such as network errors), it's printing to the console. I've already got logging through Python's built-in log module - is there any way to tell the reactor to use that instead? What's the u...
How to make Twisted use Python logging?
I've got a project where I'm using Twisted for my web server. When exceptions occur (such as network errors), it's printing to the console. I've already got logging through Python's built-in log module - is there any way to tell the reactor to use that instead? What's the usual pattern for this?
[ "Found it. It's actually quite easy:\nfrom twisted.python import log\nobserver = log.PythonLoggingObserver(loggerName='logname')\nobserver.start()\n\nYou just set loggerName to the same logger name that you're using in logging.getLogger().\n", "You can use twisted.python.log. For example:\nfrom twisted.python im...
[ 25, 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0002493644_python_twisted.txt
Q: Resulting .exe from PyInstaller with wxPython crashing I'm trying to compile a very simple wxPython script into an executable by using PyInstaller on Windows Vista. The Python script is nothing but a Hello World in wxPython. I'm trying to get that up and running as a Windows executable before I add any of the feat...
Resulting .exe from PyInstaller with wxPython crashing
I'm trying to compile a very simple wxPython script into an executable by using PyInstaller on Windows Vista. The Python script is nothing but a Hello World in wxPython. I'm trying to get that up and running as a Windows executable before I add any of the features that the program needs to have. But I'm already stuck. ...
[ "On windows I have found Py2exe to be more stable and easier to use, have you tried that. \n", "I found the solution to this problem on the PyInstaller mailing list, and it's remarkably simple, only undocumented.\nPyInstaller doesn't yet support Python 2.6. The solution is to get a patch from a page which can now...
[ 0, 0 ]
[]
[]
[ "pyinstaller", "python", "wxpython" ]
stackoverflow_0002480480_pyinstaller_python_wxpython.txt
Q: Determine cluster size of file system in Python I would like to calculate the "size on disk" of a file in Python. Therefore I would like to determine the cluster size of the file system where the file is stored. How do I determine the cluster size in Python? Or another built-in method that calculates the "size on...
Determine cluster size of file system in Python
I would like to calculate the "size on disk" of a file in Python. Therefore I would like to determine the cluster size of the file system where the file is stored. How do I determine the cluster size in Python? Or another built-in method that calculates the "size on disk" will also work. I looked at os.path.getsize bu...
[ "On UNIX/Linux platforms, use Python's built-in os.statvfs. On Windows, unless you can find a third-party library that does it, you'll need to use ctypes to call the Win32 function GetDiskFreeSpace, like this:\nimport ctypes\n\nsectorsPerCluster = ctypes.c_ulonglong(0)\nbytesPerSector = ctypes.c_ulonglong(0)\nroot...
[ 6, 2 ]
[]
[]
[ "filesystems", "python" ]
stackoverflow_0002493172_filesystems_python.txt
Q: Evaluating for loops in python, containing an array with an embedded for loop I was looking at the following code in python: for ob in [ob for ob in context.scene.objects if ob.is_visible()]: pass Obviously, it's a for each loop, saying for each object in foo array. However, I'm having a bit of trouble readi...
Evaluating for loops in python, containing an array with an embedded for loop
I was looking at the following code in python: for ob in [ob for ob in context.scene.objects if ob.is_visible()]: pass Obviously, it's a for each loop, saying for each object in foo array. However, I'm having a bit of trouble reading the array. If it just had: [for ob in context.scene.objects if ob.is_visible()]...
[ "That is the syntax for list comprehension.\n", "The first ob is an expression, take this simple example:\n>>>> [ x**2 for x in range(10) if x%2 == 0 ]\n[0, 4, 16, 36, 64]\n\nWhich reads, create a list from range(10), if x is even then square it. Discard any odd value of x.\n", "It's a list comprehension. You...
[ 1, 0, 0, 0 ]
[]
[]
[ "arrays", "foreach", "list", "python" ]
stackoverflow_0002494141_arrays_foreach_list_python.txt
Q: ctypes and pointer manipulation I am dealing with image buffers, and I want to be able to access data a few lines into my image for analysis with a c library. I have created my 8-bit pixel buffer in Python using create_string_buffer. Is there a way to get a pointer to a location within that buffer without re-cre...
ctypes and pointer manipulation
I am dealing with image buffers, and I want to be able to access data a few lines into my image for analysis with a c library. I have created my 8-bit pixel buffer in Python using create_string_buffer. Is there a way to get a pointer to a location within that buffer without re-creating a new buffer? My goal is to an...
[ "create_string_buffer gives you a ctypes object (an array of chars), then byref, and I quote,\n\nReturns a light-weight pointer to obj,\n which must be an instance of a ctypes\n type. offset defaults to zero, and\n must be an integer that will be added\n to the internal pointer value.\n\nThe offset argument has...
[ 8, 0 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0002494288_ctypes_python.txt
Q: Modify default queryset in django I have added a 'cancelled' field to my model, is there a way to modify the model default query to something like cancelled=False ? without having to modify all my filter/exclude queries ? A: You can do this with a custom model manager and override the get_queryset function to al...
Modify default queryset in django
I have added a 'cancelled' field to my model, is there a way to modify the model default query to something like cancelled=False ? without having to modify all my filter/exclude queries ?
[ "You can do this with a custom model manager and override the get_queryset function to always filter canceled=False.\nclass CustomManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().filter(canceled=False)\n\nclass MyModel(models.Model):\n # Blah blah\n objects = Custom...
[ 48, 3 ]
[]
[]
[ "django", "django_models", "metaprogramming", "python" ]
stackoverflow_0002494501_django_django_models_metaprogramming_python.txt
Q: ssh-rsa public key validation using a regular expression What regular expression can I use (if any) to validate that a given string is a legal ssh rsa public key? I only need to validate the actual key - I don't care about the key type the precedes it or the username comment after it. Ideally, someone will also pr...
ssh-rsa public key validation using a regular expression
What regular expression can I use (if any) to validate that a given string is a legal ssh rsa public key? I only need to validate the actual key - I don't care about the key type the precedes it or the username comment after it. Ideally, someone will also provide the python code to run the regex validation. Thanks.
[ "A \"good enough\" check is to see if the key starts with the correct header.\nThe data portion of the keyfile should decode from base64, or it will fail with a base64.binascii.Error\nUnpack the first 4 bytes (an int), which should be 7. This is the\nlength of the following string (I guess this could be different, ...
[ 11, 2 ]
[]
[]
[ "python", "regex", "ssh_keys", "validation" ]
stackoverflow_0002494450_python_regex_ssh_keys_validation.txt
Q: How to implement a hub in Python Dear all, I need to implement a TCP server in Python which receives some data from a client and then sends this data to another client. I've tried many different implementations but no way to make it run. Any help would be really appreciated. Below is my code: import SocketServer i...
How to implement a hub in Python
Dear all, I need to implement a TCP server in Python which receives some data from a client and then sends this data to another client. I've tried many different implementations but no way to make it run. Any help would be really appreciated. Below is my code: import SocketServer import sys import threading buffer_siz...
[ "See the Twisted tutorial, and also twisted.protocols.portforward. I think that portforward module does something slightly different from what you want, it opens an outgoing connection to the destination port rather than waiting for the second client to connect, but you should be able to work from there.\n", "Ca...
[ 1, 0 ]
[]
[]
[ "client", "python", "sockets", "tcp" ]
stackoverflow_0002493888_client_python_sockets_tcp.txt
Q: Django URL regex question I had a quick question about Django URL configuration, and I guess REGEX as well. I have a small configuration application that takes in environments and artifacts in the following way: url(r'^env/(?P<env>\w+)/artifact/(?P<artifact>\w+)/$', 'config.views.ipview', name="bothlist"), Now, t...
Django URL regex question
I had a quick question about Django URL configuration, and I guess REGEX as well. I have a small configuration application that takes in environments and artifacts in the following way: url(r'^env/(?P<env>\w+)/artifact/(?P<artifact>\w+)/$', 'config.views.ipview', name="bothlist"), Now, this works fine, but what I woul...
[ "I wouldn't put such options into the URL. As you said, these are optional options, they might only change the output. They don't belong in an URL.\nYour initial regex should match URLs like:\n/env/<env>/artifact/<artifact>?verbose=1&noformat=1\n\nImho this is a much better usage of URLs\n" ]
[ 9 ]
[]
[]
[ "django", "python", "regex" ]
stackoverflow_0002494821_django_python_regex.txt
Q: How do I retrieve Hotmail contacts with python How can I retrieve contacts from hotmail with python? Is there any example? A: Hotmail: Windows Live Contacts API If a python interface doesn't exist you may have to resort to screen scraping. A: use octazen, but you have to pay for it
How do I retrieve Hotmail contacts with python
How can I retrieve contacts from hotmail with python? Is there any example?
[ "Hotmail: Windows Live Contacts API\nIf a python interface doesn't exist you may have to resort to screen scraping.\n", "use octazen, but you have to pay for it\n" ]
[ 1, 0 ]
[ "IIRC Hotmail has POP access, so just use the poplib library.\nUsage is something like this (NOT tested):\nhotmail = poplib.POP3_SSL('pop3.live.com', 995)\nhotmail.user(USERNAME)\nhotmail.pass_(PASSWORD)\n\nmessage_count = len(hotmail.list()[1])\n\nfor i in range(message_count):\n for message in hotmail.retr(i+1...
[ -1 ]
[ "hotmail", "python" ]
stackoverflow_0002165517_hotmail_python.txt
Q: Can't call a webservice method using SOAPpy I am trying to call a webservice using SOAPpy: from SOAPpy import SOAPProxy url = 'http://www.webservicex.net/WeatherForecast.asmx' server = SOAPProxy(url); print server.GetWeatherByPlaceName('Dallas'); print server.GetWeatherByZipCode ('33126'); The server call fails...
Can't call a webservice method using SOAPpy
I am trying to call a webservice using SOAPpy: from SOAPpy import SOAPProxy url = 'http://www.webservicex.net/WeatherForecast.asmx' server = SOAPProxy(url); print server.GetWeatherByPlaceName('Dallas'); print server.GetWeatherByZipCode ('33126'); The server call fails: Traceback (most recent call last): File "soap...
[ "When consuming .NET webservices, you can add a soap action override to the call. Like the following. Confirmed working code. \nimport SOAPpy\n\nns = 'http://www.webservicex.net'\nurl = '%s/WeatherForecast.asmx' % ns\n\nserver = SOAPpy.SOAPProxy( url, namespace=ns )\n#following is required for .NET\nserver.config.b...
[ 7, 4 ]
[]
[]
[ ".net", "python", "soap", "soappy", "web_services" ]
stackoverflow_0001768185_.net_python_soap_soappy_web_services.txt
Q: Writing Strings to files in python I'm getting the following error when trying to write a string to a file in pythion: Traceback (most recent call last): File "export_off.py", line 264, in execute save_off(self.properties.path, context) File "export_off.py", line 244, in save_off primary.write(file) ...
Writing Strings to files in python
I'm getting the following error when trying to write a string to a file in pythion: Traceback (most recent call last): File "export_off.py", line 264, in execute save_off(self.properties.path, context) File "export_off.py", line 244, in save_off primary.write(file) File "export_off.py", line 181, in write...
[ "What version of Python are you using? In Python 3.x a string contains Unicode text in no particular encoding. To write it out to a stream of bytes (a file) you must convert it to a byte encoding such as UTF-8, UTF-16, and so on. Fortunately this is easily done with the encode() method:\nPython 3.1.1 (...)\n>>> s =...
[ 23, 9, 2, 1, 0 ]
[]
[]
[ "file", "io", "python", "python_3.x", "string" ]
stackoverflow_0002495290_file_io_python_python_3.x_string.txt
Q: Finding longest non-repeating path through connected nodes I've been working on this for a couple of days now without success. Basically, I have a bunch of nodes arranged in a 2D matrix. Every node has four neighbors, except for the nodes on the sides and corners of the matrix, which have 3 and 2 neighbors, respec...
Finding longest non-repeating path through connected nodes
I've been working on this for a couple of days now without success. Basically, I have a bunch of nodes arranged in a 2D matrix. Every node has four neighbors, except for the nodes on the sides and corners of the matrix, which have 3 and 2 neighbors, respectively. Imagine a bunch of square cards laid out side by side in...
[ "You do know the longest path problem in a graph with cycles is NP-hard?\n", "\n...Romania has been added to the processed_countries list by Ukraine. \n\nUse separate processed_countries lists for each graph path. They say one code example is worth thousand words, so I've changed your code a little (untested):\nd...
[ 6, 2, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0002495306_pygame_python.txt
Q: Variable alpha blending in pylab How does one control the transparency over a 2D image in pylab? I'd like to give two sets of values (X,Y,Z,T) where X,Y are arrays of positions, Z is the color value, and T is the transparency to a function like imshow but it seems that the function only takes alpha as a scalar. As...
Variable alpha blending in pylab
How does one control the transparency over a 2D image in pylab? I'd like to give two sets of values (X,Y,Z,T) where X,Y are arrays of positions, Z is the color value, and T is the transparency to a function like imshow but it seems that the function only takes alpha as a scalar. As a concrete example, consider the code...
[ "One thing that you can do is modify what you put into imshow. The first variable can be grayscale values as you have used or it can be RGB or RGBA values. If you RGB/RGBA values then the cmap is ignored. So for instance,\nimshow(Z1, cmap=cm.hsv, alpha=.6, extent=extent)\n\nwill generate the same image as\nimshow(c...
[ 8 ]
[]
[]
[ "alphablending", "matplotlib", "python" ]
stackoverflow_0002495656_alphablending_matplotlib_python.txt
Q: Check if a MediaWiki page exists (Python) I'm working on a Python script that transforms this: foo bar Into this: [[Component foo]] [[bar]] The script checks (per input line) if the page "Component foo" exists. If it exists then a link to that page is created, if it doesn't exist then a direct link is created. T...
Check if a MediaWiki page exists (Python)
I'm working on a Python script that transforms this: foo bar Into this: [[Component foo]] [[bar]] The script checks (per input line) if the page "Component foo" exists. If it exists then a link to that page is created, if it doesn't exist then a direct link is created. The problem is that I need a quick & cheap way t...
[ "You can definitely use the API to check if a page exists:\n# assuming words is a list of words you wish to query for\nimport urllib\n\n# replace en.wikipedia.org with the address of the wiki you want to access\nquery = \"http://en.wikipedia.org/w/api.php?action=query&titles=%s&format=xml\" % \"|\".join(words)\npag...
[ 10, 5, 2, 1 ]
[]
[]
[ "mediawiki", "python" ]
stackoverflow_0002439824_mediawiki_python.txt
Q: Displaying a list of items vertically in a table instead of horizontally I have a list of items sorted alphabetically: mylist = [a,b,c,d,e,f,g,h,i,j] I'm able to output the list in an html table horizonally like so: | a , b , c , d | | e , f , g , h | | i , j , , | What's the algorithm to create the table ve...
Displaying a list of items vertically in a table instead of horizontally
I have a list of items sorted alphabetically: mylist = [a,b,c,d,e,f,g,h,i,j] I'm able to output the list in an html table horizonally like so: | a , b , c , d | | e , f , g , h | | i , j , , | What's the algorithm to create the table vertically like this: | a , d , g , j | | b , e , h , | | c , f , i , | I'm...
[ ">>> l = [1,2,3,4,5,6,7,8,9,10]\n>>> [l[i::3] for i in xrange(3)]\n[[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]\n\nReplace 3 by the number of lines you want as a result:\n>>> [l[i::5] for i in xrange(5)]\n[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]\n\n", "import itertools\ndef grouper(n, iterable, fillvalue=None):\n # ...
[ 9, 1, 0, 0, 0 ]
[ "int array_size = 26;\nint col_size = 4;\n\nfor (int i = 0; i <= array_size/col_size; ++i) {\n for (int j = i; j < array_size; j += col_size-1) {\n print (a[j]);\n }\n print(\"\\n\");\n}\n\n" ]
[ -1 ]
[ "html", "python", "tabular" ]
stackoverflow_0002495046_html_python_tabular.txt
Q: Filtering documents against a dictionary key in MongoDB I have a collection of articles in MongoDB that has the following structure: { 'category': 'Legislature', 'updated': datetime.datetime(2010, 3, 19, 15, 32, 22, 107000), 'byline': None, 'tags': { 'party': ['Peter Hoekstra', 'Virg Ber...
Filtering documents against a dictionary key in MongoDB
I have a collection of articles in MongoDB that has the following structure: { 'category': 'Legislature', 'updated': datetime.datetime(2010, 3, 19, 15, 32, 22, 107000), 'byline': None, 'tags': { 'party': ['Peter Hoekstra', 'Virg Bernero', 'Alma Smith', 'Mike Bouchard', 'Tom George', 'Rick Sny...
[ "If the \"geography\" field doesn't exist when there aren't any tags in it (i.e., it's created when you add a location), you could do:\ndb.articles.find({tags.geography : {$exists : true}})\n\nIf it does exists and is empty (i.e., \"geography\" : []) you should add a geography_size field or something and do:\ndb.ar...
[ 10 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0002495932_mongodb_pymongo_python.txt
Q: Django - provide additional information in template I am building an app to learn Django and have started with a Contact system that currently stores Contacts and Addresses. C's are a many to many relationship with A's, but rather than use Django's models.ManyToManyField() I've created my own link-table providing ...
Django - provide additional information in template
I am building an app to learn Django and have started with a Contact system that currently stores Contacts and Addresses. C's are a many to many relationship with A's, but rather than use Django's models.ManyToManyField() I've created my own link-table providing additional information about the link, such as what the a...
[ "In order to add extra information, you should use a ManyToMany relationship with a 'trough' extra-field :\nhttp://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships\nThis will lead to this code:\ndef contact_view_full(request, contact_id):\n c = get_object_or_404(Contact,...
[ 3 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0002495985_django_django_templates_django_views_python.txt
Q: How do I parse timezones with UTC offsets in Python? Let's say I have a timezone like "2009-08-18 13:52:54-04". I can parse most of it using a line like this: datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S") However, I can't get the timezone to work. There's a %Z that handles textual timezones ("EST", "UTC", e...
How do I parse timezones with UTC offsets in Python?
Let's say I have a timezone like "2009-08-18 13:52:54-04". I can parse most of it using a line like this: datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S") However, I can't get the timezone to work. There's a %Z that handles textual timezones ("EST", "UTC", etc) but I don't see anything that can parse "-04".
[ "Maybe you could use dateutil.parser.parse? That method is also mentioned on wiki.python.org/WorkingWithTime.\n>>> from dateutil.parser import parse\n>>> parse(\"2009-08-18 13:52:54-04\")\ndatetime.datetime(2009, 8, 18, 13, 52, 54, tzinfo=tzoffset(None, -14400))\n\n\n(is this question a duplicate?)\n", "use Babel...
[ 24, 3, 0, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0001302161_datetime_python.txt
Q: Exception_Record in python2.5 problem I'm using Python2.5 & the following code produce 2 errors. Can any body help me? class EXCEPTION_RECORD(Structure): _fields_ = [ ("ExceptionCode", DWORD), ("ExceptionFlags", DWORD), ("ExceptionRecord", POINTER(EXCEPTION_RECORD)), ("Exception...
Exception_Record in python2.5 problem
I'm using Python2.5 & the following code produce 2 errors. Can any body help me? class EXCEPTION_RECORD(Structure): _fields_ = [ ("ExceptionCode", DWORD), ("ExceptionFlags", DWORD), ("ExceptionRecord", POINTER(EXCEPTION_RECORD)), ("ExceptionAddress", LPVOID), ("NumberParamete...
[ "Apparently, you can't refer to a class type while defining a class, e.g.:\n>>> class C:\n f = C\n\n\n\nTraceback (most recent call last):\n File \"<pyshell#17>\", line 1, in <module>\n class C:\n File \"<pyshell#17>\", line 2, in C\n f = C\nNameError: name 'C' is not defined\n\nHowever, you can work aro...
[ 2, 2, 0 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0002496258_python_winapi.txt
Q: SelfReferenceProperty vs. ListProperty Google App Engine I am experimenting with the Google App Engine and have a question. For the sake of simplicity, let's say my app is modeling a computer network (a fairly large corporate network with 10,000 nodes). I am trying to model my Node class as follows: class Node(db...
SelfReferenceProperty vs. ListProperty Google App Engine
I am experimenting with the Google App Engine and have a question. For the sake of simplicity, let's say my app is modeling a computer network (a fairly large corporate network with 10,000 nodes). I am trying to model my Node class as follows: class Node(db.Model): name = db.StringProperty() neighbors = db.Sel...
[ "Re 1, yes (if I understand correctly what you're asking): for each property in a model, each instance of the model (AKA \"entity\") has one value for that property. So e.g. an IntegerProperty has one integer value for a given entity, a SelfReferenceProperty has one value (internally a key string) for a given enti...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002495709_google_app_engine_python.txt
Q: Asynchronous background processes in Python? I have been using this as a reference, but not able to accomplish exactly what I need: Calling an external command in Python I also was reading this: http://www.python.org/dev/peps/pep-3145/ For our project, we have 5 svn checkouts that need to update before we can depl...
Asynchronous background processes in Python?
I have been using this as a reference, but not able to accomplish exactly what I need: Calling an external command in Python I also was reading this: http://www.python.org/dev/peps/pep-3145/ For our project, we have 5 svn checkouts that need to update before we can deploy our application. In my dev environment, where s...
[ "Don't use shell=True. It will needlessy invoke the shell to call your svn program, and that will give you the shell's return code instead of svn's.\nrepos = ['/repo1', '/repo2', '/repo3']\n# launch 3 async calls:\nprocs = [subprocess.Popen(['svn', 'update', repo]) for repo in repos]\n# wait.\nfor proc in procs:\n ...
[ 18 ]
[]
[]
[ "asynchronous", "background_process", "python" ]
stackoverflow_0002496772_asynchronous_background_process_python.txt
Q: Python.expat can't parse XML file with bad symbols. How to go around? I'm trying to parse an XML file (OSM data) with expat, and there are lines with some Unicode characters that expat can't parse: <tag k="name" v="абвгдежзиклмнопр�?туфхцчшщьыъ�?ю�?�?БВГДЕЖЗИКЛМ�?ОПРСТУФХЦЧШЩЬЫЪЭЮЯ" /> <tag k="name" v="Cin\x8e? R...
Python.expat can't parse XML file with bad symbols. How to go around?
I'm trying to parse an XML file (OSM data) with expat, and there are lines with some Unicode characters that expat can't parse: <tag k="name" v="абвгдежзиклмнопр�?туфхцчшщьыъ�?ю�?�?БВГДЕЖЗИКЛМ�?ОПРСТУФХЦЧШЩЬЫЪЭЮЯ" /> <tag k="name" v="Cin\x8e? Rex" /> (XML file encoding in the opening line is "UTF-8") The file is quit...
[ "Not sure if '�' characters were introduced by copy-pasting string here,\nbut if you have them in original data, then it seems to be generator\nproblem which introduced \\uFFFD charactes as:\n\"used to replace an incoming character whose value is unknown or\nunrepresentable in Unicode\"\ncitied from:\nhttp://www.fi...
[ 1 ]
[]
[]
[ "expat_parser", "python", "unicode", "xml" ]
stackoverflow_0002495538_expat_parser_python_unicode_xml.txt
Q: add/remove items in a list I'm trying to create a player who can add and remove items from their inventory. I have everything working, I just have 1 small problem. Every time it prints the inventory, 'None' also appears. I've been messing with it to try and remove that, but no matter what I do, 'None' always appea...
add/remove items in a list
I'm trying to create a player who can add and remove items from their inventory. I have everything working, I just have 1 small problem. Every time it prints the inventory, 'None' also appears. I've been messing with it to try and remove that, but no matter what I do, 'None' always appears in the program! I know I'm ju...
[ "The problem is this statement:\nprint \"Inventory:\", player.inventory()\n\nYou're telling Python to print the value returned from player.inventory(). But your inventory() method just prints the inventory, it doesn't return anything - so the return value is implicitly None.\nYou probably want to explicitly choose ...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002496926_python.txt
Q: python duration of a file object in an argument list In the pickle module documentation there is a snippet of example code: reader = pickle.load(open('save.p', 'rb')) which upon first read looked like it would allocate a system file descriptor, read its contents and then "leak" the open descriptor for there isn't...
python duration of a file object in an argument list
In the pickle module documentation there is a snippet of example code: reader = pickle.load(open('save.p', 'rb')) which upon first read looked like it would allocate a system file descriptor, read its contents and then "leak" the open descriptor for there isn't any handle accessible to call close() upon. This got me w...
[ "\nWhat is the duration of the file\n object returned by the example code\n above?\n\nThat code does not return the file object (as the Q's title correctly says, it receives it as an argument).\nIn current CPython, the file will be closed at the time the function return (since the function doesn't stash away any ...
[ 3 ]
[]
[]
[ "internals", "python" ]
stackoverflow_0002496983_internals_python.txt
Q: How to disable Excel's auto recognition of numbers and text I used Python to generate a CSV file. But when I open it in Excel, Excel will auto recognize a string into a number if it could be converted. e.g.33E105 becomes 33*10^105, which is actually an ID, not a number. How to disable this in Excel while opening...
How to disable Excel's auto recognition of numbers and text
I used Python to generate a CSV file. But when I open it in Excel, Excel will auto recognize a string into a number if it could be converted. e.g.33E105 becomes 33*10^105, which is actually an ID, not a number. How to disable this in Excel while opening a CSV file? Or I need to resort to a excel-python library to out...
[ "You could precede it with a single quote, forcing it to text.\nA fun answer is you could keep the first eight rows blank (it only processes the first eight rows to determine data type), although I think this may blank all your data entirely. You could hide those empty rows.\n", "You have 3 options:\n\nOutput a ...
[ 4, 3, 2, 1, 0 ]
[]
[]
[ "excel", "python" ]
stackoverflow_0002496990_excel_python.txt
Q: convert a binary file in a list (python) I'd like to be able to open a binary file, and make a list (kind of array) with all the chars in, like : "\x21\x23\x22\x21\x22\x31" to ["\x21","\x23","\x22","\x21","\x22","\x31"] What would be the best solution to convert it ? Thanks ! A: You need to understand that "\x21...
convert a binary file in a list (python)
I'd like to be able to open a binary file, and make a list (kind of array) with all the chars in, like : "\x21\x23\x22\x21\x22\x31" to ["\x21","\x23","\x22","\x21","\x22","\x31"] What would be the best solution to convert it ? Thanks !
[ "You need to understand that \"\\x21\" and \"!\" are two ways of representing the same thing\nso \"\\x21\\x23\\x22\\x21\\x22\\x31\" is the same as '!#\"!\"1'\n>>> \"\\x21\\x23\\x22\\x21\\x22\\x31\" == '!#\"!\"1'\nTrue\n\n>>> infile = open('infile.txt', 'rb')\n>>> list(infile.read())\n['!', '#', '\"', '!', '\"', '1...
[ 4, 2, 1, 1 ]
[]
[]
[ "binary", "list", "python" ]
stackoverflow_0002496854_binary_list_python.txt
Q: Can I create class properties during __new__ or __init__? I want to do something like this, but I haven't had much success so far. I would like to make each attr a property that computes _lazy_eval only when accessed: class Base(object): def __init__(self): for attr in self._myattrs: setat...
Can I create class properties during __new__ or __init__?
I want to do something like this, but I haven't had much success so far. I would like to make each attr a property that computes _lazy_eval only when accessed: class Base(object): def __init__(self): for attr in self._myattrs: setattr(self, attr, property(lambda self: self._lazy_eval(attr))) ...
[ "Descriptors (such as instances of the property type) are only meaningful when they're held in the class object, not the instance object. So, you need to change the class, not the instance, and (in Python 2.6 or better) a class decorator is very handy for that purpose:\nclass Base(object):\n def _lazy_eval(self...
[ 5, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002496930_python.txt
Q: Python: Dynamic attribute name generation without exec() or eval() I'm trying to dynamically create buttons at runtime with PyQT4.7 However, this being my first python program I'm not sure how to get the functionality I want. I would like to be able to substitute a text string for an attribute name: i.e. for eac...
Python: Dynamic attribute name generation without exec() or eval()
I'm trying to dynamically create buttons at runtime with PyQT4.7 However, this being my first python program I'm not sure how to get the functionality I want. I would like to be able to substitute a text string for an attribute name: i.e. for each in xrange(4): myname = "tab1_button%s" % each #tab1_button0, tab1...
[ "If I interpreted this correctly, I think what you want is this:\nself.ui.gridLayout.addWidget(getattr(self.ui,myname))\nGive that a go. In Python the following two statements are functionally equivalent (from the link below):\nvalue = obj.attribute\nvalue = getattr(obj, \"attribute-name\")\n\nFor extra context:\n...
[ 3, 0, 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0002497168_pyqt4_python.txt
Q: read a binary file (python) I cant read a file, and I dont understand why: f = open("test/test.pdf", "r") data = list(f.read()) print data Returns : [] I would like to open a PDF, and extract every bytes, and put it in a List. What's wrong with my code ? :( Thanks, A: f = open("test/test.pdf", "rb") You must i...
read a binary file (python)
I cant read a file, and I dont understand why: f = open("test/test.pdf", "r") data = list(f.read()) print data Returns : [] I would like to open a PDF, and extract every bytes, and put it in a List. What's wrong with my code ? :( Thanks,
[ "f = open(\"test/test.pdf\", \"rb\")\n\nYou must include the pseudo-mode \"b\" for binary when reading and writing on Windows. Otherwise the OS silently translates what it considers to be \"line endings\", causing i/o corruption.\n", "Jonathan is correct that you should be opening the file in binary mode if you a...
[ 12, 1, 1, 0 ]
[]
[]
[ "file", "io", "python" ]
stackoverflow_0002497027_file_io_python.txt
Q: How to make python_select work for '$>python' command? I installed a couple of pythons in different versions with macports, and the apple python 2.6 is also working. Now I need to run a program which requires MySQLdb package support in python, and this package was installed to the python I installed by macports. T...
How to make python_select work for '$>python' command?
I installed a couple of pythons in different versions with macports, and the apple python 2.6 is also working. Now I need to run a program which requires MySQLdb package support in python, and this package was installed to the python I installed by macports. The program tells me that there is no MySQLdb installed, so I...
[ "By default, MacPorts installs user programs (or links to them) in /opt/local/bin. The MacPorts select_python command selects which python instance is linked to /opt/local/bin/python. It has no effect (nor should it) on what Apple installs in /usr/bin, which is where the Apple-supplied python and python2.x comman...
[ 7, 0, 0 ]
[]
[]
[ "macos", "mysql", "python" ]
stackoverflow_0001768881_macos_mysql_python.txt
Q: I am currently serving my static files in Django. How do I use Apache2 to do this? (r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), As you can see, I have a directory called "media" under my Django project. I would like to delete this line in my urls.py and instead us...
I am currently serving my static files in Django. How do I use Apache2 to do this?
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), As you can see, I have a directory called "media" under my Django project. I would like to delete this line in my urls.py and instead us Apache to serve my static files. What do I do to my Apache configs (which files do I ch...
[ "I would read Django's official static files docs and apache mod_python documentation.\n\nThis example sets up Django at the\n site root but explicitly disables\n Django for the media subdirectory and\n any URL that ends with .jpg, .gif or\n .png:\n\n<Location \"/\">\n SetHandler python-program\n PythonHa...
[ 4 ]
[]
[]
[ "apache", "django", "linux", "python", "unix" ]
stackoverflow_0002497485_apache_django_linux_python_unix.txt
Q: I'm making a simulated tv I need to make a tv that shows the user the channel and the volume, and shows whether or not the television is on. I have the majority of the code made, but for some reason the channels won't switch. I'm fairly unfamiliar with how properties work, and I think that's what my problem here i...
I'm making a simulated tv
I need to make a tv that shows the user the channel and the volume, and shows whether or not the television is on. I have the majority of the code made, but for some reason the channels won't switch. I'm fairly unfamiliar with how properties work, and I think that's what my problem here is. Help please. class Televisio...
[ "\nThe channel number is integer, but raw_input returns string. Should be:\nchange = int(raw_input(\"What would you like to change the channel to?\"))\n\nalso your set_channel function has this:\nchannel=self.__channel\n\nWhen it should be:\nself.__channel = choice\n\n\nThose two changes make it work.\n", "EXTRA ...
[ 5, 3 ]
[]
[]
[ "class", "properties", "python" ]
stackoverflow_0002497525_class_properties_python.txt
Q: How can I tell [G]vim where to look for python26.dll? I have a version of Vim compiled with python 2.6 support enabled (from here). however vim cannot find the python26.dll. :version confirms +python/dyn :version and gvim.exe confirms DYNAMIC_PYTHON_DLL="python26.dll" echo PATH confirms python26.dll is in the sear...
How can I tell [G]vim where to look for python26.dll?
I have a version of Vim compiled with python 2.6 support enabled (from here). however vim cannot find the python26.dll. :version confirms +python/dyn :version and gvim.exe confirms DYNAMIC_PYTHON_DLL="python26.dll" echo PATH confirms python26.dll is in the search path. (both c:\windows\system32, and C:\python26) W...
[ "Be sure that any dll you try to load is compiled for the same architecture as the exe. \ne.g. If you have x86 Vim installed. Make sure that the python dll you are loading is not x64, or vice-versa.\n" ]
[ 8 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0002497551_python_vim.txt
Q: Updating section in ConfigParser (or an alternative) I am making a plugin for another program and so I am trying to make thing as lightweight as possible. What i need to do is be able to update the name of a section in the ConfigParser's config file. [project name] author:john doe email: spam@example.com year: 20...
Updating section in ConfigParser (or an alternative)
I am making a plugin for another program and so I am trying to make thing as lightweight as possible. What i need to do is be able to update the name of a section in the ConfigParser's config file. [project name] author:john doe email: spam@example.com year: 2010 I then have text fields where user can edit project's ...
[ "ini files are probably best suited for configuring applications, with well-defined inputs and so forth. It sounds like you want a more generic serialization tool; JSON would probably work well for this. Perhaps you want to store a JSON representation of a list (hence your incrementing indices) of dicts with those ...
[ 2 ]
[]
[]
[ "configparser", "python" ]
stackoverflow_0002497717_configparser_python.txt
Q: Python overriding class (not instance) special methods How do I override a class special method? I want to be able to call the __str__() method of the class without creating an instance. Example: class Foo: def __str__(self): return 'Bar' class StaticFoo: @staticmethod def __str__(): r...
Python overriding class (not instance) special methods
How do I override a class special method? I want to be able to call the __str__() method of the class without creating an instance. Example: class Foo: def __str__(self): return 'Bar' class StaticFoo: @staticmethod def __str__(): return 'StaticBar' class ClassFoo: @classmethod def ...
[ "Special method __str__ defined in a class works only for the instances of that class, to have the different behavior for class objects you will have to do it in a metaclass of that class e.g. (python 2.5)\nclass Meta(type):\n def __str__(self):\n return \"Klass\"\n\nclass A(object):\n __metaclass__ = ...
[ 20, 1, 0 ]
[]
[]
[ "class", "overriding", "python" ]
stackoverflow_0002497790_class_overriding_python.txt
Q: creating matrix with probabilities I want to generate a matrix of NxN to test some code that I have where each row contains floats as the elements and has to add up to 1 (i.e. a row with a set of probabilities). Where it gets tricky is that I want to make sure that randomly some of the elements should be 0 (in f...
creating matrix with probabilities
I want to generate a matrix of NxN to test some code that I have where each row contains floats as the elements and has to add up to 1 (i.e. a row with a set of probabilities). Where it gets tricky is that I want to make sure that randomly some of the elements should be 0 (in fact most of the elements should be 0 exc...
[ "import random\n\nN = 10\n\nmatrix = []\n\nfor j in range(N):\n t = [int(random.random()<0.6) for i in range(N)]\n ones = t.count(1)\n row = [float(x)/ones for x in t] if ones else t\n matrix.append(row)\n\nfor r in matrix:\n print r\n\n", "By C++ array, do you mean a C array o...
[ 2, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0002497843_c++_python.txt
Q: Best way to encrypt a directory of files? I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously. How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable? Programming language doesn't matter. I am dictioned in al...
Best way to encrypt a directory of files?
I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously. How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable? Programming language doesn't matter. I am dictioned in all syntax.
[ "\nHow can I accomplish this, and WHAT IS\n the BEST encryption way to do it, if\n applicable?\n\n\ntar and gzip the directory. \nGenerate a random bit stream of equal size to the file\nRun bitwise XOR on the streams\n\nOnly truly secure method is a truly random one time pad.\n", "I still say 7-zip is the answe...
[ 4, 3, 3, 3, 2, 0 ]
[]
[]
[ ".net", "c++", "encryption", "java", "python" ]
stackoverflow_0002498009_.net_c++_encryption_java_python.txt
Q: stopping a cherrypy server over http I have a cherrypy app that I'm controlling over http with a wxpython ui. I want to kill the server when the ui closes, but I don't know how to do that. Right now I'm just doing a sys.exit() on the window close event but thats resulting in Traceback (most recent call last): F...
stopping a cherrypy server over http
I have a cherrypy app that I'm controlling over http with a wxpython ui. I want to kill the server when the ui closes, but I don't know how to do that. Right now I'm just doing a sys.exit() on the window close event but thats resulting in Traceback (most recent call last): File "ui.py", line 67, in exitevent url...
[ "How are you stopping CherryPy? By sending a SIGKILL to itself? You should send TERM instead at the least, but even better would be to call cherrypy.engine.exit() (version 3.1+). Both techniques will allow CherryPy to shut down more gracefully, which includes allowing any in-process requests (like your \"?sigkill=1...
[ 10, 3 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0002125175_cherrypy_python.txt
Q: Flash in Python I was exploring possibilities of Rich Internet applications using Python. The most awesome possibility I found was of programming in IronPython and running it as a Silverlight. Is there something similar available for Adobe AIR? I.e. programing in Python and run in Adobe AIR (Flash, that is). A: ...
Flash in Python
I was exploring possibilities of Rich Internet applications using Python. The most awesome possibility I found was of programming in IronPython and running it as a Silverlight. Is there something similar available for Adobe AIR? I.e. programing in Python and run in Adobe AIR (Flash, that is).
[ "You can use libming to generate Macromedia Flash files, it has Python bindings too, you can see some Python examples at \"Python, Ming and Flash\".\nAnother library is \"SSWF -- A complete library to generate Flash animations\", which is in C, so can be easily used from Python if needed.\n", "There are plenty of...
[ 1, 1 ]
[]
[]
[ "air", "python", "rich_internet_application" ]
stackoverflow_0002498269_air_python_rich_internet_application.txt
Q: Python: Pretty printing a xml file directly from a tar.gz package This is the first Python script I've tried to create. I'm reading a xml file from a tar.gz package and then I want to pretty print it. However I can't seem to turn it from a file-like object to a string. I've tried to do it a few different ways incl...
Python: Pretty printing a xml file directly from a tar.gz package
This is the first Python script I've tried to create. I'm reading a xml file from a tar.gz package and then I want to pretty print it. However I can't seem to turn it from a file-like object to a string. I've tried to do it a few different ways including str(), tostring(), etc but nothing is working for me. For testi...
[ "Untested but you probably just need a read() call on the file-like object returned by tarfile, e.g.:\nmyfile = getfile.read()\n\n" ]
[ 2 ]
[]
[]
[ "pretty_print", "python", "tar" ]
stackoverflow_0002498732_pretty_print_python_tar.txt
Q: Django parallel arrays in a template I have 2 arrays that I would like to render in a template, one is the data to be output, the other is a formset for deleting items. since it seems django does not support boolean operators in the template tag, I have tried packaging the items, but they return the first item and...
Django parallel arrays in a template
I have 2 arrays that I would like to render in a template, one is the data to be output, the other is a formset for deleting items. since it seems django does not support boolean operators in the template tag, I have tried packaging the items, but they return the first item and the first form in 2 rows only. How does ...
[ "Use zip builtin. If both post and delpostformset.forms are iterables, zip will return a list of tuples. In view:\npost_and_form = zip(post, delpostformset.forms)\n\nand in template:\n{% for post, form in post_and_form %}\n{% endfor %}\n\n" ]
[ 8 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0002498870_django_django_templates_django_views_python.txt
Q: How to extract the first non-Null match from a group of regexp matches in Python? Suppose I have a regular expression (a)|(b)|(c)|(d). If I apply it to text 'foobar' I get a match object >>> compiled = re.compile('(a)|(b)|(c)|(d)') >>> compiled.search('foobar').groups() (None, 'b', None, None) How do I extract th...
How to extract the first non-Null match from a group of regexp matches in Python?
Suppose I have a regular expression (a)|(b)|(c)|(d). If I apply it to text 'foobar' I get a match object >>> compiled = re.compile('(a)|(b)|(c)|(d)') >>> compiled.search('foobar').groups() (None, 'b', None, None) How do I extract the 'b' from here? Or in general, how do I extract the first match from an unknown number...
[ ">>> g = (None, 'b', None, None)\n>>> next(x for x in g if x is not None)\n'b'\n\n>>> g = (None, None, None)\n>>> next((x for x in g if x is not None), \"default\") # try this with filter :)\n'default'\n\n>>> g = (None, None, None) # so you know what happens, and what you could catch\n>>> next(x for x in g if x i...
[ 4, 1, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002498935_python_regex.txt
Q: OSX : Defining a new URL handler that points straight at a Python script I'm trying to define a new URL handler under OSX that will point at a python script. I've wrapped the Python script up into an applet (right-clicked on the .py, and gone Open With -> Build Applet) I've added the following into the applet's In...
OSX : Defining a new URL handler that points straight at a Python script
I'm trying to define a new URL handler under OSX that will point at a python script. I've wrapped the Python script up into an applet (right-clicked on the .py, and gone Open With -> Build Applet) I've added the following into the applet's Info.plist: <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundle...
[ "After a lot of messing around, I've managed to get this working under OSX...\nThis is how I'm doing it:\nin the AppleScript Script Editor, write the following script:\non open location this_URL\n do shell script \"/scripts/runLocalCommand.py '\" & this_URL & \"'\"\nend open location\n\nIf you want to make sure ...
[ 16 ]
[]
[]
[ "handler", "macos", "python", "url" ]
stackoverflow_0002418910_handler_macos_python_url.txt
Q: Django: request object to template context transparancy I want to include an initialized data structure in my request object, making it accessible in the context object from my templates. What I'm doing right now is passing it manually and tiresome within all my views: render_to_response(...., ( {'menu': RequestCo...
Django: request object to template context transparancy
I want to include an initialized data structure in my request object, making it accessible in the context object from my templates. What I'm doing right now is passing it manually and tiresome within all my views: render_to_response(...., ( {'menu': RequestContext(request)})) The request object contains the key, value...
[ "To accomplish this, you will probably have to create your own middleware. That way, you have full control of the request, both before and after the view function.\nMiddleware is a very powerful concept, and not as hard to implement as it could seem, but don’t overdo it – it makes it hard to follow the program flow...
[ 1, 0 ]
[]
[]
[ "django", "django_context", "python", "request", "templates" ]
stackoverflow_0002498582_django_django_context_python_request_templates.txt
Q: Segment string into array, regex? I have a string which looks like this: "[segment1][segment2][segment2]" What I'd like is to be able to split the string into an array, so I'd end up with: Array[0] = "segment1", Array[1] = "segment2", Array[2] = "segment3" I've tried using the string split function, but it doesn...
Segment string into array, regex?
I have a string which looks like this: "[segment1][segment2][segment2]" What I'd like is to be able to split the string into an array, so I'd end up with: Array[0] = "segment1", Array[1] = "segment2", Array[2] = "segment3" I've tried using the string split function, but it doesn't seem to do exactly what I want. I wa...
[ "You could take the slice of the string without the first and last characters, then split on ][:\ns = \"[segment1][segment2][segment2]\"\ns[1:-1].split('][')\n\noutputs\n['segment1', 'segment2', 'segment2']\n\n", "You could use the re.split() function:\nsubject = \"[segment1][segment2][segment2]\"\nreobj = re.com...
[ 4, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002499865_python_regex.txt
Q: Faster float to int conversion in Python Here's a piece of code that takes most time in my program, according to timeit statistics. It's a dirty function to convert floats in [-1.0, 1.0] interval into unsigned integer [0, 2**32]. How can I accelerate floatToInt? piece = [] rng = range(32) for i in rng: piece.a...
Faster float to int conversion in Python
Here's a piece of code that takes most time in my program, according to timeit statistics. It's a dirty function to convert floats in [-1.0, 1.0] interval into unsigned integer [0, 2**32]. How can I accelerate floatToInt? piece = [] rng = range(32) for i in rng: piece.append(1.0/2**i) def floatToInt(x): n = x ...
[ "Did you try the obvious one?\ndef floatToInt(x):\n return int((x+1.0) * (2**31))\n\n" ]
[ 4 ]
[]
[]
[ "binary_data", "floating_point", "python" ]
stackoverflow_0002499933_binary_data_floating_point_python.txt
Q: in Python find number of same elements in 2 lists In Python if I have 2 lists say: l1 = ['a', 'b', 'c', 'd'] l2 = ['c', 'd', 'e'] is there a way to find out how many elements they have the same. In the case about it would be 2 (c and d) I know I could just do a nested loop but is there not a built in function lik...
in Python find number of same elements in 2 lists
In Python if I have 2 lists say: l1 = ['a', 'b', 'c', 'd'] l2 = ['c', 'd', 'e'] is there a way to find out how many elements they have the same. In the case about it would be 2 (c and d) I know I could just do a nested loop but is there not a built in function like in php with the array_intersect function Thanks
[ "You can use a set intersection for that :)\nl1 = ['a', 'b', 'c', 'd']\nl2 = ['c', 'd', 'e']\nset(l1).intersection(l2)\nset(['c', 'd'])\n\n", ">>> l1 = ['a', 'b', 'c', 'd']\n>>> l2 = ['c', 'd', 'e']\n>>> set(l1) & set(l2)\nset(['c', 'd'])\n\n", "If you only have unique elements, you can use the set data type an...
[ 10, 6, 5, 1 ]
[]
[]
[ "array_intersect", "arrays", "python" ]
stackoverflow_0002500124_array_intersect_arrays_python.txt
Q: Pylons and multiple forms per page I've got a web page I'm generating with Pylons and the evoque templating tool. I'm trying to generate a page with multiple forms per page (one form is part of a base template that becomes part of every page). I'm having a problem as I seemingly can only get the form element value...
Pylons and multiple forms per page
I've got a web page I'm generating with Pylons and the evoque templating tool. I'm trying to generate a page with multiple forms per page (one form is part of a base template that becomes part of every page). I'm having a problem as I seemingly can only get the form element values for one form; whenever I try to get th...
[ "You will only get the form values for the form that was posted in the request(ie: whichever submit button the user clicked), that's how html works. \n", "Yes (to iterate Tom's answer), HTML is designed to explicitly only allow a single form to be submitted at a time. Plus, forms may not be nested, so no confusio...
[ 1, 0 ]
[]
[]
[ "forms", "html", "pylons", "python" ]
stackoverflow_0002097556_forms_html_pylons_python.txt
Q: QTableWidget signal cellChanged(): distinguish between user input and change by routines i am using PyQt but my question is a general Qt one: I have a QTableWidget that is set up by the function updateTable. It writes the data from DATASET to the table when it is called. Unfortunately this causes my QTableWidget t...
QTableWidget signal cellChanged(): distinguish between user input and change by routines
i am using PyQt but my question is a general Qt one: I have a QTableWidget that is set up by the function updateTable. It writes the data from DATASET to the table when it is called. Unfortunately this causes my QTableWidget to emit the signal cellChanged() for every cell. The signal cellChanged() is connected to a fun...
[ "In similar situation I've just used\nbool QObject::blockSignals ( bool block )\nbool QObject::signalsBlocked () const\n\nBlock signals before setting up the table, then unblock:\nmyTable.blockSignals(True)\n#blah-blah..\nmyTable.blockSignals(False)\n\n", "It seems, that this is the only signal in QTableWidget at...
[ 8, 1, 1 ]
[]
[]
[ "pyqt", "python", "qt", "qtablewidget", "signals" ]
stackoverflow_0002431844_pyqt_python_qt_qtablewidget_signals.txt
Q: In Elixir or SQLAlchemy, is there a way to also store a comment for a/each field in my entities? Our project is basically a web interface to several systems of record. We have many tables mapped, and the names of each column aren't as well named and intuitive as we'd like... The users would like to know what data ...
In Elixir or SQLAlchemy, is there a way to also store a comment for a/each field in my entities?
Our project is basically a web interface to several systems of record. We have many tables mapped, and the names of each column aren't as well named and intuitive as we'd like... The users would like to know what data fields are available (i.e. what's been mapped from the database). But, it's pointless to just give the...
[ "Doing some research thru the SQLAlchemy documentation, my buddy and I found a line that says the Column object has a default dictionary called info that is a space to store \"application specific data.\" So, in my case, I can just doing something like:\nclass SegregationCode(Entity):\n using_options(tablename=\...
[ 1 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0002499821_python_python_elixir_sqlalchemy.txt
Q: Spaceship objects I'm trying to make a program which creates a spaceship and I'm using the status() method to display the ship's name and fuel values. However, it doesn't seem to be working. I think I may have messed something up with the status() method. I'm also trying to make it so that I can change the fuel va...
Spaceship objects
I'm trying to make a program which creates a spaceship and I'm using the status() method to display the ship's name and fuel values. However, it doesn't seem to be working. I think I may have messed something up with the status() method. I'm also trying to make it so that I can change the fuel values, but I don't want ...
[ "In your status method self is not defined, because you made it a static method. It makes more sense to make it non-static, since every ship has its individual name. So just say\ndef status(self):\n print \"Name: \", self.name\n print \"Fuel level: \", self.fuel\n\nand later call\nship1.status()\nship2.status...
[ 4, 4 ]
[]
[]
[ "object", "python", "static_methods" ]
stackoverflow_0002500584_object_python_static_methods.txt
Q: Nose Tests - File Uploads How would one go about testing a Pylons controller (using Nose Tests) that takes a file upload as a POST parameter? A: Like this: class TestUploadController(TestController): // .... def test_upload_files(self): """ Check that upload of text file works. """ file...
Nose Tests - File Uploads
How would one go about testing a Pylons controller (using Nose Tests) that takes a file upload as a POST parameter?
[ "Like this:\nclass TestUploadController(TestController):\n // ....\n def test_upload_files(self):\n \"\"\" Check that upload of text file works. \"\"\"\n\n files = [(\"Filedata\", \"filename.txt\", \"contents of the file\")]\n res = self.app.post(\"/my/upload/path\", upload_files = files)...
[ 4 ]
[]
[]
[ "nosetests", "pylons", "python", "unit_testing" ]
stackoverflow_0002488978_nosetests_pylons_python_unit_testing.txt
Q: Programmatically specifying Django model attributes I would like to add attributes to a Django models programmatically. At class creation time (the time of the definition of the model class). The model is not going to change after that in run time. For instance, lets say I want to define a Car model class and want...
Programmatically specifying Django model attributes
I would like to add attributes to a Django models programmatically. At class creation time (the time of the definition of the model class). The model is not going to change after that in run time. For instance, lets say I want to define a Car model class and want to add one price attribute (database column) per currenc...
[ "My solution is something which is bad from various reasons, but it works:\nfrom django.db import models\n\ncurrencies = [\"EUR\", \"USD\"]\n\nclass Car(models.Model):\n\n name = models.CharField(max_length=50)\n\n for currency in currencies:\n locals()['price_%s' % currency.lower()] = models.IntegerFi...
[ 5, 4, 2, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002501173_django_django_models_python.txt
Q: String comparison in Numpy In the following example In [8]: import numpy as np In [9]: strings = np.array(['hello ', 'world '], dtype='|S10') In [10]: strings == 'hello' Out[10]: array([False, False], dtype=bool) The comparison fails because of the whitespace. Is there a Numpy built-in function that does ...
String comparison in Numpy
In the following example In [8]: import numpy as np In [9]: strings = np.array(['hello ', 'world '], dtype='|S10') In [10]: strings == 'hello' Out[10]: array([False, False], dtype=bool) The comparison fails because of the whitespace. Is there a Numpy built-in function that does the equivalent of In [12]: np.ar...
[ "Numpy provides vectorised string operations for arrays similar to Python's string methods. They are in the numpy.char module.\nhttp://docs.scipy.org/doc/numpy/reference/routines.char.html\nimport numpy as np\n\nstrings = np.array(['hello ', 'world '], dtype='|S10')\n\nprint np.char.strip(strings) == 'hello'\...
[ 11 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002501362_numpy_python.txt
Q: What can be done in Cpython that can not be done in IronPython? What can be done in Cpython that can not be done in IronPython? A: If you are writing "100% pure Python", you can do everything that CPython can do in IronPython. The problem comes in when you want to use a third-party package. Many of them will h...
What can be done in Cpython that can not be done in IronPython?
What can be done in Cpython that can not be done in IronPython?
[ "If you are writing \"100% pure Python\", you can do everything that CPython can do in IronPython. The problem comes in when you want to use a third-party package. Many of them will have written their performance-intensive portions in C, and rely on the Python/C API (e.g. NumPy).\nAs a glue language for hooking t...
[ 4 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0002501492_ironpython_python.txt
Q: add a decorate function to a class I have a decorated function (simplified version): class Memoize: def __init__(self, function): self.function = function self.memoized = {} def __call__(self, *args, **kwds): hash = args try: return self.memoized[hash] ex...
add a decorate function to a class
I have a decorated function (simplified version): class Memoize: def __init__(self, function): self.function = function self.memoized = {} def __call__(self, *args, **kwds): hash = args try: return self.memoized[hash] except KeyError: self.memoized...
[ "The problem is that you have defined your own callable class then tried to use it as a method. When you use a function as an attribute, accessing the function as an attribute calls it its __get__ method to return something other than the function itself—the bound method. When you have your own class without defini...
[ 3 ]
[]
[]
[ "class", "decorator", "descriptor", "python" ]
stackoverflow_0002501529_class_decorator_descriptor_python.txt
Q: How to step through debug twisted? I'd like to be able to debug Punjab, a twisted python application, in Netbeans so that I can step through the code. How can I do that? Alternatively, how could I do it in a different debugger? A: Since you're trying to debug a twisted application, you have a few options: If yo...
How to step through debug twisted?
I'd like to be able to debug Punjab, a twisted python application, in Netbeans so that I can step through the code. How can I do that? Alternatively, how could I do it in a different debugger?
[ "Since you're trying to debug a twisted application, you have a few options:\n\nIf you're running via twistd you can use the -b command-line options:\n -b, --debug run the application in the Python Debugger (implies\n nodaemon), sending SIGUSR2 will drop into debugger\n\nYou ca...
[ 10 ]
[]
[]
[ "debugging", "netbeans", "python", "twisted" ]
stackoverflow_0002501136_debugging_netbeans_python_twisted.txt
Q: format printing How to format printing stmt in python? print"---------------------------------" print"client:mount-point:logfile:status" print"---------------------------------" print clientname,mntpt,logfile,status Currently it prints something like this : --------------------------------- client:mount-poin...
format printing
How to format printing stmt in python? print"---------------------------------" print"client:mount-point:logfile:status" print"---------------------------------" print clientname,mntpt,logfile,status Currently it prints something like this : --------------------------------- client:mount-point:logfile:status ---...
[ "Take a look at string formatting : http://docs.python.org/release/2.5.2/lib/typesseq-strings.html\n", "If you're trying to format a table, consider using other software for table formatting.\nAs an example, you can produce HTML with the print statements and view the table with a browser. Another option is to gen...
[ 1, 0, 0 ]
[]
[]
[ "printing", "python" ]
stackoverflow_0002499917_printing_python.txt
Q: Printing elements out of list I have a certain check to be done and if the check satisfies, I want the result to be printed. Below is the code: import string import codecs import sys y=sys.argv[1] list_1=[] f=1.0 x=0.05 write_in = open ("new_file.txt", "w") write_in_1 = open ("new_file_1.txt", "w") ligand_file=op...
Printing elements out of list
I have a certain check to be done and if the check satisfies, I want the result to be printed. Below is the code: import string import codecs import sys y=sys.argv[1] list_1=[] f=1.0 x=0.05 write_in = open ("new_file.txt", "w") write_in_1 = open ("new_file_1.txt", "w") ligand_file=open( y, "r" ) #Open the receptor.txt...
[ "To convert a list of strings to a single string with spaces in between the lists's items, use ' '.join(seq).\n>>> ' '.join(['1','2','3'])\n'1 2 3'\n\nYou can replace ' ' with whatever string you want in between the items.\n", "Mark Rushakoff seems to have solved your immediate problem, but there are some other i...
[ 9, 2 ]
[]
[]
[ "list", "printing", "python" ]
stackoverflow_0002501675_list_printing_python.txt
Q: Reading UDP Packets I am having some trouble dissecting a UDP packet. I am receiving the packets and storing the data and sender-address in variables 'data' and 'addr' with: data,addr = UDPSock.recvfrom(buf) This parses the data as a string, that I am now unable to turn into bytes. I know the structure of the dat...
Reading UDP Packets
I am having some trouble dissecting a UDP packet. I am receiving the packets and storing the data and sender-address in variables 'data' and 'addr' with: data,addr = UDPSock.recvfrom(buf) This parses the data as a string, that I am now unable to turn into bytes. I know the structure of the datagram packet which is a t...
[ "An unsigned int32 is 4 bytes long, so you have to feed 4 bytes into struct.unpack.\nReplace\nmybytes = data[16:19]\n\nwith\nmybytes = data[16:20]\n\n(right number is the first byte not included, i.e. range(16,19) = [16,17,18]) and you should be good to go.\n" ]
[ 3 ]
[]
[]
[ "networking", "python", "udp" ]
stackoverflow_0002501882_networking_python_udp.txt
Q: Python 2.5 fails on a datetime.strptime format I have seen several questions with people asking about the same problem but none of the answers are helping me. I'm receiving this error: pydev debugger: starting Traceback (most recent call last): >>> File "/usr/local/zend/apache2/htdocs/pyth/src/conn.py", line...
Python 2.5 fails on a datetime.strptime format
I have seen several questions with people asking about the same problem but none of the answers are helping me. I'm receiving this error: pydev debugger: starting Traceback (most recent call last): >>> File "/usr/local/zend/apache2/htdocs/pyth/src/conn.py", line 23, in <module> userConnDate = datetime.strptim...
[ "you are using %y (which matches a 2 digit year).\ntry with %Y, which matches a 4 digit year (like your 2010)\n", "Try using the a capital Y - '%Y' to match a 4-digit year.\n" ]
[ 3, 1 ]
[]
[]
[ "python", "strptime" ]
stackoverflow_0002502123_python_strptime.txt
Q: Profiling shared library/plugins written in C++ for Python? I've got a C++ library that lets me write plugins in C++ and then automatically exposes them to python. I'm working on some networking stuff in a plugin and I'd like to profile it with something like gprof, but simply compiling with -pg and running the p...
Profiling shared library/plugins written in C++ for Python?
I've got a C++ library that lets me write plugins in C++ and then automatically exposes them to python. I'm working on some networking stuff in a plugin and I'd like to profile it with something like gprof, but simply compiling with -pg and running the plugin via python doesn't generated the necessary profiling data. ...
[ "I've found valgrind's cachegrind with KCachegrind to be helpful in analysis of un-prepared (e.g. no gprof code embedded) binaries.\n" ]
[ 1 ]
[]
[]
[ "c++", "profile", "python" ]
stackoverflow_0002502262_c++_profile_python.txt
Q: Implementing pyglet breaks my once working framebuffer OpenGL code This question repeats my earlier one but my earlier one was a failure because I didn't copy some vital information correctly, so I have to redo it. I'm getting an error with a call to an OpenGL function. Maybe pyglet isn't initialising OpenGL corre...
Implementing pyglet breaks my once working framebuffer OpenGL code
This question repeats my earlier one but my earlier one was a failure because I didn't copy some vital information correctly, so I have to redo it. I'm getting an error with a call to an OpenGL function. Maybe pyglet isn't initialising OpenGL correctly? The error happens with a simple function that worked before: def ...
[ "glBindFramebufferEXT expects pointer to a buffer. AFAIK, you have to use ctypes in this case.\nfrom pyglet.gl import *\nfrom ctypes import c_uint, byref\n\nfb = c_uint()\nglGenFramebuffersEXT(1, byref(fb))\nglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb) \n\nSearch pyglet mailing list for better examples. And BTW:\n>...
[ 1 ]
[]
[]
[ "framebuffer", "opengl", "pyglet", "pyopengl", "python" ]
stackoverflow_0002502362_framebuffer_opengl_pyglet_pyopengl_python.txt
Q: What are some strategies to add spell checking to a Google App Engine program? I'm working on a Google App Engine program that will require some basic spell checking features. Normally iSpell or it's cousins would be options, but I'm not sure that will work in GEA. Are there other strategies/tools that would work ...
What are some strategies to add spell checking to a Google App Engine program?
I'm working on a Google App Engine program that will require some basic spell checking features. Normally iSpell or it's cousins would be options, but I'm not sure that will work in GEA. Are there other strategies/tools that would work in that environment?
[ "A very minimal, pure-Python spell checker can be found here: http://norvig.com/spell-correct.html\nThe big.txt file Norvig uses to train his spell checker is too large to upload to App Engine at 6.2 megabytes, but the NWORDS dict that results from training is only ~650K when pickled. So one solution might be to p...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python", "spell_checking" ]
stackoverflow_0002500093_google_app_engine_python_spell_checking.txt
Q: GAE Datastore Put() def post(self): update = self.request.get('update') if users.get_current_user(): if update: personal = db.GqlQuery("SELECT * FROM Personal WHERE __key__ = :1", db.Key(update)) personal.name = self.request.get('name') personal.gender = self.r...
GAE Datastore Put()
def post(self): update = self.request.get('update') if users.get_current_user(): if update: personal = db.GqlQuery("SELECT * FROM Personal WHERE __key__ = :1", db.Key(update)) personal.name = self.request.get('name') personal.gender = self.request.get('gender') ...
[ "There's no need to do a query when you know the key: Simply call db.get() on the key to retrieve it directly, which is much faster than doing a query.\nAs to why you're creating a new record each time, it looks like you're not passing in 'update' to your page correctly. Try logging the query string parameters to s...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002498264_google_app_engine_google_cloud_datastore_python.txt
Q: Reducing size of a character array in Numpy Given a character array: In [21]: x = np.array(['a ','bb ','cccc ']) One can remove the whitespace using: In [22]: np.char.strip(x) Out[22]: array(['a', 'bb', 'cccc'], dtype='|S8') but is there a way to also shrink the width of the column to the minimu...
Reducing size of a character array in Numpy
Given a character array: In [21]: x = np.array(['a ','bb ','cccc ']) One can remove the whitespace using: In [22]: np.char.strip(x) Out[22]: array(['a', 'bb', 'cccc'], dtype='|S8') but is there a way to also shrink the width of the column to the minimum required size, in the above case |S4?
[ "Do you just want to change the data type?\nimport numpy as NP\na = NP.array([\"a\", \"bb\", \"ccc\"])\na \n# returns array(['a', 'bb', 'ccc'], dtype='|S3')\na = NP.array(a, dtype=\"|S8\") # change dtype\n# returns array(['a', 'bb', 'ccc'], dtype='|S8')\n\na = NP.array(a, dtype=\"|S3\") # change it back\n# retu...
[ 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002502235_numpy_python.txt
Q: Simple forloop - Python this is probably too simple of a question, but here I go. I have paginated items, each page contains 100 items. The program fetches items till it reaches the item index specified within item_num This is what I have: item_num = 56 range(0, item_num/100 + (item_num%100 > 0)): get_next_100(...
Simple forloop - Python
this is probably too simple of a question, but here I go. I have paginated items, each page contains 100 items. The program fetches items till it reaches the item index specified within item_num This is what I have: item_num = 56 range(0, item_num/100 + (item_num%100 > 0)): get_next_100() I'm not really sure about...
[ "You seem to be trying to call the function zero times if item_num is 0, once if item_num is 1 to 100, twice if item_num is between 101 and 200, etc...\nA simpler way to write this is:\nn = 0\nwhile n < item_num:\n get_next_100()\n n += 100\n\nOr you could do it as a for loop:\nfor _ in range(0, item_num, 100):...
[ 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0002503543_python.txt
Q: python design patterns I am looking for any resources that gives examples of Best Practices, Design patterns and the SOLID principles using Python. A: Some overlap in these Intermediate and Advanced Software Carpentry in Python Code Like a Pythonista: Idiomatic Python Python Idioms and Efficiency Google Develo...
python design patterns
I am looking for any resources that gives examples of Best Practices, Design patterns and the SOLID principles using Python.
[ "Some overlap in these\nIntermediate and Advanced Software Carpentry in Python\nCode Like a Pythonista: Idiomatic Python\nPython Idioms and Efficiency\nGoogle Developers Day US - Python Design Patterns\nAnother resource is by example at the Python Recipes. A good number do not follow best practices but you can fin...
[ 152, 25, 13, 6, 6, 3 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0000606448_design_patterns_python.txt
Q: Superfluous python parameters I've noticed a discrepancy in the way that python parameters are called. In every other language I've dealt with, you either have foo() meaning either no parameters, or as many parameters as you like, or foo(arg1, arg2,...,argn) where you pass in the same number of parameters to...
Superfluous python parameters
I've noticed a discrepancy in the way that python parameters are called. In every other language I've dealt with, you either have foo() meaning either no parameters, or as many parameters as you like, or foo(arg1, arg2,...,argn) where you pass in the same number of parameters to define the function and call it. ...
[ "\nWhere did the self parameter go?\n\nIt's in front of the dot when you call the function, i.e. in your case it's zoo.\nNote that you can also call the function as foo.bar(zoo, arg1, arg2). Basically in python object.method(arguments) is a shortcut for objects_class.method(object, arguments).\n", "zoo is the sel...
[ 7, 3, 1, 0 ]
[]
[]
[ "class", "function", "parameters", "python" ]
stackoverflow_0002503281_class_function_parameters_python.txt
Q: How to make Python Extensions for Windows for absolute beginners I've been looking around the internet trying to find a good step by step guide to extend Python in Windows, and I haven't been able to find something for my skill level. let's say you have some c code that looks like this: #include <stdio.h> #include...
How to make Python Extensions for Windows for absolute beginners
I've been looking around the internet trying to find a good step by step guide to extend Python in Windows, and I haven't been able to find something for my skill level. let's say you have some c code that looks like this: #include <stdio.h> #include <math.h> double valuex(float value, double rate, double timex) { ...
[ "Cython (Pyrex with a few kinks worked out and decisions made for practicality) can use one code base to make Python 2 and Python 3 modules. It's a really great choice for making libraries for 2 and 3. The user guide explains how to use it, but it doesn't demystify Windows programming or C or Python or programming ...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "python", "python_3.x", "windows" ]
stackoverflow_0002503310_python_python_3.x_windows.txt
Q: Dynamically creating page definitions in Cherrypy I've been looking around the CherryPy documentation, but can't quite get my head around what I want to do. I suspect it might be more of a Python thing than a CherryPy thing... My current class looks something like this: import managerUtils class WebManager: d...
Dynamically creating page definitions in Cherrypy
I've been looking around the CherryPy documentation, but can't quite get my head around what I want to do. I suspect it might be more of a Python thing than a CherryPy thing... My current class looks something like this: import managerUtils class WebManager: def A(self, **kwds): return managerUtils.runActi...
[ "class WebManager:\n def default(self, action, **kwds):\n return managerUtils.runAction(action, kwds)\n default.exposed = True\n\nTwo notes about why this is different than other answers:\n\n.exposed is the correct attribute for publishing methods, not .enabled\nthe index method is the only one which d...
[ 3 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0002499219_cherrypy_python.txt
Q: Is it good to use Django 1.1 on App Engine? We are planning a web application to build on Google's App Engine platform. Is it good to use the Django 1.1 framework to develop Google App Engine applications? If not, could you please suggest me the best option available, which has good tutorials and learning resource...
Is it good to use Django 1.1 on App Engine?
We are planning a web application to build on Google's App Engine platform. Is it good to use the Django 1.1 framework to develop Google App Engine applications? If not, could you please suggest me the best option available, which has good tutorials and learning resource?
[ "Yes, Django 1.1 is well-supported on Google App Engine. You'll need to do your own installation thereof locally, to enable it in the GAE SDK -- but it's already there for you on the App Engine production servers, see the docs -- just do\nimport os\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\n\nfrom google....
[ 4, 1, 0, 0 ]
[]
[]
[ "django", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002490335_django_google_app_engine_google_cloud_datastore_python.txt
Q: Update element values using xml.dom.minidom I have an XML structure which looks similar to: <Store> <foo> <book> <isbn>123456</isbn> </book> <title>XYZ</title> <checkout>no</checkout> </foo> <bar> <book> <isbn>7890</isbn> </book> <title>XYZ2</titl...
Update element values using xml.dom.minidom
I have an XML structure which looks similar to: <Store> <foo> <book> <isbn>123456</isbn> </book> <title>XYZ</title> <checkout>no</checkout> </foo> <bar> <book> <isbn>7890</isbn> </book> <title>XYZ2</title> <checkout>yes</checkout> </bar> </Sto...
[ "I'm not entirely sure what you mean by \"checkout\". This script will find the element and alter the value of that element. Perhaps you can adapt it to your specific needs.\nimport xml.dom.minidom as DOM\n\n# find the author as a child of the \"Store\"\ndef getAuthor(parent, author):\n # by looking at the child...
[ 5 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0002502758_minidom_python_xml.txt
Q: Put an AuiManager inside a AuiNotebook page Is it possible ho put an AuiManager inside an AuiNotebook page? Have tested with a small sample code, but I only get a 'Segmentation fault'. Is this possible to begin with? The reason why I want this is to split a notebook page in two parts and get the caption field and ...
Put an AuiManager inside a AuiNotebook page
Is it possible ho put an AuiManager inside an AuiNotebook page? Have tested with a small sample code, but I only get a 'Segmentation fault'. Is this possible to begin with? The reason why I want this is to split a notebook page in two parts and get the caption field and the maximize field in the top of each part of the...
[ "wxAUIManager only works as a child of a wxFrame.\nhttp://docs.wxwidgets.org/trunk/classwx_aui_manager.html\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0002502270_python_wxpython_wxwidgets.txt