content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python psycopg2 error when changing environment to os x I have this error when i perform the following task, results = db1.executeSelectCommand(siteSql, (),) TypeError: unbound method executeSelectCommand() must be called with dbConnn instance as first argument (got str instance instead) My code is as follows:...
Python psycopg2 error when changing environment to os x
I have this error when i perform the following task, results = db1.executeSelectCommand(siteSql, (),) TypeError: unbound method executeSelectCommand() must be called with dbConnn instance as first argument (got str instance instead) My code is as follows: class dbConnn: db_con = None execfile("/Users/usera...
[ "db1 = dbConnections.dbConnn\n\nHere you assign the class dbConn to the variable db1. You probably wanted to create a new instance instead:\ndb1 = dbConnections.dbConnn()\n\n" ]
[ 0 ]
[]
[]
[ "macos", "psycopg2", "python" ]
stackoverflow_0003488521_macos_psycopg2_python.txt
Q: Idiomatic way of taking action on attempt to loop over an empty iterable Suppose that I am looping over a iterable and would like to take some action if the iterator is empty. The two best ways that I can think of to do this are: for i in iterable: # do_something if not iterable: # do_something_else and ...
Idiomatic way of taking action on attempt to loop over an empty iterable
Suppose that I am looping over a iterable and would like to take some action if the iterator is empty. The two best ways that I can think of to do this are: for i in iterable: # do_something if not iterable: # do_something_else and empty = True for i in iterable: empty = False # do_something if empty:...
[ "This is quite hackish, but you can delete i and then check if it exists after the loop (if not, the loop never happened):\ntry:\n del i\nexcept NameException: pass\n\nfor i in iterable:\n do_something(i)\n\ntry:\n del i\nexcept NameException:\n do_something_else()\n\nI think that's probably uglier than...
[ 3, 3, 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "coding_style", "iterable", "python" ]
stackoverflow_0003486257_coding_style_iterable_python.txt
Q: Writing unittests for a function that returns a hierarchy of objects I have a function that performs a hierarchical clustering on a list of input vectors. The return value is the root element of an object hierarchy, where each object represents a cluster. I want to test the following things: Does each cluster con...
Writing unittests for a function that returns a hierarchy of objects
I have a function that performs a hierarchical clustering on a list of input vectors. The return value is the root element of an object hierarchy, where each object represents a cluster. I want to test the following things: Does each cluster contain the correct elements (and maybe other properties as well)? Does each ...
[ "If there are isomorphic results, you should probably have a predicate that can test for logical equivalence. This would likely be good for your code unit as well as helping to implement the unit test.\nThis is the core of Manoj Govindan's answer without the string intermediates and since you aren't interested in s...
[ 2, 0, 0 ]
[]
[]
[ "python", "readability", "unit_testing" ]
stackoverflow_0003487507_python_readability_unit_testing.txt
Q: Using tweepy library with Python in identi.ca I'm using the tweepy library to make a small news application for my desktop in Python. As I've seen in the main web page: http://github.com/joshthecoder/tweepy it has support for identi.ca but I can't manage to log in correctly. To authenticate I do: auth = tweepy.Bas...
Using tweepy library with Python in identi.ca
I'm using the tweepy library to make a small news application for my desktop in Python. As I've seen in the main web page: http://github.com/joshthecoder/tweepy it has support for identi.ca but I can't manage to log in correctly. To authenticate I do: auth = tweepy.BasicAuthHandler(username, password) api = tweepy.API(...
[ "Using just identi.ca as the host and setting api_root to /api would be the correct way to access the identi.ca API, as implied by the tweepy documentation.\n" ]
[ 1 ]
[]
[]
[ "python", "tweepy" ]
stackoverflow_0003488738_python_tweepy.txt
Q: Bandwidth throttling in Python What libraries out there let you control the download speed of network requests (http in particular). I don't see anything built-in in urllib2 (nor in (Py)Qt which I intend on using). Can Twisted control bandwidth? If not, how can I control the read buffer size of urllib2 or Twisted?...
Bandwidth throttling in Python
What libraries out there let you control the download speed of network requests (http in particular). I don't see anything built-in in urllib2 (nor in (Py)Qt which I intend on using). Can Twisted control bandwidth? If not, how can I control the read buffer size of urllib2 or Twisted? sleeping to suspend network operati...
[ "urllib2 doesn't offer a way to do this, so you'd have to extend some of the classes it uses and implement rate limiting yourself. You might want to look at this question. If you decide to write a limiter, read up on the token bucket and leaky bucket algorithms.\nSome attempted hack solutions available on github ...
[ 9, 8 ]
[]
[]
[ "network_programming", "networking", "python" ]
stackoverflow_0003488616_network_programming_networking_python.txt
Q: A more suitable way to rewrite this? I have the method: def checkAgainstDate(): currentDate = date.today() currentMonth = date.today().month if currentMonth == 1 year = currentDate.year-1 return date(year, 11, 01) elif currentMonth == 2: year = currentDate.year-1 ...
A more suitable way to rewrite this?
I have the method: def checkAgainstDate(): currentDate = date.today() currentMonth = date.today().month if currentMonth == 1 year = currentDate.year-1 return date(year, 11, 01) elif currentMonth == 2: year = currentDate.year-1 return date(year, 12, 01) else ...
[ "dateutil is an amazing thing. It really should become stdlib someday.\n>>> from dateutil.relativedelta import relativedelta\n>>> from datetime import datetime\n>>> (datetime.now() - relativedelta(months=2)).replace(day=1)\ndatetime.datetime(2010, 6, 1, 13, 16, 29, 643077)\n>>> (datetime(2010, 4, 30) - relativedelt...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003489028_python.txt
Q: How can I make an http request without getting back an http response in Python? I want to send it and forget it. The http rest service call I'm making takes a few seconds to respond. The goal is to avoid waiting those few seconds before more code can execute. I'd rather not use python threads I'll use twisted asyn...
How can I make an http request without getting back an http response in Python?
I want to send it and forget it. The http rest service call I'm making takes a few seconds to respond. The goal is to avoid waiting those few seconds before more code can execute. I'd rather not use python threads I'll use twisted async calls if I must and ignore the response.
[ "You are going to have to implement that asynchronously as HTTP protocol states you have a request and a reply. \nAnother option would be to work directly with the socket, bypassing any pre-built module. This would allow you to violate protocol and write your own bit that ignores any responses, in essence dropping ...
[ 1, 0, 0 ]
[]
[]
[ "http", "python" ]
stackoverflow_0003486372_http_python.txt
Q: Google App Engine - Naked Domain Path Redirect in Python I'm working on a site, colorurl.com, and I need users to be able to type in colorurl.com/00ff00 (or some variation of that), and see the correct page. However, with the naked domain issue, users who type in colorurl.com/somepath will instead be redirected to...
Google App Engine - Naked Domain Path Redirect in Python
I'm working on a site, colorurl.com, and I need users to be able to type in colorurl.com/00ff00 (or some variation of that), and see the correct page. However, with the naked domain issue, users who type in colorurl.com/somepath will instead be redirected to www.colorurl.com/. Is there a way to detect this in python, a...
[ "What I'd do in this scenario is set up a small site at your naked domain which consists of just a .htaccess file which redirects path and all to www.*:\nOptions +FollowSymLinks \nRewriteEngine on \nRewriteCond %{HTTP_HOST} ^colorurl.com [NC] \nRewriteRule ^(.*)$ http://www.colorurl.com/$1 [L,R=301]\n\n", "You ne...
[ 4, 0 ]
[]
[]
[ "google_app_engine", "python", "redirect" ]
stackoverflow_0003482152_google_app_engine_python_redirect.txt
Q: Programming Language: What language has both Python & Ruby features? I came across this great comparison chart between Python & Ruby. I'm looking for a programming language that is truly a blend between Python and Ruby (with a slight lean towards Python). I really like in Ruby that everything is an object (unlike ...
Programming Language: What language has both Python & Ruby features?
I came across this great comparison chart between Python & Ruby. I'm looking for a programming language that is truly a blend between Python and Ruby (with a slight lean towards Python). I really like in Ruby that everything is an object (unlike Python). However, I really like in Python that things are immutable, so th...
[ "I don't understand what you mean by \"everything is an object\", as far as I know Python has no primitives either (you can derive from the basic integer type in Python 3 for example.)\nI've used both, and although I prefer Python, Ruby is no doubt a very potent language, so instead of going by a chart, install bot...
[ 2, 0 ]
[]
[]
[ "lua", "programming_languages", "python", "ruby" ]
stackoverflow_0003489339_lua_programming_languages_python_ruby.txt
Q: Is it possible to test Google App Engine OpenID authentication on development Server? I'm trying OpenID support for Google App Engine on a small project i have on my machine but when i call: users.create_login_url(federated_identity = provider_url) i get this error: google_appengine/google/appengine/api/user_serv...
Is it possible to test Google App Engine OpenID authentication on development Server?
I'm trying OpenID support for Google App Engine on a small project i have on my machine but when i call: users.create_login_url(federated_identity = provider_url) i get this error: google_appengine/google/appengine/api/user_service_pb.py", line 178, in ByteSize n += self.lengthString(len(self.destination_url_)) Ty...
[ "You should normally pass a dest_url parameter to create_login_url, unless you're certain that there is a \"current request\" whose url you want to use instead. Apparently, the latter condition does not obtain, so the destination url stays None, which causes the problem you're observing. Passing an explicit dest_...
[ 6 ]
[]
[]
[ "google_app_engine", "openid", "python" ]
stackoverflow_0003489488_google_app_engine_openid_python.txt
Q: Can't figure out how to invoke cProfile inside of a program Sorry for the beginner question, but I can't figure out cProfile (I'm really new to Python) I can run it via my terminal with: python -m cProfile myscript.py But I need to run it on a webserver, so I'd like to put the command within the script it will lo...
Can't figure out how to invoke cProfile inside of a program
Sorry for the beginner question, but I can't figure out cProfile (I'm really new to Python) I can run it via my terminal with: python -m cProfile myscript.py But I need to run it on a webserver, so I'd like to put the command within the script it will look at. How would I do this? I've seen stuff using terms like __in...
[ "I think you've been seeing ideas like this:\nif __name__ == \"__main__\":\n # do something if this script is invoked\n # as python scriptname. Otherwise, gets ignored.\n\nWhat happens is when you call python on a script, that file has an attribute __name__ set to \"__main__\" if it is the file being directly...
[ 5 ]
[]
[]
[ "cprofile", "profiler", "python", "time" ]
stackoverflow_0003489769_cprofile_profiler_python_time.txt
Q: list index out of range error received hey guys, beginner here. I have written a program that outputs files to .txt's and am using another to read them and use them. i have used a list to store these values (len(..) gives me 100 for all files). However, whenever i run this: for w in range(1,20): # i want files fil...
list index out of range error received
hey guys, beginner here. I have written a program that outputs files to .txt's and am using another to read them and use them. i have used a list to store these values (len(..) gives me 100 for all files). However, whenever i run this: for w in range(1,20): # i want files file01-file20 excluding file00 for x in ran...
[ "You seem to be incrementing c two thousand times (20 times 100 -- actually only 1900 times, since range(1,20) will not reach the value 20, as you seem to desire in a comment) -- so of course you're going out of range if you use it to index a list of 100! The whole code is rather a mess and I suggest refactoring i...
[ 4, 1, 1 ]
[]
[]
[ "debugging", "list", "python" ]
stackoverflow_0003489756_debugging_list_python.txt
Q: Automatically readdress all variables referring to an object Suppose I have in python this object class Foo: def __init__(self, val): self.val = val and these two variables a=Foo(5) b=a both b and a refer to the same instance of Foo(), so any modification to the attribute .val will be seen equally ...
Automatically readdress all variables referring to an object
Suppose I have in python this object class Foo: def __init__(self, val): self.val = val and these two variables a=Foo(5) b=a both b and a refer to the same instance of Foo(), so any modification to the attribute .val will be seen equally and synchronized as a.val and b.val. >>> b.val 5 >>> b.val=3 >>> ...
[ "As Aaron points out, there may be very hacky and fragile solutions but there is likely nothing that would be guaranteed to work across all Python implementations (e.g. CPython, IronPython, Jython, PyPy, etc). But why would one realistically want to do something that is so contrary to the design and idiomatic use ...
[ 7, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003489380_python.txt
Q: How to remove the things I don't like about Python? Python is a great programming language, but certain things about it just annoy the heck out of me. As such, I: 1) wanted to find out how to remove these annoyances from the language itself, or 2) find a language that is Python-like that don't have these annoyanc...
How to remove the things I don't like about Python?
Python is a great programming language, but certain things about it just annoy the heck out of me. As such, I: 1) wanted to find out how to remove these annoyances from the language itself, or 2) find a language that is Python-like that don't have these annoyances. I love Python for everything except: self: just see...
[ "pypy is a complete implementation of Python in Python itself (with all of the things you consider annoyances, nevertheless a very high-level implementation language that makes altering even the core of the language itself for your own purposes easier than ever before). Download it, fork it, and edit it to fix wha...
[ 7, 2, 0 ]
[]
[]
[ "programming_languages", "python" ]
stackoverflow_0003489929_programming_languages_python.txt
Q: Using cProfile or line_profile on a Python script in /cgi-bin/? Is there a way to run cProfile or line_profile on a script on a server? ie: how could I get the results for one of the two methods on http://www.Example.com/cgi-bin/myScript.py Thanks! A: Not sure what line_profile is. For cProfile, you just need t...
Using cProfile or line_profile on a Python script in /cgi-bin/?
Is there a way to run cProfile or line_profile on a script on a server? ie: how could I get the results for one of the two methods on http://www.Example.com/cgi-bin/myScript.py Thanks!
[ "Not sure what line_profile is. For cProfile, you just need to direct the results to a file you can later read on the server (depending on what kind of access you have to the server).\nTo quote the example from the docs,\nimport cProfile\ncProfile.run('foo()', 'fooprof')\n\nand put all the rest of the code into a ...
[ 1 ]
[]
[]
[ "cgi_bin", "cprofile", "python", "time" ]
stackoverflow_0003489932_cgi_bin_cprofile_python_time.txt
Q: App Engine - Output Response Time Say I wanted to print the response time on my pages like Google do. How would I go about doing this? A: Call start = time.time() as the very first operation in your handling scripts, and, when you're just about done with everything, as the very last thing you output use (a prop...
App Engine - Output Response Time
Say I wanted to print the response time on my pages like Google do. How would I go about doing this?
[ "Call start = time.time() as the very first operation in your handling scripts, and, when you're just about done with everything, as the very last thing you output use (a properly formatted version of) time.time() - start.\nIf you're using templates for your output (e.g., the Django templates that come with app eng...
[ 3 ]
[]
[]
[ "google_app_engine", "performance", "python" ]
stackoverflow_0003489968_google_app_engine_performance_python.txt
Q: Why does Python require the "self" parameter? Possible Duplicates: python ‘self’ explained Why do you need explicitly have the “self” argument into a Python method? Why does Python require the "self" parameter for methods? For example def method_abc(self, arg1) And is there ever a date that the need for it will...
Why does Python require the "self" parameter?
Possible Duplicates: python ‘self’ explained Why do you need explicitly have the “self” argument into a Python method? Why does Python require the "self" parameter for methods? For example def method_abc(self, arg1) And is there ever a date that the need for it will be removed?
[ "Python gives you the option of naming it something other than self, even though the standard is to name it self. Just as it gives you the option of using tabs for indents, even though the standard is to use spaces.\nIn other words, it's not just \"assumed\" because...\n\nTo give you naming flexibility\nTo make it ...
[ 0 ]
[]
[]
[ "programming_languages", "python" ]
stackoverflow_0003490017_programming_languages_python.txt
Q: How to install/organize python modules on a mac? I have a mbp, but I've been lazy and have been using ubuntu for my python development thus far b/c its so easy to install modules etc. How do you install modules on a mac? And best-practises with storing all .py files? A: One of the perks of using high level lang...
How to install/organize python modules on a mac?
I have a mbp, but I've been lazy and have been using ubuntu for my python development thus far b/c its so easy to install modules etc. How do you install modules on a mac? And best-practises with storing all .py files?
[ "One of the perks of using high level languages is that they function mostly the same on each platform they support. Python is no diffent. You install modules the same way you do on Linux: using easy_install or pip, check them out http://pypi.python.org/pypi/setuptools http://pypi.python.org/pypi/pip\n", "See my ...
[ 0, 0 ]
[]
[]
[ "installation", "python" ]
stackoverflow_0003489646_installation_python.txt
Q: Does python have a ruby installer like gem that lets you install modules from the command line even if they are not on your machine? With Ruby you can do gem install from the command line to install a module...even if it is not on your machine. Can you do that with python. Does someone know of a module? Seth A:...
Does python have a ruby installer like gem that lets you install modules from the command line even if they are not on your machine?
With Ruby you can do gem install from the command line to install a module...even if it is not on your machine. Can you do that with python. Does someone know of a module? Seth
[ "no it does not have a ruby installer that I know of. It does have easy_install and pip though. Your google-fu is lacking.\n", "There's setuptools, which allows you to install packages from PyPi via easy_install. Another option is pip, which also installs from PyPi.\n" ]
[ 4, 3 ]
[]
[]
[ "python", "rubygems" ]
stackoverflow_0003490543_python_rubygems.txt
Q: How to display and tag a region of an image with python I'm used to writing python scripts that interact with files, data and databases but I haven't done user-interfaces. For my current project, I want to show an image (jpg/gif/png) to a user so it can be region-tagged. Region-tags are not just information about ...
How to display and tag a region of an image with python
I'm used to writing python scripts that interact with files, data and databases but I haven't done user-interfaces. For my current project, I want to show an image (jpg/gif/png) to a user so it can be region-tagged. Region-tags are not just information about the image (like location or has/doesn't have people in it) bu...
[ "Python has bindings for may GUI toolkits which can allow you to display an image and interact with it in any way you want. A binding for Tk comes installed with Python. I personally recommend PyQt (a binding to the Qt library), but many people also like wxPython, a binding to wxWindows.\nSee here for more. Googlin...
[ 1 ]
[]
[]
[ "image", "python", "tags", "user_interface" ]
stackoverflow_0003490552_image_python_tags_user_interface.txt
Q: Parsing text files using Python I am very new to Python and am looking to use it to parse a text file. The file has between 250-300 lines of the following format: ---- Mark Grey (mark.grey@gmail.com) changed status from Busy to Available @ 14/07/2010 16:32:36 ---- ---- Silvia Pablo (spablo@gmail.com) became Avail...
Parsing text files using Python
I am very new to Python and am looking to use it to parse a text file. The file has between 250-300 lines of the following format: ---- Mark Grey (mark.grey@gmail.com) changed status from Busy to Available @ 14/07/2010 16:32:36 ---- ---- Silvia Pablo (spablo@gmail.com) became Available @ 14/07/2010 16:32:39 ---- I ne...
[ "To get you started:\nresult = []\nregex = re.compile(\n r\"\"\"^-*\\s+\n (?P<name>.*?)\\s+\n \\((?P<email>.*?)\\)\\s+\n (?:changed\\s+status\\s+from\\s+(?P<previous>.*?)\\s+to|became)\\s+\n (?P<new>.*?)\\s+@\\s+\n (?P<date>\\S+)\\s+\n (?P<time>\\S+)\\s+\n -*$\"\"\", re.VERBOSE)\nwith open(\...
[ 16, 6, 6, 4, 1, 1 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003253383_parsing_python.txt
Q: Reading files using Python I have a file of the following format. "08-10-2010 13:29:31 1 APs were seen " "08-10-2010 13:29:31 MAC Address SSID RSSI" "08-10-2010 13:29:31 00:1e:79:d7:d5:b0 -80" "08-10-2010 13:30:32 2 APs were seen...
Reading files using Python
I have a file of the following format. "08-10-2010 13:29:31 1 APs were seen " "08-10-2010 13:29:31 MAC Address SSID RSSI" "08-10-2010 13:29:31 00:1e:79:d7:d5:b0 -80" "08-10-2010 13:30:32 2 APs were seen " "08-10-2010 13:30:32 MAC...
[ "http://docs.python.org/library/\nLook carefully at sections 10 and 7. They will give you what you need to look at a file and parse it for the information required. Study, post something, whether it works or not, and we'll help you out more.\n" ]
[ 1 ]
[]
[]
[ "file", "function", "python" ]
stackoverflow_0003490492_file_function_python.txt
Q: Mongodb - are reliability issues significant still? I have a couple of sqlite dbs (i'd say about 15GBs), with about 1m rows in total - so not super big. I was looking at mongodb, and it looks pretty easy to work with, especially if I want to try and do some basic natural language processing on the documents which ...
Mongodb - are reliability issues significant still?
I have a couple of sqlite dbs (i'd say about 15GBs), with about 1m rows in total - so not super big. I was looking at mongodb, and it looks pretty easy to work with, especially if I want to try and do some basic natural language processing on the documents which make up the databases. I've never worked with Mongo in t...
[ "As others have said, MongoDB does not have single-server durability right now. Fortunately, it's dead easy to set up multi-node replication. You can even set up a second machine in another data center and have data automatically replicated to it live!\nIf a write must succeed, you can cause Mongo to not return fro...
[ 10, 9, 4, 3, 2 ]
[]
[]
[ "mongodb", "python", "sqlite" ]
stackoverflow_0003487456_mongodb_python_sqlite.txt
Q: python program bug help I've got an exam coming up soon. I've been looking through the past paper, this question keeps bugging me. I can't seem to find what the bug in the program could be because I'm quite new to all this. Can anyone help me out? The following program contains a bug. Determine what kind of probl...
python program bug help
I've got an exam coming up soon. I've been looking through the past paper, this question keeps bugging me. I can't seem to find what the bug in the program could be because I'm quite new to all this. Can anyone help me out? The following program contains a bug. Determine what kind of problem the program exhibits, and ...
[ "There's a race condition between your two threads. Basically, there is a time between setting data[0] to something before setting data[1] to four times that value.\nIf the second thread comes in and checks the values during that time, the data inconsistency will occur.\nYou may think the two threads refer to their...
[ 4, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003487301_multithreading_python.txt
Q: error when call python object thru MEL code How to resolve this. Following error occurs from maya. I am doing the following in Filemenu.mel file. this runs at the startup. python("import saveCentral_fromPath"); . . . global proc runSaveCentral() { python("saveCentral_fromPath.saveCentral()"); python("a._first_()...
error when call python object thru MEL code
How to resolve this. Following error occurs from maya. I am doing the following in Filemenu.mel file. this runs at the startup. python("import saveCentral_fromPath"); . . . global proc runSaveCentral() { python("saveCentral_fromPath.saveCentral()"); python("a._first_()"); } . . . menuItem -label ("save Cen...
[ "python(\"import saveCentral_fromPath\");\n.\n..\n\nglobal proc runSaveCentral()\n\n{\n python(\"saveCentral_fromPath.saveCentral()._first_()\");\n# filename.classname.functionname\n}\n\n.\n.\n.\nmenuItem -label (\"save Central\") -en 1\n-annotation (\"publish : copy to central area\")\n-command (\...
[ 0 ]
[]
[]
[ "maya", "python" ]
stackoverflow_0003147757_maya_python.txt
Q: Python on windows, shutting down and taking a screenshot I have the following two quesions: 1 I want to be able to shutdown windows xp from python code. I am able to do that by running the following code in the python console: import os os.system("shutdown -s -f") But, if i put the same code in a .py file and tr...
Python on windows, shutting down and taking a screenshot
I have the following two quesions: 1 I want to be able to shutdown windows xp from python code. I am able to do that by running the following code in the python console: import os os.system("shutdown -s -f") But, if i put the same code in a .py file and try to execute it,it does not work. I get the help prompt for th...
[ "There's some code to shutdown windows in this message from the python-win32 list.\nYou can take a screen shot using PIL's ImageGrab module.\n" ]
[ 2 ]
[]
[]
[ "python", "windows", "windows_xp" ]
stackoverflow_0003491226_python_windows_windows_xp.txt
Q: what is wrong in my python code? #!usr/bin/python listofnames = [] names = input("Pls enter how many of names:") x = 1 for x in range(0, names): inname = input("Enter the name " + str(x)) listofnames.append(inname) print listofnames error inname = input("Enter the name " + str(x)) File "", line 1, i...
what is wrong in my python code?
#!usr/bin/python listofnames = [] names = input("Pls enter how many of names:") x = 1 for x in range(0, names): inname = input("Enter the name " + str(x)) listofnames.append(inname) print listofnames error inname = input("Enter the name " + str(x)) File "", line 1, in NameError: name 'Jhon' is not def...
[ "Use raw_input instead. See http://docs.python.org/library/functions.html#raw_input. input will do the same thing as eval(raw_input(prompt)), so entering in Jhon will try to find the symbol Jhon within the file (which doesn't exist). So for your existing script you'd have to input 'Jhon' (notice the set of quotes)...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003491316_python.txt
Q: Converting graph traversal to multiprocessing in Python I've been working on a graph traversal algorithm over a simple network and I'd like to run it using multiprocessing since it it going to require a lot of I/O bounded calls when I scale it over the full network. The simple version runs pretty fast: already_se...
Converting graph traversal to multiprocessing in Python
I've been working on a graph traversal algorithm over a simple network and I'd like to run it using multiprocessing since it it going to require a lot of I/O bounded calls when I scale it over the full network. The simple version runs pretty fast: already_seen = {} already_seen_get = already_seen.get GH_add_node = GH...
[ "Queues in Python are synchronized. This means that only one thread at a time can read/write, this will definitely provoke a bottleneck in your app.\nOne better solution is to distribute the processing based on a hash function and assign the processing to the threads with a simple module operation. So for instance ...
[ 1 ]
[]
[]
[ "algorithm", "graph", "multithreading", "parallel_processing", "python" ]
stackoverflow_0003469343_algorithm_graph_multithreading_parallel_processing_python.txt
Q: What's the best dispatcher/callback library in Python? I need to allow other Python applications to register callback functions for events in my application. These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions ...
What's the best dispatcher/callback library in Python?
I need to allow other Python applications to register callback functions for events in my application. These need to have priorities associated with them (so a callback with a priority of 10 runs before a callback with a priority of 1) and callback functions need to be able to signal errors to the dispatcher. These ar...
[ "Are these other applications running in another address space? If so, you'll need to use an interprocess communication library like D-BUS.\nIf you're just sending signals in the same process, try PyDispatcher\n", "What platform are you running under? GObject is the basis of the GTK GUI that's widely-used under ...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000118221_python.txt
Q: get http response codes with python I know how to do this with httplib, but I need to also set the user-agent and I'm sure you need urllib to do that. How can I get the http response codes with urllib? A: You can use .getcode() in urllib2 to get the HTTP code: urllib2.urlopen("http://google.com").getcode() Full...
get http response codes with python
I know how to do this with httplib, but I need to also set the user-agent and I'm sure you need urllib to do that. How can I get the http response codes with urllib?
[ "You can use .getcode() in urllib2 to get the HTTP code:\nurllib2.urlopen(\"http://google.com\").getcode()\n\nFull headers with are in info() as a list:\nurllib2.urlopen(\"http://google.com\").info().headers\n\n", "Actually, httplib DOES allow to set User-Agent.\nheaders = { 'User-Agent' : 'someapp', 'Content-Typ...
[ 5, 0 ]
[]
[]
[ "http", "python" ]
stackoverflow_0003491495_http_python.txt
Q: Calling python script on MAC/Linux from Command line - passing arguments Consider this setup and folder structure: c:\foo \bin\foo.bat \lib\foo.py I have foo.bat path added to my environment PATH, so I can call it from anywhere passing in some arguments: c:/>foo.bat -v foo.bat contains this code: @E...
Calling python script on MAC/Linux from Command line - passing arguments
Consider this setup and folder structure: c:\foo \bin\foo.bat \lib\foo.py I have foo.bat path added to my environment PATH, so I can call it from anywhere passing in some arguments: c:/>foo.bat -v foo.bat contains this code: @ECHO OFF "c:\foo\lib\foo.py" %1 %2 %3 %4 %5 %6 %7 %8 %9 This works fine in Win...
[ "You can call python scripts directly on mac/linux, just make sure to put your python interpreter on the first line, example file foo:\n#!/usr/bin/python \nif __name__ == \"__main__\":\n print 'bar'\n\nto run the file call it directly form your current directory using ./foo\nif you want to access if from everywh...
[ 6, 2 ]
[]
[]
[ "batch_file", "command_line", "linux", "macos", "python" ]
stackoverflow_0003492050_batch_file_command_line_linux_macos_python.txt
Q: Get existing or create new App Engine Syntax I came across this syntax browsing through code for examples. From its surrounding code, it looked like would a) get the entity with the given keyname or b) if the entity did not exist, create a new entity that could be saved. Assume my model class is called MyModel. m...
Get existing or create new App Engine Syntax
I came across this syntax browsing through code for examples. From its surrounding code, it looked like would a) get the entity with the given keyname or b) if the entity did not exist, create a new entity that could be saved. Assume my model class is called MyModel. my_model = MyModel(key_name='mymodelkeyname', ...
[ "The constructor, which is what you're using, always constructs a new entity. When you store it, it overwrites any other entity with the same key.\nThe alternate code you propose also has an issue: it's susceptible to race conditions. Two instances of that code running simultaneously could both determine that the e...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "modeling", "models", "python" ]
stackoverflow_0003490141_google_app_engine_modeling_models_python.txt
Q: How to make GtkListStore store object attribute in a row? I'w trying to keep at ListStore non-text objects using snippet I found. These are the objects: class Series(gobject.GObject, object): def __init__(self, title): super(Series, self).__init__() self.title = title gobject.type_register(Series) class Ser...
How to make GtkListStore store object attribute in a row?
I'w trying to keep at ListStore non-text objects using snippet I found. These are the objects: class Series(gobject.GObject, object): def __init__(self, title): super(Series, self).__init__() self.title = title gobject.type_register(Series) class SeriesListStore(gtk.ListStore): def __init__(self): super(Serie...
[ "Two mistakes in the second-to-last block.\n\nGtkWarning: gtk_tree_view_column_cell_layout_set_cell_data_func: assertion `info != NULL'\nIn English, this means that the cell renderer is not in the column's list of cell renderers. You need to add the cell renderer to the column first before calling set_cell_data_fun...
[ 3 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0003488285_gtk_pygtk_python.txt
Q: Why does updating a set in a tuple cause an error? I have just tried the following in Python 2.6: >>> foo = (set(),) >>> foo[0] |= set(range(5)) TypeError: 'tuple' object does not support item assignment >>> foo (set([0, 1, 2, 3, 4]),) >>> foo[0].update(set(range(10))) >>> foo (set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),...
Why does updating a set in a tuple cause an error?
I have just tried the following in Python 2.6: >>> foo = (set(),) >>> foo[0] |= set(range(5)) TypeError: 'tuple' object does not support item assignment >>> foo (set([0, 1, 2, 3, 4]),) >>> foo[0].update(set(range(10))) >>> foo (set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),) I have several questions here: Why does foo[0] |= se...
[ ">>> def f():\n... x = (set(),)\n... y = set([0])\n... x[0] |= y\n... return \n... \n>>> import dis\n>>> dis.dis(f)\n 2 0 LOAD_GLOBAL 0 (set)\n 3 CALL_FUNCTION 0\n 6 BUILD_TUPLE 1\n 9 STORE_FAST 0 (x)\n\n ...
[ 11, 2, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0003492216_python_tuples.txt
Q: Import all modules in django In django is there way to import all modules ex: from project.models import * ex: from project1.models import * Can this be done with one statement A: If you just want to do this when testing things in the shell, look into the shell_plus command provided by the django-extensio...
Import all modules in django
In django is there way to import all modules ex: from project.models import * ex: from project1.models import * Can this be done with one statement
[ "If you just want to do this when testing things in the shell, look into the shell_plus command provided by the django-extensions project.\nThis is a really neat extension, which starts a shell and automatically loads all the models in your project when you do ./manage.py shell_plus from the command line.\n" ]
[ 4 ]
[]
[]
[ "django", "django_settings", "python" ]
stackoverflow_0003493204_django_django_settings_python.txt
Q: what is the next step? When I type "python" it displays: ActivePython 2.6.5.14 (ActiveState Software Inc.) based on Python 2.6.5 (r265:79063, Jul 4 2010, 21:05:58) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. This is what I get at the command line: >>...
what is the next step?
When I type "python" it displays: ActivePython 2.6.5.14 (ActiveState Software Inc.) based on Python 2.6.5 (r265:79063, Jul 4 2010, 21:05:58) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. This is what I get at the command line: >>> python create-application....
[ "Apparently you are confusing between the Python REPL and the command line. You should be calling python create-application.py from the command line (\"cmd\" in Windows) and not from the REPL (which is what you get when you type python on the command line).\nI suggest reading up on the basics before venturing furt...
[ 10, 3 ]
[]
[]
[ "java", "python", "qooxdoo" ]
stackoverflow_0003493377_java_python_qooxdoo.txt
Q: matplotlib weirdness, it's not drawing my graph What happened is I followed this demo, I modified it to suit my needs had it working, changed it to use a function to draw two graphs but now it doesn't work at all using plt.show() or plt.savefig() here's my code import csv import numpy as np import matplotlib matp...
matplotlib weirdness, it's not drawing my graph
What happened is I followed this demo, I modified it to suit my needs had it working, changed it to use a function to draw two graphs but now it doesn't work at all using plt.show() or plt.savefig() here's my code import csv import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt im...
[ "Try removing\nimport matplotlib\nmatplotlib.use('Agg')\n\nThe command\npython -c 'import matplotlib; matplotlib.use(\"\")'\n\nwill show you the valid string arguments that can be sent to matplotlib.use. \nOn my machine, 'Agg' is listed as valid, though I get no output when this is set. If you are curious, you coul...
[ 1 ]
[]
[]
[ "graph", "matplotlib", "python" ]
stackoverflow_0003493409_graph_matplotlib_python.txt
Q: How to convert a binary file into a Long integer? In python, long integers have an unlimited range. Is there a simple way to convert a binary file (e.g., a photo) into a single long integer? A: Here's one way to do it. def file_to_number(f): number = 0 for line in f: for char in line: ...
How to convert a binary file into a Long integer?
In python, long integers have an unlimited range. Is there a simple way to convert a binary file (e.g., a photo) into a single long integer?
[ "Here's one way to do it.\ndef file_to_number(f):\n number = 0\n for line in f:\n for char in line:\n number = ord(char) | (number << 8)\n return number\n\nYou might get a MemoryError eventually.\n", "Using the bitstring module it's just:\nbitstring.BitString(filename='your_file').uint\...
[ 3, 3 ]
[]
[]
[ "algorithm", "long_integer", "python" ]
stackoverflow_0003493781_algorithm_long_integer_python.txt
Q: An extended Bezier Library or Algorithms of bezier operations Is there a library of data structures and operations for quadratic bezier curves? I need to implement: bezier to bitmap converting with arbitrary quality optimizing bezier curves common operations like subtraction, extraction, rendering etc. languages...
An extended Bezier Library or Algorithms of bezier operations
Is there a library of data structures and operations for quadratic bezier curves? I need to implement: bezier to bitmap converting with arbitrary quality optimizing bezier curves common operations like subtraction, extraction, rendering etc. languages: c,c++,.net,python Algorithms without implementation (pseudocode o...
[ "A little bit of python lib is included in nodebox:\nhttp://nodebox.net/code/index.php/Bezier\nThere are plenty of algorithms inside inkscape, but I did not digg the code yet to find, how easy they could be used outside if inkscape.\nUpdate: Inkscape is using lib2geom:\n\nlib2geom (2Geom in private life) was\n ini...
[ 4, 1 ]
[]
[]
[ "algorithm", "bezier", "curve", "python" ]
stackoverflow_0002568018_algorithm_bezier_curve_python.txt
Q: How can I convert the time in a datetime string from 24:00 to 00:00 in Python? I have a lot of date strings like Mon, 16 Aug 2010 24:00:00 and some of them are in 00-23 hour format and some of them in 01-24 hour format. I want to get a list of date objects of them, but when I try to transform the example string in...
How can I convert the time in a datetime string from 24:00 to 00:00 in Python?
I have a lot of date strings like Mon, 16 Aug 2010 24:00:00 and some of them are in 00-23 hour format and some of them in 01-24 hour format. I want to get a list of date objects of them, but when I try to transform the example string into a date object, I have to transform it from Mon, 16 Aug 2010 24:00:00 to Tue, 17 A...
[ "import email.utils as eutils\nimport time\nimport datetime\n\nntuple=eutils.parsedate('Mon, 16 Aug 2010 24:00:00')\nprint(ntuple)\n# (2010, 8, 16, 24, 0, 0, 0, 1, -1)\ntimestamp=time.mktime(ntuple)\nprint(timestamp)\n# 1282017600.0\ndate=datetime.datetime.fromtimestamp(timestamp)\nprint(date)\n# 2010-08-17 00:00:0...
[ 10 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0003493924_datetime_python.txt
Q: Getting started with Qooxdoo i downloaded Qooxdoo, then ActivePython and installed it as in this tutorial http://qooxdoo.org/documentation/1.1/helloworld. When I follow the instructions I get the following results: C:\qooxdoo-1.1-sdk\tool\bin\create-application.py --name=custom --out=C: - this command opens a "cr...
Getting started with Qooxdoo
i downloaded Qooxdoo, then ActivePython and installed it as in this tutorial http://qooxdoo.org/documentation/1.1/helloworld. When I follow the instructions I get the following results: C:\qooxdoo-1.1-sdk\tool\bin\create-application.py --name=custom --out=C: - this command opens a "create-application" wordfile. cd C:\...
[ "In order to execute .pys from the command line on Windows like that you'll need to add .py to your PATHEXT environment variable.\nYou might also need to make sure that ActivePython's bin directory is in your path. If it is, you can then equivalently run python generate.py.\n" ]
[ 2 ]
[]
[]
[ "ajax", "javascript", "python", "qooxdoo" ]
stackoverflow_0003493974_ajax_javascript_python_qooxdoo.txt
Q: Organizing files in tar bz2 file with python I have about 200,000 text files that are placed in a bz2 file. The issue I have is that when I scan the bz2 file to extract the data I need, it goes extremely slow. It has to look through the entire bz2 file to fine the single file I am looking for. Is there anyway to s...
Organizing files in tar bz2 file with python
I have about 200,000 text files that are placed in a bz2 file. The issue I have is that when I scan the bz2 file to extract the data I need, it goes extremely slow. It has to look through the entire bz2 file to fine the single file I am looking for. Is there anyway to speed this up? Also, I thought about possibly organ...
[ "Do you have to use bzip2? Reading it's documentation, it's quite clear it's not designed to support random access. Perhaps you should use a compression format that more closely matches your requirements. The good old Zip format supports random access, but might compress worse, of course.\n", "Bzip2 compresses in...
[ 6, 0 ]
[]
[]
[ "bzip2", "python", "tar", "tarfile" ]
stackoverflow_0003494020_bzip2_python_tar_tarfile.txt
Q: python setuptool how can I add dependency for libxml2-dev and libxslt1-dev? My application needs lxml >= 2.1, but to install lxml its requied to install libxml2-dev libxslt1-dev else it raises error while installing the lxml, is there a way that using python setup tool I can give this as dependency in my setup.py....
python setuptool how can I add dependency for libxml2-dev and libxslt1-dev?
My application needs lxml >= 2.1, but to install lxml its requied to install libxml2-dev libxslt1-dev else it raises error while installing the lxml, is there a way that using python setup tool I can give this as dependency in my setup.py....
[ "Not really ... setuptools only handle dependencies on package wich belongs already to pypi. So if you want these kind of dependencies, i think that you have to select the packaging technology brought by your favorite distribution.\nBut, you can override your setuptools build or install command to make extra check ...
[ 2 ]
[]
[]
[ "dependencies", "libxml2", "lxml", "python", "setuptools" ]
stackoverflow_0003493151_dependencies_libxml2_lxml_python_setuptools.txt
Q: getting all child nodes' values of the current node I am trying to retrieve all of the values in the div. For example: <div>xyz <span> abc </span> def</div> This is the code the_page="<div>xyz <span> abc </span> def</div>" doc = libxml2dom.parseString(the_page, html=1) divs=doc.getElementsByTagName("div") print ...
getting all child nodes' values of the current node
I am trying to retrieve all of the values in the div. For example: <div>xyz <span> abc </span> def</div> This is the code the_page="<div>xyz <span> abc </span> def</div>" doc = libxml2dom.parseString(the_page, html=1) divs=doc.getElementsByTagName("div") print divs[0].firstChild.nodeValue This only prints "xyz". I t...
[ "for your: \ndivs=doc.getElementsByTagName(\"div\")\n\nuse:\nchilds = divs[0].childNodes\n\nthen, you can crawl them. Each child contains a list of childs and nodeValue\nfor child in childs :\n if child.childNode == []:\n print child.nodeValue\n else :\n ## Recurse\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003488572_python.txt
Q: Why am I receiving these syntax errors in Python 3.1.2? I have been receiving errors when trying to save and run this Python 3.1 script, and I'm not sure why. I'm new to python, and I've been trying some of the Project Euler problems (this is problem 2). I recieve a "invalid syntac" error on "evenfibsum(v)", and o...
Why am I receiving these syntax errors in Python 3.1.2?
I have been receiving errors when trying to save and run this Python 3.1 script, and I'm not sure why. I'm new to python, and I've been trying some of the Project Euler problems (this is problem 2). I recieve a "invalid syntac" error on "evenfibsum(v)", and on the colon after "_____main_____". I'm not sure why this is ...
[ "There is no closing bracket in v = int(...\n", "You are missing a closing parenthesis on the line assigning v.\n" ]
[ 11, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003494780_python.txt
Q: How can I improve this long-winded Python code? I have a data structure like this: items = [ ['Schools', '', '', '32'], ['Schools', 'Primary schools', '', '16'], ['Schools', 'Secondary schools', '', '16'], ['Schools', 'Secondary schools', 'Special ed', '8'], ['Schools', 'Secondary schools', 'No...
How can I improve this long-winded Python code?
I have a data structure like this: items = [ ['Schools', '', '', '32'], ['Schools', 'Primary schools', '', '16'], ['Schools', 'Secondary schools', '', '16'], ['Schools', 'Secondary schools', 'Special ed', '8'], ['Schools', 'Secondary schools', 'Non-special ed', '8'], ] It's a list of spending items...
[ "Firstly, I suggest your data structure should look more like this:\nitems = [\n ['Schools', None, None, 32],\n ['Schools', 'Primary schools', None, 16],\n ['Schools', 'Secondary schools', None, 8],\n ['Schools', 'Secondary schools', 'Special ed', 4],\n ['Schools', 'Secondary schools', 'Non-special e...
[ 2, 1, 0, 0, 0, 0 ]
[ "You could use a list comprehension, as follows:\nitems = [a for a in items if a[1] != '' and a[2] != '']\n\nOr, if an empty string in any position denotes an aggregate item:\nitems = [a for a in items if '' not in a]\n\nOf course, you don't necessarily need to assign the reduced list to items - you can use it howe...
[ -1 ]
[ "python", "refactoring" ]
stackoverflow_0003491877_python_refactoring.txt
Q: What's wrong with this code? The code is to search for a substring...the code takes in 2 inputs...the 2nd string is used to search...i.e 2nd string is smaller in length. a=input("Enter the 1st string") //Giving error here b=input("Enter the second string") com="" for x in range(0,len(a)): com="" ...
What's wrong with this code?
The code is to search for a substring...the code takes in 2 inputs...the 2nd string is used to search...i.e 2nd string is smaller in length. a=input("Enter the 1st string") //Giving error here b=input("Enter the second string") com="" for x in range(0,len(a)): com="" for j in range(x,len(b)+x): ...
[ "If you are using Python 2.x, you need to use raw_input, not input. input tries to evaluate what you enter as though it is Python code. This is no longer true in Python 3.\nAnother obvious thing is that this:\nif(com==b):\nprint \"Match Found at\" + str(x)\nelse:\ncontinue\n\n... needs to be indented like this:\n...
[ 4, 4 ]
[]
[]
[ "python", "search", "substring" ]
stackoverflow_0003494914_python_search_substring.txt
Q: What is the fastest way to plot a 2d numpy array of pixel data with pygtk? I have a numpy array of pixel data that I want to draw at interactive speeds in pygtk. Is there some simple, fast way to get my data onto the screen? A: I'm not aware of anything GTK specific, but have a look at glumpy and pygarrayimage ...
What is the fastest way to plot a 2d numpy array of pixel data with pygtk?
I have a numpy array of pixel data that I want to draw at interactive speeds in pygtk. Is there some simple, fast way to get my data onto the screen?
[ "I'm not aware of anything GTK specific, but have a look at glumpy and pygarrayimage for fast, OpenGL based visualization (and animation) of numpy arrays. \nPygarrayimage is focused more on just getting numpy arrays as an OpenGL texture. I don't know a ton about it, but it is somewhat widely used, as far as I can ...
[ 2 ]
[]
[]
[ "gtk", "numpy", "pygtk", "python" ]
stackoverflow_0003486354_gtk_numpy_pygtk_python.txt
Q: Font width returns incorrect values The following code should return the width in pixels of the character 'a' in the default font; it doesn't: import pygtk gtk.require20() import gtk t = gtk.TextView() print t.get_style().get_font().width("w") # Always returns -6 A: gtk.Style.get_font() is deprecated, as evid...
Font width returns incorrect values
The following code should return the width in pixels of the character 'a' in the default font; it doesn't: import pygtk gtk.require20() import gtk t = gtk.TextView() print t.get_style().get_font().width("w") # Always returns -6
[ "gtk.Style.get_font() is deprecated, as evidenced by the DeprecationWarning you get when you try to call it; I assume that's why it's not working. On my PyGTK there isn't any such function as gtk.Style.string_width().\nYou should use Pango:\nimport pygtk\npygtk.require20()\nimport gtk\n\nt = gtk.TextView()\nprint t...
[ 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0003481972_pygtk_python.txt
Q: Format of activate_time in Gtk.Menu What is the format of the parameter activate_time in Python GTK+ when using Gtk.Menu.popup() method? I have tried using int(time.time()) but I get a traceback saying an integer is required... A: Not sure if it is a complete solution, but time.time() returns a float, try castin...
Format of activate_time in Gtk.Menu
What is the format of the parameter activate_time in Python GTK+ when using Gtk.Menu.popup() method? I have tried using int(time.time()) but I get a traceback saying an integer is required...
[ "Not sure if it is a complete solution, but time.time() returns a float, try casting to an int and see what happens.\nEDIT:\nAfter consulting the source docs, I found this tidbit:\n\nThe button and activate_time values should be the mouse button that was pressed to trigger the menu popup and the time the button wa...
[ 1, 1 ]
[]
[]
[ "gtk", "python" ]
stackoverflow_0003494587_gtk_python.txt
Q: How to get the last value of a list of tkinter Entry widgets I have a list of n Entry widgets. Every widget accepts only one character, and then the focus is passed to the next one. I would like to ".get()" the values of the n widgets, but I can't get the last one. Here is the sample code: import Tkinter as tk de...
How to get the last value of a list of tkinter Entry widgets
I have a list of n Entry widgets. Every widget accepts only one character, and then the focus is passed to the next one. I would like to ".get()" the values of the n widgets, but I can't get the last one. Here is the sample code: import Tkinter as tk def vf(event): actual=entrylist.index(root.focus_get()) prin...
[ "The value you enter into the fourth Entry widget is only stored after the event has finished. That is, after the call to vf(event) is complete.\nI have added a button which displays the contents of the Entry widgets when pressed. This will display the contents of all four widgets.\nOtherwise access the contents of...
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003494810_python_tkinter.txt
Q: Uninstall pysvn in Mac OSX 10.5 I installed the wrong version of pysvn in my system using the .dmg. I realized the mistake and removed the pysvn folder from /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/. I don't see pysvn anywhere else on my system. Now when I try to install the co...
Uninstall pysvn in Mac OSX 10.5
I installed the wrong version of pysvn in my system using the .dmg. I realized the mistake and removed the pysvn folder from /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/. I don't see pysvn anywhere else on my system. Now when I try to install the correct (older) version of pysvn the in...
[ "In case anyone else needs an answer to this I'll post the solution that worked for me. This link was what I was looking for. Deleting the pysvn .pkg file from /Library/Receipts allowed me to install the older version.\n" ]
[ 2 ]
[]
[]
[ "macos", "pysvn", "python" ]
stackoverflow_0003479331_macos_pysvn_python.txt
Q: python interpreter with ellipsis _ function? >>> type(_) <type 'ellipsis'> >>> 1 + 1 2 >>> _ 2 >>> what's the usefulness of this _ function? A: It just makes it easier to track intermediate values or to operate on the previously returned value. >>> [x*x for x in range(5)] [0, 1, 4, 9, 16] >>> sum(_) # instead...
python interpreter with ellipsis _ function?
>>> type(_) <type 'ellipsis'> >>> 1 + 1 2 >>> _ 2 >>> what's the usefulness of this _ function?
[ "It just makes it easier to track intermediate values or to operate on the previously returned value.\n>>> [x*x for x in range(5)]\n[0, 1, 4, 9, 16]\n>>> sum(_) # instead of having to type sum([0,1,4,9,16]) by hand\n30\n\n", "in case you use ipython it's part of ipythons [output caching system] - it just stores t...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003495248_python.txt
Q: The best way to use python as a server scripting language for use on localhost relatively long-time PHP user here. I could install XAMPP in my sleep at this point to the point where I can get a PHP script running in the browser at "localhost", but in my searches to find a similar path using Python, I've run out of...
The best way to use python as a server scripting language for use on localhost
relatively long-time PHP user here. I could install XAMPP in my sleep at this point to the point where I can get a PHP script running in the browser at "localhost", but in my searches to find a similar path using Python, I've run out of Googling ideas. I've discovered the mod_python Apache mod, but then I also discover...
[ "well mod_python has been retired. So in order to host python apps you want mod_wsgi \nhttp://code.google.com/p/modwsgi/\nBut python isn't really like php(as in you mix it with html to get output, if I understand your question correctly). In learning python, using the command line/repl will probably be much more u...
[ 5, 4, 2 ]
[]
[]
[ "localhost", "python", "xampp" ]
stackoverflow_0003495290_localhost_python_xampp.txt
Q: sqlite SQL query for unprocessed rows I'm not quite even sure where / what to search for - so apologies if this is a trivial thing that has been asked before! I have two tables in sqlite: table_A = [id, value1, value2] table_A$foo = [id, foo(value1), foo(value2)] table_A$bar = [id, bar(value1), bar(value2)] Where...
sqlite SQL query for unprocessed rows
I'm not quite even sure where / what to search for - so apologies if this is a trivial thing that has been asked before! I have two tables in sqlite: table_A = [id, value1, value2] table_A$foo = [id, foo(value1), foo(value2)] table_A$bar = [id, bar(value1), bar(value2)] Where foo() / bar() are arbitrary functions not ...
[ "I don't understand if you consider a match based on value1 columns matching, or a combination of all three columns...\nUsing EXISTS to find those that are already present:\nSELECT *\n FROM TABLE_A a\n WHERE EXISTS(SELECT NULL\n FROM TABLE_A$foo f\n WHERE a.id = f.id\n ...
[ 1 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0003495524_python_sql_sqlite.txt
Q: Check ports with SNMP (net-snmp) Is there a way to monitor server ports using SNMP (I'm using net-snmp-python to check this with python). So far I've checked pretty simple with "nc" command, however I want to see if I can do this with SNMP. Thank you for your answers and patience. A: Well if you want to use SN...
Check ports with SNMP (net-snmp)
Is there a way to monitor server ports using SNMP (I'm using net-snmp-python to check this with python). So far I've checked pretty simple with "nc" command, however I want to see if I can do this with SNMP. Thank you for your answers and patience.
[ "Well if you want to use SNMP to see exactly what ports are listening, you should be able to use the following OIDS and walk the table\n \"1.3.6.1.2.1.6.13.1.1\" tcpConnState \n \"1.3.6.1.2.1.7.5.1.1\" udpLocalAddress\n\nWalking UDP would give you something like this: \nsnmpwalk -cpublic 192.168.1.13 1.3.6.1.2.1...
[ 4, 0, 0 ]
[]
[]
[ "networking", "python", "snmp" ]
stackoverflow_0003485203_networking_python_snmp.txt
Q: How to organize GUI Code for a PyQt project? i am looking for something similar to Organizing GUI code, but for Python and PyQt4. Especially, I am looking at tips and examples of how to handle and store the configuration data, general state etc. EDIT: I have found some hints regarding older versions under: http:...
How to organize GUI Code for a PyQt project?
i am looking for something similar to Organizing GUI code, but for Python and PyQt4. Especially, I am looking at tips and examples of how to handle and store the configuration data, general state etc. EDIT: I have found some hints regarding older versions under: http://www.commandprompt.com/community/pyqt/
[ "Here's an overview of what we did w/some example names and their functions (we have a lot more in the actual app.)\nProjectFolder/\n - src/\n - my_project/\n - model/\n - preference.py # Interact with config params\n - api.py # Interact with our REST api\n\n - controller/\n ...
[ 15 ]
[]
[]
[ "code_organization", "pyqt4", "python" ]
stackoverflow_0003495703_code_organization_pyqt4_python.txt
Q: Compression types for a specific use in Python I actually partially asked this in this thread Organizing files in tar bz2 file with python But it mad eme rethink what I was doing. Now I think it might be a good idea to change the compression method I am using. I am currently using tar.bz2 compression. What I need ...
Compression types for a specific use in Python
I actually partially asked this in this thread Organizing files in tar bz2 file with python But it mad eme rethink what I was doing. Now I think it might be a good idea to change the compression method I am using. I am currently using tar.bz2 compression. What I need to be able to do is access the compressed files one ...
[ "You could compress the individual files and put those into a tar (or ar) container.\n" ]
[ 1 ]
[]
[]
[ "compression", "python" ]
stackoverflow_0003495978_compression_python.txt
Q: What is the difference between a parameterized class and a metaclass (code examples in Python please)? Hello Stack Overflow contributers, I'm a novice programmer learning Python right now, and I came upon this site which helps explain object-oriented paradigms. I know that metaclasses are classes of classes (like ...
What is the difference between a parameterized class and a metaclass (code examples in Python please)?
Hello Stack Overflow contributers, I'm a novice programmer learning Python right now, and I came upon this site which helps explain object-oriented paradigms. I know that metaclasses are classes of classes (like how meta-directories are directories of directories, etc. etc.), but I'm having trouble with something: What...
[ "Python doesn't have (or need) \"parameterized classes\", so it's hard to provide examples of them in Python;-). A metaclass is simply \"the class of a class\": normally type (as long, in Py2, as you remember to make the class new-style by inheriting from object, or some other built-in type or other new-style clas...
[ 17, 0 ]
[]
[]
[ "class", "metaclass", "parameterized", "python" ]
stackoverflow_0003496029_class_metaclass_parameterized_python.txt
Q: How to run all test-cases from several modules? I have several modules full of test-cases and would like to create one module that runs them all. I tried loading the tests in each of the modules using TestLoader.loadTestFromModule, but it always returns empty test-suites. What is the easiest way to achieve this? ...
How to run all test-cases from several modules?
I have several modules full of test-cases and would like to create one module that runs them all. I tried loading the tests in each of the modules using TestLoader.loadTestFromModule, but it always returns empty test-suites. What is the easiest way to achieve this?
[ "Have a look at nose. It can also be called programmatically, and it may thus be used to call your tests once you've configured it.\n", "Ok, the problem there was that I handed in the modules-names as strings, when I should have been handing in module-objects like this:\nimport unittest\nimport SomeTestModule\n\...
[ 0, 0 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0003452846_python_unit_testing.txt
Q: How to map one list to another in python? ['a','a','b','c','c','c'] to [2, 2, 1, 3, 3, 3] and {'a': 2, 'c': 3, 'b': 1} A: >>> x=['a','a','b','c','c','c'] >>> map(x.count,x) [2, 2, 1, 3, 3, 3] >>> dict(zip(x,map(x.count,x))) {'a': 2, 'c': 3, 'b': 1} >>> A: This coding should give the result: from collection...
How to map one list to another in python?
['a','a','b','c','c','c'] to [2, 2, 1, 3, 3, 3] and {'a': 2, 'c': 3, 'b': 1}
[ ">>> x=['a','a','b','c','c','c']\n>>> map(x.count,x)\n[2, 2, 1, 3, 3, 3]\n>>> dict(zip(x,map(x.count,x)))\n{'a': 2, 'c': 3, 'b': 1}\n>>>\n\n", "This coding should give the result:\nfrom collections import defaultdict\n\nmyDict = defaultdict(int)\n\nfor x in mylist:\n myDict[x] += 1\n\nOf course if you want the l...
[ 41, 12, 7, 6, 5, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002401885_python.txt
Q: Worst practices in Django you have ever seen What are the worst mistakes made using Django framework, that you have noticed? Have you seen some real misuses, that maybe should go as warnings to the Django docs? A: Too much logic in views. I used to write views that would struggle to fit in 40 lines. Now I consi...
Worst practices in Django you have ever seen
What are the worst mistakes made using Django framework, that you have noticed? Have you seen some real misuses, that maybe should go as warnings to the Django docs?
[ "Too much logic in views. \nI used to write views that would struggle to fit in 40 lines. Now I consider more than 2-3 indentation levels, 10 or so LOC or a handful of inline comments in a view to be code smells.\nThe temptation is to write minimal models, figure out your url routing, then do everything else in the...
[ 27, 12, 11, 9, 5, 5, 5, 4, 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002058532_django_python.txt
Q: What's the simplest way to pass a file as an argument in a simple shell script? The following works fine on Mac OS X: #!/bin/bash R CMD Sweave myfile.Rnw pdflatex myfile.tex open myfile.pdf Now, I realize that these 3 lines of code are really helpful for my work – independently of some particular file. Thus I'd l...
What's the simplest way to pass a file as an argument in a simple shell script?
The following works fine on Mac OS X: #!/bin/bash R CMD Sweave myfile.Rnw pdflatex myfile.tex open myfile.pdf Now, I realize that these 3 lines of code are really helpful for my work – independently of some particular file. Thus I'd like to use the file as an argument. I know how to use an argument itself but have pro...
[ "I do all my shell scripting in python.\nIt's easier to read, more powerful and works on windows as well.\n", "You could just take the base name as an argument and use $1.Rnw, $1.tex, and $1.pdf. Python is great for shell scripts, but I usually stick with bash for things less than 10 lines long.\nIf you really wa...
[ 6, 6, 2, 1, 0 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0003496628_python_shell.txt
Q: Find what is in a PYC file This may be a noobie questions, but... So I have a pyc file that I need to use, but I don't have any documentation on it. Is there a way to find out what classes and functions are in it and what variables they take? I don't need to code, just how to run it. Thanks A: As long as you can...
Find what is in a PYC file
This may be a noobie questions, but... So I have a pyc file that I need to use, but I don't have any documentation on it. Is there a way to find out what classes and functions are in it and what variables they take? I don't need to code, just how to run it. Thanks
[ "As long as you can import the file, you can inspect it; it doesn't matter whether it comes from a .py or .pyc.\n>>> import getopt\n>>> dir(getopt)\n['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args',...
[ 9, 4, 1, 0 ]
[]
[]
[ "pyc", "python" ]
stackoverflow_0003497075_pyc_python.txt
Q: Tkinter: Why is one Frame overlaying another? I am trying to build a GUI in Python using Tkinter. My idea is to build several Frames inside the root Frame. I can get 2 Frames to appear, but the third Frame overlays the second Frame. I've tried both pack() and grid() as the layout manager in the root Frame. I wa...
Tkinter: Why is one Frame overlaying another?
I am trying to build a GUI in Python using Tkinter. My idea is to build several Frames inside the root Frame. I can get 2 Frames to appear, but the third Frame overlays the second Frame. I've tried both pack() and grid() as the layout manager in the root Frame. I want to have a "Stuff At The Top" Frame and a "Stuff ...
[ "The short answer to your code is that you're giving the same name to both of your Cat2Frame objects. Either give them unique names, or don't use the name attribute for the frame.\nAlso, might I suggest you reconsider your programming style a bit? The way you have written your code it is very difficult to read. I'v...
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003496819_python_tkinter.txt
Q: How do I access base class variables through an instance of a child class in Python? I wanted to know how to access to the super class’s variables with a object of child class If it makes any sense I add that some of the variables are defined in this __variable name way. Any time I want to access the variables wi...
How do I access base class variables through an instance of a child class in Python?
I wanted to know how to access to the super class’s variables with a object of child class If it makes any sense I add that some of the variables are defined in this __variable name way. Any time I want to access the variables with a child object. Python says the object with the type CHILE CLASS TYPE here is not defi...
[ "Something is wrong, but not with the code you've shown. If Worksheet truly defines .nrows, then your AcuExcelSheet will have access to it. There are a few possibilities: \n\nWorksheet doesn't define nrows. You mention double-underscore names. Are you sure it isn't __nrows?\nWorksheet defines nrows, but only fo...
[ 4, 2, 0 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0003494006_inheritance_python.txt
Q: making paint in pyqt or qt i have just received a task to implement a software that paints over pictures (pretty much like microsoft paint ) i have no idea where to start or how to do that. do anyone have a good reference or idea for painting in qt or pyqt ? this will be highly appreciated thanks in advance ...
making paint in pyqt or qt
i have just received a task to implement a software that paints over pictures (pretty much like microsoft paint ) i have no idea where to start or how to do that. do anyone have a good reference or idea for painting in qt or pyqt ? this will be highly appreciated thanks in advance
[ "You'll be working with the QImage class, which represents bitmap images. It has methods for changing the colour at a given pixel using setPixel. There is am Image Viewer Example provided with Qt and PyQT should come with the same example in Python. However it uses a Qlabel to display the image so you may want to u...
[ 4, 1, 0 ]
[]
[]
[ "paint", "pyqt", "python", "qt" ]
stackoverflow_0003179469_paint_pyqt_python_qt.txt
Q: How can I properly use multidimensional dictionaries in Cheetah for Python? I have the following dictionary: {0: {'Shortname': 'cabling', 'Name': 'CAT5 Cabling', 'MSRP': '$45.00'}, 1: {'Shortname': 'antenna', 'Name': 'Radio Antenna', 'MSRP': '$35.00'}} And using Cheetah, the following section of template: #for $i...
How can I properly use multidimensional dictionaries in Cheetah for Python?
I have the following dictionary: {0: {'Shortname': 'cabling', 'Name': 'CAT5 Cabling', 'MSRP': '$45.00'}, 1: {'Shortname': 'antenna', 'Name': 'Radio Antenna', 'MSRP': '$35.00'}} And using Cheetah, the following section of template: #for $item in $items <tr> <td>$item.Name</td> <td>$item.MSRP</td> </tr> #end for When I...
[ "First off, I had problems using items as the variable name in Cheetah. Might be a reserved word or something.\nSomething less generic might be better to use.\nSecondly, since you use an outer dict with an integer as key, $item will be that integer.\nWhich means you look for Name in an integer. So in your case with...
[ 2 ]
[]
[]
[ "cheetah", "dictionary", "python", "templates" ]
stackoverflow_0003496530_cheetah_dictionary_python_templates.txt
Q: Defining path to module's configuration files A Python module I'm developing has a master configuration file in /path/to/module/conf.conf. The /path/to/module/ depends on the platform (for instance, /Users/me/module in OS X, /home/me/module in Linux, etc). Currently I define the /path/to/module in __init__.py, whe...
Defining path to module's configuration files
A Python module I'm developing has a master configuration file in /path/to/module/conf.conf. The /path/to/module/ depends on the platform (for instance, /Users/me/module in OS X, /home/me/module in Linux, etc). Currently I define the /path/to/module in __init__.py, where I use logic: if sys.platform == 'darwin': ROOT ...
[ "Inside of your __init__.py, you could get the directory where the __init_.py script lives using the __file__ magic variable like so:\nfrom os.path import dirname\nROOT = dirname(__file__)\n\nThen you know that conf.conf will be located at os.path.join(ROOT, 'conf.conf').\n" ]
[ 2 ]
[]
[]
[ "configuration", "cross_platform", "python" ]
stackoverflow_0003497270_configuration_cross_platform_python.txt
Q: Proper way to include files I am trying to keep a somewhat organized directory structure as I plan to add more and more scripts. So lets say I have a structure like this: /src/main.py /src/db/<all my DB conn & table manipulation scripts> /src/api/<all my scripts that call different APIs> My main.py script will in...
Proper way to include files
I am trying to keep a somewhat organized directory structure as I plan to add more and more scripts. So lets say I have a structure like this: /src/main.py /src/db/<all my DB conn & table manipulation scripts> /src/api/<all my scripts that call different APIs> My main.py script will include certain classes from db & a...
[ "The way you have it setup is creating three different modules - this may or may not be what you want to do. If you want a common module which can manage different tasks you could arrange it as follows:\nmymodule\n |- __init__.py\n |--database\n | |- __init__.py\n | |- dbclasses.py\n | \n |--api\n | |- __init...
[ 3, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003497520_python.txt
Q: Python: output of scapy cannot be stored in a text file? When runnning scapy from command prompt (windows XP), the output cannot be stored. When the following command is executed in command prompt: scapy >C:\dir.txt The following error shows up: C:\automation\atg\GeneralFiles_AC\ScapyExe>scapy >C:\dir.txt INFO: ...
Python: output of scapy cannot be stored in a text file?
When runnning scapy from command prompt (windows XP), the output cannot be stored. When the following command is executed in command prompt: scapy >C:\dir.txt The following error shows up: C:\automation\atg\GeneralFiles_AC\ScapyExe>scapy >C:\dir.txt INFO: Can't import python gnuplot wrapper . Won't be able to plot. I...
[]
[]
[ "Check out the documentation on installing optional packages for Windows here.\n" ]
[ -1 ]
[ "python", "scapy", "windows" ]
stackoverflow_0003497746_python_scapy_windows.txt
Q: matplotlib plot and imshow The behavior of matplotlib's plot and imshow is confusing to me. import matplotlib as mpl import matplotlib.pyplot as plt If I call plt.show() prior to calling plt.imshow(i), then an error results. If I call plt.imshow(i) prior to calling plt.show(), then everything works perfectly. How...
matplotlib plot and imshow
The behavior of matplotlib's plot and imshow is confusing to me. import matplotlib as mpl import matplotlib.pyplot as plt If I call plt.show() prior to calling plt.imshow(i), then an error results. If I call plt.imshow(i) prior to calling plt.show(), then everything works perfectly. However, if I close the first figur...
[ "\nIf I call plt.show() prior to calling\nplt.imshow(i), then an error results.\nIf I call plt.imshow(i) prior to\ncalling plt.show(), then everything\nworks perfectly.\n\nplt.show() displays the figure (and enters the main loop of whatever gui backend you're using). You shouldn't call it until you've plotted thin...
[ 40 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003497578_matplotlib_python.txt
Q: python try/finally for flow control I'm sure this concept has come up before but I can't find a good, simple answer. Is using try/finally a bad way to handle functions with multiple returns? For example I have try: if x: return update(1) else: return update(2) finally: notifyUpdated() ...
python try/finally for flow control
I'm sure this concept has come up before but I can't find a good, simple answer. Is using try/finally a bad way to handle functions with multiple returns? For example I have try: if x: return update(1) else: return update(2) finally: notifyUpdated() This just seems nicer than storing upd...
[ "I wouldn't recommend it. First because notifyUpdated() will be called even if the code in either branch throws an exception. You would need something like this to really get the intended behavior:\ntry:\n if x:\n return update(1)\n else:\n return update(2)\nexcept:\n raise\nelse:\n noti...
[ 11, 11, 3, 3, 3, 0 ]
[]
[]
[ "control_flow", "python", "try_catch_finally" ]
stackoverflow_0003497371_control_flow_python_try_catch_finally.txt
Q: Why can't I write all the data from sys.stdin to a file in Windows? I am trying to read binary data from sys.stdin using Python 2.7 on Windows XP. The binary data is a WAV file decoded by foobar2000. Normally, this data is sent to a command-line encoder such as lame.exe on stdin, where it is processed and written ...
Why can't I write all the data from sys.stdin to a file in Windows?
I am trying to read binary data from sys.stdin using Python 2.7 on Windows XP. The binary data is a WAV file decoded by foobar2000. Normally, this data is sent to a command-line encoder such as lame.exe on stdin, where it is processed and written to an output file whose name is provided in the command-line arguments. I...
[ "Suggestion: maybe you need to use msvcrt.setmode(fd, flags) where fd is sys.stdin.fileno() \n" ]
[ 2 ]
[]
[]
[ "binary_data", "io", "python", "windows" ]
stackoverflow_0003497879_binary_data_io_python_windows.txt
Q: Python List Help I have a list of lists that looks like: floodfillque = [[1,1,e],[1,2,w], [1,3,e], [2,1,e], [2,2,e], [2,3,w]] for each in floodfillque: if each[2] == 'w': floodfillque.remove(each) else: tempfloodfill.append(floodfillque[each[0+1][1]]) That is a simplified, but I think rel...
Python List Help
I have a list of lists that looks like: floodfillque = [[1,1,e],[1,2,w], [1,3,e], [2,1,e], [2,2,e], [2,3,w]] for each in floodfillque: if each[2] == 'w': floodfillque.remove(each) else: tempfloodfill.append(floodfillque[each[0+1][1]]) That is a simplified, but I think relevant part of the code...
[ "In addition to the bug in your code that other answers have already spotted, you have at least one more:\nfor each in floodfillque:\n if each[2] == 'w':\n floodfillque.remove(each)\n\ndon't add or remove items from the very container you're looping on. While such a bug will usually be diagnosed only for...
[ 5, 4, 3, 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003494615_list_python.txt
Q: How to implement substring algorithm I am trying to implement an algorithm to take a string of length n and returns all substrings with a length of 2 or greater. If the user inputs a string e.g "abcd", then the output should be ab, bc, cd, abc, bcd, abcd. a=input("Ente the input") list=[] com="" for k in range(2,l...
How to implement substring algorithm
I am trying to implement an algorithm to take a string of length n and returns all substrings with a length of 2 or greater. If the user inputs a string e.g "abcd", then the output should be ab, bc, cd, abc, bcd, abcd. a=input("Ente the input") list=[] com="" for k in range(2,len(a)+1): for x in range(k,len(a)+1): ...
[ ">>> [ a[ index : index + length ] for index in range( len( a ) - 1 ) for length in range( 2, len( a ) - index + 1 ) ]\n['ab', 'abc', 'abcd', 'bc', 'bcd', 'cd']\n\nIf you need the list sorted:\n>>> sorted( [ a[ index : index + length ] for index in range( len( a ) - 1 ) for length in range( 2, len( a ) - index + 1 ...
[ 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0003496047_algorithm_python.txt
Q: In Python is it bad to create an attribute called 'id'? I know that there's a function called id so I wouldn't create a function or a variable called id, but what about an attribute on an object? A: That's ok, and is pretty common. For example, objects mapped to a database record will often have an "id" attribu...
In Python is it bad to create an attribute called 'id'?
I know that there's a function called id so I wouldn't create a function or a variable called id, but what about an attribute on an object?
[ "That's ok, and is pretty common. For example, objects mapped to a database record will often have an \"id\" attribute mapped to the database \"id\" column value.\nAttributes are always \"namespaced\" so you have to refer to them via self.id or obj.id so there's no conflict with the built-in function.\n", "I do ...
[ 40, 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003497883_python.txt
Q: Python: openssl segmentation fault I followed the instrunction on this site http://paltman.com/2007/nov/15/getting-ssl-support-in-python-251/ to install openssl. When I go to test i get this as the output: test_rude_shutdown ... test_basic ... Segmentation fault How would I resolve this? A: First, make sure whi...
Python: openssl segmentation fault
I followed the instrunction on this site http://paltman.com/2007/nov/15/getting-ssl-support-in-python-251/ to install openssl. When I go to test i get this as the output: test_rude_shutdown ... test_basic ... Segmentation fault How would I resolve this?
[ "First, make sure which python returns /usr/local/bin/python. If not, use the Python you just built instead of your system copy! If it does, try creating a crash dump.\nBefore running the tests:\nulimit -c unlimited\nThen run the crashy test again. Take the file which materializes in your current directory. It'...
[ 1 ]
[]
[]
[ "openssl", "python" ]
stackoverflow_0003498263_openssl_python.txt
Q: organising classes and modules in python I'm getting a bit of a headache trying to figure out how to organise modules and classes together. Coming from C++, I'm used to classes encapsulating all the data and methods required to process that data. In python there are modules however and from code I have looked at...
organising classes and modules in python
I'm getting a bit of a headache trying to figure out how to organise modules and classes together. Coming from C++, I'm used to classes encapsulating all the data and methods required to process that data. In python there are modules however and from code I have looked at, some people have a lot of loose functions st...
[ "It seems like loose functions bother you. This is the python way. It makes sense because a module in python is really just an object on the same footing as any other object. It does have language level support for loading it from a file but other than that, it's just an object.\nso if I have a module foo.py:\nimpo...
[ 16, 3 ]
[]
[]
[ "class", "module", "oop", "python" ]
stackoverflow_0003498200_class_module_oop_python.txt
Q: Help with multiline regex match I am trying to have a regular expression match a value that spans multiple lines. I am using the re.S flag, but still get no results. Any ideas why? This is the text that I am searching through: <File id="abc.txt" EngRev="74"> <Identifier id="STRING_ID" isArray="1" goesWith="30272...
Help with multiline regex match
I am trying to have a regular expression match a value that spans multiple lines. I am using the re.S flag, but still get no results. Any ideas why? This is the text that I am searching through: <File id="abc.txt" EngRev="74"> <Identifier id="STRING_ID" isArray="1" goesWith="3027253"> <EngTranslation>"Value 1","V...
[ "I strongly urge you to not use regular expressions for parsing XML. SO has a lot of question/answer threads explaining why. For instance see this classic.\nSince you are using Python why not use libraries like BeautifulSoup or Lxml to do the job much more cleanly and concisely? \n", "You're missing an argument:\...
[ 7, 1 ]
[]
[]
[ "python", "regex", "xml" ]
stackoverflow_0003495700_python_regex_xml.txt
Q: Upload an image file using python Is there a way of uploading an image file using python ?. Im able to upload files from a simple html page consisting of the code below.But i would like to be able to do that from a python program. Can it be done using urllib2 module ?. Any example i can refer to ? Please help. Tha...
Upload an image file using python
Is there a way of uploading an image file using python ?. Im able to upload files from a simple html page consisting of the code below.But i would like to be able to do that from a python program. Can it be done using urllib2 module ?. Any example i can refer to ? Please help. Thank You. <form action="http://somesite.c...
[ "You can use pycurl package for that.\nfrom StringIO import StringIO\nfrom pycurl import *\nc = Curl()\nd = StringIO()\nh = StringIO()\nc.setopt(URL, \"http://somesite.com/handler.php\")\nc.setopt(POST, 1)\nc.setopt(HTTPPOST, [('file', (FORM_FILE, '/path/to/file')), ('submit', 'Upload')])\nc.setopt(WRITEFUNCTION, d...
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003497969_python.txt
Q: How to filter columns in two tables with many-to-many relation? I have this table: channel_items = Table( "channel_items", metadata, Column("channel_id", Integer, ForeignKey("channels.id")), Column("media_item_id", Integer, ForeignKey("media_items.id")) ) class Channel(rdb.Mode...
How to filter columns in two tables with many-to-many relation?
I have this table: channel_items = Table( "channel_items", metadata, Column("channel_id", Integer, ForeignKey("channels.id")), Column("media_item_id", Integer, ForeignKey("media_items.id")) ) class Channel(rdb.Model): """Set up channels table in the database""" rdb.metadata(...
[ "You just reference it through relation name. Also, its 'items' in your scheme, not 'item'.\nchannels = session.query(Channel).options(eagerload(\"items\")).filter(Channel.items.type == \"jpg\").all()\n\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003497912_python_sqlalchemy.txt
Q: Using Linux redirect to overwrite file from Python script I have a simple python script that just takes in a filename, and spits out a modified version of that file. I would like to redirect stdout (using '>' from the command line) so that I can use my script to overwrite a file with my modifications, e.g. python ...
Using Linux redirect to overwrite file from Python script
I have a simple python script that just takes in a filename, and spits out a modified version of that file. I would like to redirect stdout (using '>' from the command line) so that I can use my script to overwrite a file with my modifications, e.g. python myScript.py test.txt > test.txt When I do this, the resulting t...
[ "The reason it works that way is that, before Python even starts, Bash interprets the redirection operator and opens an output stream to write stdout to the file. That operation truncates the file to size 0 - in other words, it clears the contents of the file. So by the time your Python script starts, it sees an em...
[ 7, 1, 1 ]
[]
[]
[ "linux", "python", "redirect", "shell" ]
stackoverflow_0003498106_linux_python_redirect_shell.txt
Q: how to write a Python debugger/editor Sorry for the kind of general question. More details about what I want: I want the user to be able to write some Python code and execute it. Once there is an exception which is not handled, I want the debugger to pause the execution, show information about the current state/en...
how to write a Python debugger/editor
Sorry for the kind of general question. More details about what I want: I want the user to be able to write some Python code and execute it. Once there is an exception which is not handled, I want the debugger to pause the execution, show information about the current state/environment/stack/exception and make it possi...
[ "Playing around with ast and compile (built-in) it seems that you could possibly use the NodeTransformer to modify some nodes... You can also edit them manually if you know what you're looking for.\ntest.py\nprint 'Dumb Guy'\nx = 4 + 4\nprint x * 3\n\nchange.py\nimport ast\nwith open('test.py') as f:\n expr = f....
[ 2, 1, 1 ]
[]
[]
[ "abstract_syntax_tree", "compiler_construction", "parsing", "python", "stack_trace" ]
stackoverflow_0003229102_abstract_syntax_tree_compiler_construction_parsing_python_stack_trace.txt
Q: How do you find the filename that you pass to open()? I'm trying to open a file with Python, but I'm unsure how to find the correct filename to use. A: Access the name attribute. fh = open('spam.txt') print fh.name A: You can specify the path to the file in either a complete way (e.g. 'c:/wher/ever/the.txt'), ...
How do you find the filename that you pass to open()?
I'm trying to open a file with Python, but I'm unsure how to find the correct filename to use.
[ "Access the name attribute.\nfh = open('spam.txt')\nprint fh.name\n\n", "You can specify the path to the file in either a complete way (e.g. 'c:/wher/ever/the.txt'), also known as \"absolute\" because it's taken exactly as you specify it, or a partial one (e.g., just \"the.txt\", or \"ever/the.txt\", or \"../ever...
[ 2, 2 ]
[]
[]
[ "file", "python" ]
stackoverflow_0003498587_file_python.txt
Q: Error when adding value to array with open('file00.txt') as f00: for line in f00: farr=array.append(float(line)) print "farr= ",farr i get: farr=array.append(float(line)) AttributeError: 'module' object has no attribute 'append' does anyone know why I get this? do I have...
Error when adding value to array
with open('file00.txt') as f00: for line in f00: farr=array.append(float(line)) print "farr= ",farr i get: farr=array.append(float(line)) AttributeError: 'module' object has no attribute 'append' does anyone know why I get this? do I have to import something? am I doing it co...
[ "To append to an array, you must create the array (as an instance of the array.array type with the appropriate type code), giving it a name, and call append on that name - that is, on the instance, definitely not on the module.\nSo, for example:\n>>> import array\n>>> x = array.array('d') # array of double-precisi...
[ 1, 0 ]
[]
[]
[ "append", "arrays", "debugging", "python" ]
stackoverflow_0003498479_append_arrays_debugging_python.txt
Q: I'm having trouble opening a Python file :( I saved a file as DictionaryE.txt in a Modules folder I created within Python. Then I type: fh = open("DictionaryE.txt") I get this error message: Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> fh = open("DictionaryE.txt") IOError: [Er...
I'm having trouble opening a Python file :(
I saved a file as DictionaryE.txt in a Modules folder I created within Python. Then I type: fh = open("DictionaryE.txt") I get this error message: Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> fh = open("DictionaryE.txt") IOError: [Errno 2] No such file or directory: 'DictionaryE.tx...
[ "As other answers suggested, you need to specify the file's path, not just the name.\nFor example, if you know the file is in C:\\Blah\\Modules, use\nfh = open('c:/Blah/Modules/DictionaryE.txt')\n\nNote that I've turned the slashes \"the right way up\" (Unix-style;-) rather than \"the Windows way\". That's optiona...
[ 3, 1, 0, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0003498688_file_python.txt
Q: Using numpy's flatten_dtype with structured dtypes that have titles I usually don't post questions on these forums, but I've searched all over the place and I haven't found anything about this issue. I am working with structured arrays to store experimental data. I'm using titles to store information about my fiel...
Using numpy's flatten_dtype with structured dtypes that have titles
I usually don't post questions on these forums, but I've searched all over the place and I haven't found anything about this issue. I am working with structured arrays to store experimental data. I'm using titles to store information about my fields, in this case the units of measure. When I call numpy.lib.io.flatten_d...
[ "Here is a possible workaround:\nSince your custom dtype causes a problem, supply a flattened dtype instead:\nIn [77]: arr=np.genfromtxt('a',dtype='f8,f8')\n\nIn [78]: arr\nOut[78]: \narray([(1.0, 2.0), (3.0, 4.0)], \n dtype=[('f0', '<f8'), ('f1', '<f8')])\n\nThen use astype to convert to your desired dtype:\n...
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003498603_numpy_python.txt
Q: Software Validation Server in Python? I have been working on a huge project for work for a while now, and it is almost done. However, in an effort to prevent the program was being pirated (I already know there is pretty much no method that can't be cracked ), the software needs to be able to validate. I'm not exac...
Software Validation Server in Python?
I have been working on a huge project for work for a while now, and it is almost done. However, in an effort to prevent the program was being pirated (I already know there is pretty much no method that can't be cracked ), the software needs to be able to validate. I'm not exactly sure how to do this. Could some sort of...
[ "The software, when starting, should launch an https (so it can't just be sniffed easily;-) request to your server, identifying itself (however it is that you choose to identify, e.g. a serial number or whatever), and the server's response will tell it what to do (run normally, or terminate, or ask the user to regi...
[ 2, 0 ]
[]
[]
[ "python", "validation", "windows" ]
stackoverflow_0003498904_python_validation_windows.txt
Q: python package get imported automatically when importing a global from a module Let's say I have these files: - package1/ - __init__.py - package2/ - __init__.py - module1.py Content of package1/__init__.py: from package2.module1 import var1 print package2 Empty package1/package2/__init__.py Content ...
python package get imported automatically when importing a global from a module
Let's say I have these files: - package1/ - __init__.py - package2/ - __init__.py - module1.py Content of package1/__init__.py: from package2.module1 import var1 print package2 Empty package1/package2/__init__.py Content of package1/package2/module1.py: var1 = 123 The question is why would package2 get i...
[ "When you import a module from within a package the package is always imported (loaded, if it's not already in sys.modules) first -- which may have the side effect of binding the package's name in the importing module, though that's not guaranteed (depends on the Python implementation and version).\nAnd, importing ...
[ 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003498929_import_python.txt
Q: What is the working of web Crawler? Will web crawler crawl the web and create a database of the web or it will just create a searchable index of web? If suppose it creates an index, who will exactly will gather the data of web pages and store it in database? A: Though the question is slightly vague Let me puts s...
What is the working of web Crawler?
Will web crawler crawl the web and create a database of the web or it will just create a searchable index of web? If suppose it creates an index, who will exactly will gather the data of web pages and store it in database?
[ "Though the question is slightly vague Let me puts some words to clarify.\n\nCrawler makes http request of a URL and analyse the information of that web page. Say for example it makes a http req. http://www.example.com it retrieves the content of the page.\nOnce it gets the content of the page it analyse it. Now co...
[ 2 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003498962_php_python.txt
Q: Google app engine images API - get image size How can I get the size of an image transformed with the app engine images API? Note: I mean the size in bytes, not the dimensions. A: execute_transforms returns a str (bytestring), so you can just call len(image_str).
Google app engine images API - get image size
How can I get the size of an image transformed with the app engine images API? Note: I mean the size in bytes, not the dimensions.
[ "execute_transforms returns a str (bytestring), so you can just call len(image_str).\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "image", "python", "upload" ]
stackoverflow_0003499060_google_app_engine_image_python_upload.txt
Q: How should I structure a video streaming web app? I want a user to be able to create an account and upload a video to the site. How should I structure this web app, how should I start thinking about the project, how should I store the videos, and what stack would you recommend for this project? How should I think ...
How should I structure a video streaming web app?
I want a user to be able to create an account and upload a video to the site. How should I structure this web app, how should I start thinking about the project, how should I store the videos, and what stack would you recommend for this project? How should I think about the front-end, the server, and the database? The ...
[ "I'd start by breaking it down into more manageable chunks.\n\nA python web framework to work in:\n\n\nDjango\nPylons\nGoogle App Engine (webapp)\n\nVideo storage solution:\n\n\nAmazon S3\nAmazon CloudFront (for proper H.264 streaming instead of progressive download)\nGoogle Storage\nCacheFly\nEtc.\n\nVideo metadat...
[ 16 ]
[]
[]
[ "python", "video", "video_streaming", "web_applications" ]
stackoverflow_0003499227_python_video_video_streaming_web_applications.txt
Q: Referencing list entries within a for loop without indexes, possible? A question of particular interest about python for loops. Engineering programs often require values at previous or future indexes, such as: for i in range(0,n): value = 0.3*list[i-1] + 0.5*list[i] + 0.2*list[i+1] etc... However I rather lik...
Referencing list entries within a for loop without indexes, possible?
A question of particular interest about python for loops. Engineering programs often require values at previous or future indexes, such as: for i in range(0,n): value = 0.3*list[i-1] + 0.5*list[i] + 0.2*list[i+1] etc... However I rather like the nice clean python syntax: for item in list: #Do stuff with item i...
[ "Here's a recipe, based on the itertools pairwise code, which does general n-wise grouping:\nimport itertools\n\ndef nwise(iterable, n=2):\n \"s->(s_0,s_1, ..., s_n), (s_1,s_2,..., s_n+1), ... \"\n ntup = itertools.tee(iterable, n)\n for i, item in enumerate(ntup):\n for ii in range(i):\n ...
[ 4, 2, 1, 0 ]
[]
[]
[ "indexing", "loops", "python" ]
stackoverflow_0003499130_indexing_loops_python.txt
Q: Convert Hexadecimal MAC address to user readable formatting (Python) I'm receiving from the socket a MAC address in this format: 0024e865a023 (hex converted from binary with received-string.encode("hex")) I would like to convert it to a user readable format like this : 00-24-e8-65-a0-23 Any easy way to do so? A: ...
Convert Hexadecimal MAC address to user readable formatting (Python)
I'm receiving from the socket a MAC address in this format: 0024e865a023 (hex converted from binary with received-string.encode("hex")) I would like to convert it to a user readable format like this : 00-24-e8-65-a0-23 Any easy way to do so?
[ "You can break apart the MAC address into an array of each block, and then join them on -:\nmac = '0024e865a023'\nblocks = [mac[x:x+2] for x in xrange(0, len(mac), 2)]\nmacFormatted = '-'.join(blocks)\n\n" ]
[ 6 ]
[]
[]
[ "bin", "hex", "macos", "python" ]
stackoverflow_0003499510_bin_hex_macos_python.txt
Q: Erase whole array Python How do I erase a whole array, leaving it with no items? I want to do this so I can store new values in it (a new set of 100 floats) and find the minimum. Right now my program is reading the minimum from sets before I think because it is appending itself with the previous set still in there...
Erase whole array Python
How do I erase a whole array, leaving it with no items? I want to do this so I can store new values in it (a new set of 100 floats) and find the minimum. Right now my program is reading the minimum from sets before I think because it is appending itself with the previous set still in there. I use .append by the way.
[ "Note that list and array are different classes. You can do:\ndel mylist[:]\n\nThis will actually modify your existing list. David's answer creates a new list and assigns it to the same variable. Which you want depends on the situation (e.g. does any other variable have a reference to the same list?).\nTry:\na =...
[ 57, 35, 9, 1 ]
[]
[]
[ "arrays", "erase", "python" ]
stackoverflow_0003499233_arrays_erase_python.txt
Q: find value of forloop at which event occurred Python hey guys, this is very confusing... i am trying to find the minimum of an array by: for xpre in range(100): #used pre because I am using vapor pressures with some x molarity xvalue=xarray[xpre] for ppre in range(100): #same as xpre but vapor ...
find value of forloop at which event occurred Python
hey guys, this is very confusing... i am trying to find the minimum of an array by: for xpre in range(100): #used pre because I am using vapor pressures with some x molarity xvalue=xarray[xpre] for ppre in range(100): #same as xpre but vapor pressures for pure water, p pvalue=parray[p] ...
[ "A couple things: \n\nTry enumerate\nInstead of darr being a list, use a dict and store the dvp values as keys, with the xindex and pindex variables as values\n\nHere's the code\nfor xindex, xvalue in enumerate(xarr):\n darr = {}\n for pindex, pvalue in enumerate(parr):\n dvp = math.fabs(xvalue - pvalue)\n ...
[ 2, 0 ]
[]
[]
[ "arrays", "for_loop", "minimum", "python" ]
stackoverflow_0003499620_arrays_for_loop_minimum_python.txt
Q: Efficient way of phrasing multiple tuple pair WHERE conditions in SQL statement I want to perform an SQL query that is logically equivalent to the following: DELETE FROM pond_pairs WHERE ((pond1 = 12) AND (pond2 = 233)) OR ((pond1 = 12) AND (pond2 = 234)) OR ((pond1 = 12) AND (pond2 = 8)) OR ((pond1 = 13) ...
Efficient way of phrasing multiple tuple pair WHERE conditions in SQL statement
I want to perform an SQL query that is logically equivalent to the following: DELETE FROM pond_pairs WHERE ((pond1 = 12) AND (pond2 = 233)) OR ((pond1 = 12) AND (pond2 = 234)) OR ((pond1 = 12) AND (pond2 = 8)) OR ((pond1 = 13) AND (pond2 = 6547)) OR ((pond1 = 13879) AND (pond2 = 6)) I will have hundreds of t...
[ "I will do 3. (with JOIN rather than subquery) and measure time of DELETE query (without creating table and inserting). This is good starting point, because JOINing is very common and optimized procedure, so It will be hard to beat that time. Then you can compare that time to your current approach.\nAlso you can tr...
[ 1, 1, 0 ]
[]
[]
[ "optimization", "postgresql", "python", "sql" ]
stackoverflow_0003499613_optimization_postgresql_python_sql.txt
Q: Python - Writing to a text file using functions? i wrote a simple function to write into a text file. like this, def write_func(var): var = str(var) myfile.write(var) a= 5 b= 5 c= a + b write_func(c) this will write the output to a desired file. now, i want the output in another format. say, write...
Python - Writing to a text file using functions?
i wrote a simple function to write into a text file. like this, def write_func(var): var = str(var) myfile.write(var) a= 5 b= 5 c= a + b write_func(c) this will write the output to a desired file. now, i want the output in another format. say, write_func("Output is :"+c) so that the output will have a...
[ "You can't add/concatenate a string and integer directly.\nIf you do anything more complicated than \"string :\"+str(number), I would strongly recommend using string formatting:\nwrite_func('Output is: %i' % (c))\n\n", "Simple, you do:\nwrite_func('Output is' + str(c))\n\nYou have to convert c to a string before ...
[ 3, 2, 2, 1 ]
[]
[]
[ "file_io", "function", "python" ]
stackoverflow_0003499961_file_io_function_python.txt
Q: Can you use Python v. 2.7 with Django? The Django book says: "The core Django framework works with any Python version from 2.3 to 2.6, inclusive. Django’s optional GIS (Geographic Information Systems) support requires Python 2.4 to 2.6." A: From Django's FAQ: Currently, Django itself officially supports any ver...
Can you use Python v. 2.7 with Django?
The Django book says: "The core Django framework works with any Python version from 2.3 to 2.6, inclusive. Django’s optional GIS (Geographic Information Systems) support requires Python 2.4 to 2.6."
[ "From Django's FAQ:\n\nCurrently, Django itself officially supports any version of Python from 2.4 through 2.7, inclusive. \n\nThe Django Book (2nd edition) is written for Django version 1.0, while the latest release of Django is version 1.2.1, hence the difference.\n" ]
[ 6 ]
[]
[]
[ "compatibility", "django", "python" ]
stackoverflow_0003500160_compatibility_django_python.txt