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: Google App Engine dev_appserver can't find PIL (I've installed it) I recently upgraded my Google App Engine launcher on my Mac, running OSX 10.5.8, and afterwards my projects that work with images stopped working locally. It seems to be the same problem that I had when first using GAE locally to work with images, before I installed PIL. Here is the error I get: SystemError: Parent module 'PIL' not loaded I have PIL installed. When I run python normally, I can access it and work with it as expected. I also checked to ensure that dev_appserver.py was running the same version of Python. If I open the interpreter and type sys.version I get this back: 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] This is identical to what I get when I display the sys.version from my projects running through dev_appserver. Any thoughts on why dev_appserver can't find the PIL module? I have been banging my head against this for a bit. Thank you! A: You may be suffering from the problems I was explaining here, specifically, I think...: You need to find another way to extend Python sys.path's appropriately. The simplest way is to make a file named PIL.pth with a single-line content: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages and place that PIL.pth in any of the directories that all Python processes see; in my case, I used /Library/Python/2.5/site-packages/ -- but that directory is not available in a pristine installation of Mac OS X 10.5 so you may have to use some other directory.
Google App Engine dev_appserver can't find PIL (I've installed it)
I recently upgraded my Google App Engine launcher on my Mac, running OSX 10.5.8, and afterwards my projects that work with images stopped working locally. It seems to be the same problem that I had when first using GAE locally to work with images, before I installed PIL. Here is the error I get: SystemError: Parent module 'PIL' not loaded I have PIL installed. When I run python normally, I can access it and work with it as expected. I also checked to ensure that dev_appserver.py was running the same version of Python. If I open the interpreter and type sys.version I get this back: 2.5 (r25:51918, Sep 19 2006, 08:49:13) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] This is identical to what I get when I display the sys.version from my projects running through dev_appserver. Any thoughts on why dev_appserver can't find the PIL module? I have been banging my head against this for a bit. Thank you!
[ "You may be suffering from the problems I was explaining here, specifically, I think...:\n\nYou need to find another way to extend Python sys.path's\n appropriately. The simplest way is to\n make a file named PIL.pth with a\n single-line content:\n/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages\nand place that PIL.pth in any of the\n directories that all Python processes\n see; in my case, I used\n /Library/Python/2.5/site-packages/ --\n but that directory is not available in\n a pristine installation of Mac OS X\n 10.5 so you may have to use some other directory.\n\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002813742_google_app_engine_python.txt
Q: Windows 7 Task Scheduler Very new to this, and I have no idea where to start. I want to schedule a python script using Task Scheduler in Windows 7. When I add a "New Action", I place the following command as the script/program : c:\python25\python.exe As the argument, I add the full path to the location of my python script path\script.py Here is my script: import datetime import csv import os now = datetime.datetime.now() print str(now) os.chdir('C:/Users/Brock/Desktop/') print os.getcwd() writer = csv.writer(open("test task.csv", "wb")) row = ('This is a test', str(now)) writer.writerow(row) I got an error saying the script could not run. Any help you can provide to get me up and running will be very much appreciated! Thanks, Brock A: Not sure how to do it properly through the GUI, but see here for a nice solution involving the schtasks command.
Windows 7 Task Scheduler
Very new to this, and I have no idea where to start. I want to schedule a python script using Task Scheduler in Windows 7. When I add a "New Action", I place the following command as the script/program : c:\python25\python.exe As the argument, I add the full path to the location of my python script path\script.py Here is my script: import datetime import csv import os now = datetime.datetime.now() print str(now) os.chdir('C:/Users/Brock/Desktop/') print os.getcwd() writer = csv.writer(open("test task.csv", "wb")) row = ('This is a test', str(now)) writer.writerow(row) I got an error saying the script could not run. Any help you can provide to get me up and running will be very much appreciated! Thanks, Brock
[ "Not sure how to do it properly through the GUI, but see here for a nice solution involving the schtasks command.\n" ]
[ 2 ]
[]
[]
[ "python", "scheduled_tasks" ]
stackoverflow_0002815820_python_scheduled_tasks.txt
Q: python-xmpp and looping through list of recipients to receive and IM message I can't figure out the problem and want some input as to whether my Python code is incorrect, or if this is an issue or design limitation of Python XMPP library. I'm new to Python by the way. Here's snippets of code in question below. What I'd like to do is read in a text file of IM recipients, one recipient per line, in XMPP/Jabber ID format. This is read into a Python list variable. I then instantiate an XMPP client session and loop through the list of recipients and send a message to each recipient. Then sleep some time and repeat test. This is for load testing the IM client of recipients as well as IM server. There is code to alternately handle case of taking only one recipient from command line input instead of from file. What ends up happening is that Python does iterate/loop through the list but only last recipient in list receives message. Switch order of recipients to verify. Kind of looks like Python XMPP library is not sending it out right, or I'm missing a step with the library calls, because the debug print statements during runtime indicate the looping works correctly. recipient = "" delay = 60 useFile = False recList = [] ... elif (sys.argv[i] == '-t'): recipient = sys.argv[i+1] useFile = False elif (sys.argv[i] == '-tf'): fil = open(sys.argv[i+1], 'r') recList = fil.readlines() fil.close() useFile = True ... # disable debug msgs cnx = xmpp.Client(svr,debug=[]) cnx.connect(server=(svr,5223)) cnx.auth(user,pwd,'imbot') cnx.sendInitPresence() while (True): if useFile: for listUser in recList: cnx.send(xmpp.Message(listUser,msg+str(msgCounter))) print "sending to "+listUser+" msg = "+msg+str(msgCounter) else: cnx.send(xmpp.Message(recipient,msg+str(msgCounter))) msgCounter += 1 time.sleep(delay) A: Never mind, found the problem. One has to watch out for the newline characters at the end of a line for the elements in a list returned by file.readlines(), so I had to strip it out with .rstrip('\n') on the element when sending out message.
python-xmpp and looping through list of recipients to receive and IM message
I can't figure out the problem and want some input as to whether my Python code is incorrect, or if this is an issue or design limitation of Python XMPP library. I'm new to Python by the way. Here's snippets of code in question below. What I'd like to do is read in a text file of IM recipients, one recipient per line, in XMPP/Jabber ID format. This is read into a Python list variable. I then instantiate an XMPP client session and loop through the list of recipients and send a message to each recipient. Then sleep some time and repeat test. This is for load testing the IM client of recipients as well as IM server. There is code to alternately handle case of taking only one recipient from command line input instead of from file. What ends up happening is that Python does iterate/loop through the list but only last recipient in list receives message. Switch order of recipients to verify. Kind of looks like Python XMPP library is not sending it out right, or I'm missing a step with the library calls, because the debug print statements during runtime indicate the looping works correctly. recipient = "" delay = 60 useFile = False recList = [] ... elif (sys.argv[i] == '-t'): recipient = sys.argv[i+1] useFile = False elif (sys.argv[i] == '-tf'): fil = open(sys.argv[i+1], 'r') recList = fil.readlines() fil.close() useFile = True ... # disable debug msgs cnx = xmpp.Client(svr,debug=[]) cnx.connect(server=(svr,5223)) cnx.auth(user,pwd,'imbot') cnx.sendInitPresence() while (True): if useFile: for listUser in recList: cnx.send(xmpp.Message(listUser,msg+str(msgCounter))) print "sending to "+listUser+" msg = "+msg+str(msgCounter) else: cnx.send(xmpp.Message(recipient,msg+str(msgCounter))) msgCounter += 1 time.sleep(delay)
[ "Never mind, found the problem. One has to watch out for the newline characters at the end of a line for the elements in a list returned by file.readlines(), so I had to strip it out with .rstrip('\\n') on the element when sending out message.\n" ]
[ 2 ]
[]
[]
[ "python", "xmpp", "xmpppy" ]
stackoverflow_0002815851_python_xmpp_xmpppy.txt
Q: Why doesn't this work? take = raw_input('Please enter the string of numbers that compose code\n\n\t') y = str(take) l = [] for i in xrange(0, len(y), 3): l.append(str(y[i:i+3])) b = len(l) a = 0 while(a!=b): c = l[a].replace('444', ' ') c = l[a].replace('111', 'a') c = l[a].replace('112', 'b') c = l[a].replace('113', 'c') c = l[a].replace('114', 'd') c = l[a].replace('115', 'e') etc... a = a + 1 filename = 'decmes.txt' file = open(filename, 'w') file.write(c) file.close() I can enter anything, just 111 for example and it gives me back the same thing I put in. Maybe it's something dumb, but I can't figure it out. Suppose i wanted it to say bad, I would type 112111114. It should give me bad, but it doesn't. A: It's not immediately obvious to me what you are trying to do, but maybe you mean this? c = '' while(a!=b): c += l[a].replace('444', ' ') \ .replace('111', 'a') \ .replace('112', 'b') \ .replace('113', 'c') \ .replace('114', 'd') \ .replace('115', 'e') a = a + 1 There are a number of style issues here though. Here are some examples: Your line y = str(take) is unnecessary. take is already a string. You should use something like a dictionary define the replacements instead of a long list of replace statements. You could consider using the grouper recipe from itertools instead of writing it yourself. Your while loop is very C like. Consider using for x in l: instead. A: It looks to me like you're repeatedly overwriting c. So your final result would be this (for the highest value of a): c = l[a].replace('115', 'e') (assuming that's the last replacement in the sequence). All of the other lines of code in that sequence would have no effect. A: This code makes my mind explode in agony. However, I think this will be your solution: Before the while loop, do a c="" then change the c = to c += A: You absolutely need to get familiar with dictionaries! Try sth like code_dict = {'444': ' ', '111': 'a', '112': 'b', ...} and then make your replacements via c = "".join([code_dict[part] for part in l]) instead of the whole while a!=b loop.
Why doesn't this work?
take = raw_input('Please enter the string of numbers that compose code\n\n\t') y = str(take) l = [] for i in xrange(0, len(y), 3): l.append(str(y[i:i+3])) b = len(l) a = 0 while(a!=b): c = l[a].replace('444', ' ') c = l[a].replace('111', 'a') c = l[a].replace('112', 'b') c = l[a].replace('113', 'c') c = l[a].replace('114', 'd') c = l[a].replace('115', 'e') etc... a = a + 1 filename = 'decmes.txt' file = open(filename, 'w') file.write(c) file.close() I can enter anything, just 111 for example and it gives me back the same thing I put in. Maybe it's something dumb, but I can't figure it out. Suppose i wanted it to say bad, I would type 112111114. It should give me bad, but it doesn't.
[ "It's not immediately obvious to me what you are trying to do, but maybe you mean this?\nc = ''\nwhile(a!=b):\n c += l[a].replace('444', ' ') \\\n .replace('111', 'a') \\\n .replace('112', 'b') \\\n .replace('113', 'c') \\\n .replace('114', 'd') \\\n .replace('115', 'e')\n a = a + 1\n\nThere are a number of style issues here though. Here are some examples:\n\nYour line y = str(take) is unnecessary. take is already a string.\nYou should use something like a dictionary define the replacements instead of a long list of replace statements.\nYou could consider using the grouper recipe from itertools instead of writing it yourself.\nYour while loop is very C like. Consider using for x in l: instead.\n\n", "It looks to me like you're repeatedly overwriting c.\nSo your final result would be this (for the highest value of a):\nc = l[a].replace('115', 'e')\n\n(assuming that's the last replacement in the sequence).\nAll of the other lines of code in that sequence would have no effect.\n", "This code makes my mind explode in agony. However, I think this will be your solution:\nBefore the while loop, do a c=\"\" then change the c = to c +=\n", "You absolutely need to get familiar with dictionaries!\nTry sth like\ncode_dict = {'444': ' ',\n '111': 'a',\n '112': 'b',\n ...}\n\nand then make your replacements via\nc = \"\".join([code_dict[part] for part in l])\n\ninstead of the whole while a!=b loop.\n" ]
[ 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002814982_python.txt
Q: Can I start up terminal, make it open the python interactive shell and run a few python statements with the same command in os x? I often do this to prepare for some django debugging: Open up a terminal window in os x (10.6) start the python interpreter run these commands in python: from django.core.management import setup_environ import settings setup_environ(settings) Is it possible to automate these actions and make a shortcut that I can doubleclick to invoke? A: If you use django you should consider running the command python manage.py shell to debug django applications. Even better, try the shell_plus command from the excellent django command extension add-on. A: You can use the PYTHONSTARTUP environment variable to your advantage here if you want to throw that in a script and then have a batch file load up a shell with that environment variable.
Can I start up terminal, make it open the python interactive shell and run a few python statements with the same command in os x?
I often do this to prepare for some django debugging: Open up a terminal window in os x (10.6) start the python interpreter run these commands in python: from django.core.management import setup_environ import settings setup_environ(settings) Is it possible to automate these actions and make a shortcut that I can doubleclick to invoke?
[ "If you use django you should consider running the command python manage.py shell to debug django applications.\nEven better, try the shell_plus command from the excellent django command extension add-on.\n", "You can use the PYTHONSTARTUP environment variable to your advantage here if you want to throw that in a script and then have a batch file load up a shell with that environment variable.\n" ]
[ 2, 0 ]
[]
[]
[ "macos", "python", "shell", "terminal" ]
stackoverflow_0002816749_macos_python_shell_terminal.txt
Q: JQuery getJSON Callback Returning Null Data I have a getJSON call that is called back correctly, but the data variable is null. The python code posted below is executed by the getJSON call to the demandURL. Any ideas? javascript: var demandURL = "/demand/washington/"; $.getJSON(demandURL, function(data) { console.log(data); }); python: data = {"demand_count":"one"} json = simplejson.dumps(data) return HttpResponse(json, mimetype="application/json") A: Switch out your getJSON with an ajax call so you can have a look at the error message. Try something like this: $.ajax({ url: url, dataType: 'json', data: data, success: function(data) { console.log(data); }, error: function(XMLHttpRequest, textStatus, errorThrown) { console.log(textStatus, errorThrown); } });
JQuery getJSON Callback Returning Null Data
I have a getJSON call that is called back correctly, but the data variable is null. The python code posted below is executed by the getJSON call to the demandURL. Any ideas? javascript: var demandURL = "/demand/washington/"; $.getJSON(demandURL, function(data) { console.log(data); }); python: data = {"demand_count":"one"} json = simplejson.dumps(data) return HttpResponse(json, mimetype="application/json")
[ "Switch out your getJSON with an ajax call so you can have a look at the error message. Try something like this:\n$.ajax({\n url: url,\n dataType: 'json',\n data: data,\n success: function(data) {\n console.log(data);\n },\n error: function(XMLHttpRequest, textStatus, errorThrown) {\n console.log(textStatus, errorThrown);\n }\n});\n\n" ]
[ 0 ]
[]
[]
[ "getjson", "javascript", "jquery", "null", "python" ]
stackoverflow_0002815171_getjson_javascript_jquery_null_python.txt
Q: Store value of os.system or os.popen I want to grep the error's out of a log file and save the value as an error. When I use: errors = os.system("cat log.txt | grep 'ERROR' | wc -l") I get the return code that the command worked or not. When I use: errors = os.popen("cat log.txt | grep 'ERROR' | wc -l") I get what the command is trying to do. When I run this in the command line I get 3 as thats how many errors there are. Can anyone suggest another way in Python that will allow me to save the value of this bash command? Thanks A: popen is deprecated. Use subprocess instead. For example, in your case: p1 = Popen(["cat", "log.txt"], stdout=PIPE) p2 = Popen(["grep", "ERROR"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] A: First open a pipe using popen as you did. p = os.popen("cat log.txt | grep 'ERROR' | wc -l") Now just access the pipe like a normal file: output = p.readline() This will be a string so you'll still have to do some additional parsing, but that shouldn't be a problem. EDIT: Ok, it seems that from Python 2.6 onwards, os.popen is deprecated. I thus defer my answer to whoever answered correctly using subprocess.Popen instead. Thanks for that guys. A: You're probably looking for: grep -c 'ERROR' log.txt Generally for spawning a subprocess you need to use subprocess module. There are plenty example, I'm sure you wouldn't get lost. A: How many 'ERROR' in the file: nerrors = open('log.txt').read().count('ERROR') # put whole file in memory How many lines that contain 'ERROR': nerrors = sum(1 for line in open('log.txt') if 'ERROR' in line) # line at a time If you must use the literal bash line then in Python 2.7+: from subprocess import check_output as qx nerrors = int(qx("cat your_file.txt | grep 'ERROR' | wc -l", shell=True)) See Capturing system command output as a string for an implementation of check_output() for Python < 2.7.
Store value of os.system or os.popen
I want to grep the error's out of a log file and save the value as an error. When I use: errors = os.system("cat log.txt | grep 'ERROR' | wc -l") I get the return code that the command worked or not. When I use: errors = os.popen("cat log.txt | grep 'ERROR' | wc -l") I get what the command is trying to do. When I run this in the command line I get 3 as thats how many errors there are. Can anyone suggest another way in Python that will allow me to save the value of this bash command? Thanks
[ "popen is deprecated. Use subprocess instead. For example, in your case:\np1 = Popen([\"cat\", \"log.txt\"], stdout=PIPE)\np2 = Popen([\"grep\", \"ERROR\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n\n", "First open a pipe using popen as you did.\np = os.popen(\"cat log.txt | grep 'ERROR' | wc -l\")\n\nNow just access the pipe like a normal file:\noutput = p.readline()\n\nThis will be a string so you'll still have to do some additional parsing, but that shouldn't be a problem.\nEDIT: Ok, it seems that from Python 2.6 onwards, os.popen is deprecated. I thus defer my answer to whoever answered correctly using subprocess.Popen instead. Thanks for that guys.\n", "You're probably looking for:\ngrep -c 'ERROR' log.txt\n\nGenerally for spawning a subprocess you need to use subprocess module. There are plenty example, I'm sure you wouldn't get lost.\n", "How many 'ERROR' in the file:\nnerrors = open('log.txt').read().count('ERROR') # put whole file in memory\n\nHow many lines that contain 'ERROR':\nnerrors = sum(1 for line in open('log.txt') if 'ERROR' in line) # line at a time\n\nIf you must use the literal bash line then in Python 2.7+:\nfrom subprocess import check_output as qx\nnerrors = int(qx(\"cat your_file.txt | grep 'ERROR' | wc -l\", shell=True))\n\nSee Capturing system command output as a string for an implementation of check_output() for Python < 2.7.\n" ]
[ 6, 2, 1, 0 ]
[]
[]
[ "bash", "operating_system", "python" ]
stackoverflow_0002817416_bash_operating_system_python.txt
Q: OpenSSL signing and Google App Engine Is there a way to sign values with a PEM formatted private key in Google App Engine (Python)? For example in PHP it could be achieved like this: $key = openssl_pkey_get_private($privateKey); openssl_sign($strToBeSigned, $signature, $key); echo "signature: ".base64_encode($signature); Is there a way to do the same thing with Python in Google App Engine? A: Try taking a look at this question's answers, and the link to the google group discussion to see if that helps. Signing a string with RSA private key on Google App Engine Python SDK
OpenSSL signing and Google App Engine
Is there a way to sign values with a PEM formatted private key in Google App Engine (Python)? For example in PHP it could be achieved like this: $key = openssl_pkey_get_private($privateKey); openssl_sign($strToBeSigned, $signature, $key); echo "signature: ".base64_encode($signature); Is there a way to do the same thing with Python in Google App Engine?
[ "Try taking a look at this question's answers, and the link to the google group discussion to see if that helps.\nSigning a string with RSA private key on Google App Engine Python SDK\n" ]
[ 1 ]
[]
[]
[ "cryptography", "google_app_engine", "openssl", "python" ]
stackoverflow_0002813571_cryptography_google_app_engine_openssl_python.txt
Q: In Python, urllib2 giving error I tried running this, >>> urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') But it is giving error like this, can anyone tell me a solution ? Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') File "C:\Python26\lib\urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "C:\Python26\lib\urllib2.py", line 391, in open response = self._open(req, data) File "C:\Python26\lib\urllib2.py", line 409, in _open '_open', req) File "C:\Python26\lib\urllib2.py", line 369, in _call_chain result = func(*args) File "C:\Python26\lib\urllib2.py", line 1161, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python26\lib\urllib2.py", line 1136, in do_open raise URLError(err) URLError: <urlopen error [Errno 11001] getaddrinfo failed> A: Double check domain is accessible or not. I am getting 504 Gateway Timeout error here for domain - tycho.usno.navy.mil , at the moment. Looks like the site is down, also downforeveryoneorjustme.com says that It's not just you! http://tycho.usno.navy.mil looks down from here. Thats why getaddrinfo is failing A: Wrapping in try..except could help keep it neat: try: urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') except URLError: print "Error opening URL"
In Python, urllib2 giving error
I tried running this, >>> urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') But it is giving error like this, can anyone tell me a solution ? Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') File "C:\Python26\lib\urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "C:\Python26\lib\urllib2.py", line 391, in open response = self._open(req, data) File "C:\Python26\lib\urllib2.py", line 409, in _open '_open', req) File "C:\Python26\lib\urllib2.py", line 369, in _call_chain result = func(*args) File "C:\Python26\lib\urllib2.py", line 1161, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python26\lib\urllib2.py", line 1136, in do_open raise URLError(err) URLError: <urlopen error [Errno 11001] getaddrinfo failed>
[ "Double check domain is accessible or not.\nI am getting 504 Gateway Timeout error here for domain - tycho.usno.navy.mil , at the moment.\nLooks like the site is down, also downforeveryoneorjustme.com says that \n\nIt's not just you!\n http://tycho.usno.navy.mil looks down\n from here.\n\nThats why getaddrinfo is failing \n", "Wrapping in try..except could help keep it neat: \ntry:\n urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl')\nexcept URLError:\n print \"Error opening URL\"\n\n" ]
[ 4, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0002818098_python_urllib2.txt
Q: Dynamically calling functions - Python I have a list of functions... e.g. def filter_bunnies(pets): ... def filter_turtles(pets): ... def filter_narwhals(pets): ... Is there a way to call these functions by using a string representing their name? e.g. 'filter_bunnies', 'filter_turtles', 'filter_narwhals' A: Are your function a part of an object? If so you could use getattr function: >> class A: def filter_bunnies(self, pets): print('bunnies') >>> getattr(A(), 'filter_bunnies')(1) bunnies A: Yes, you can use: globals()['filter_bunnies']() to call 'filter_bunnies'. A: You can use the built-in function locals() to get a dictionary of variables and functions, here is an example: def a(str): print("A" + str) def b(str): print("B" + str) def c(str): print("C" + str) for f in ['a', 'b', 'c']: locals()[f]('hello') A: My code crystal ball detects that there may be some commonality among your filter functions. Are they really different functions, or are they all the same with just a single filter value that is different? If you have substantial repetition in a program, stop and think if it is worth some refactoring into a single common function, which will be much more maintainable than a set of very similar functions. You could have a single function filterByType that takes 2 arguments, the list of pets and the filtering type, and then just define a dict to map input strings to the type object or class that you mean to filter by. A: using eval? A: See the eval function. A: The easiest and ugliest way would be to call it by using eval function, which would evaluate your string. Much cleaner solution is to use getattr function on a module to which function belongs to obtain function's reference, and then call it by reference. Another way that just occurred to me to obtain function-s reference would be with use of eval function like this func = eval("filter_bunnies") Be careful when you're using eval, especially if the value of eval is dependent on some sort of user input as it could make you execute unwanted/malicious code. A: Usually, when I need to dispatch a function call to one of several functions based on a string, I will make the functions elements of a dict. I've done this, for example, in writing a simple interpreter, where each keyword is implemented by a different function. You can even use decorators to elegantly take care of the assignments: KEYWORD_FUNCTIONS = {} def MAKE_KEYWORD( f ): KEYWORD_FUNCTIONS[ f.func_name ] = f return f @MAKE_KEYWORD def KEYWORD_A( arg ): print "Keyword A with arg %s" % arg @MAKE_KEYWORD def KEYWORD_B( arg ): print "Keyword B with arg %s" % arg if __name__ == "__main__": KEYWORD_FUNCTIONS[ "KEYWORD_A" ]( "first_argument" ) KEYWORD_FUNCTIONS[ "KEYWORD_B" ]( "second_argument" )
Dynamically calling functions - Python
I have a list of functions... e.g. def filter_bunnies(pets): ... def filter_turtles(pets): ... def filter_narwhals(pets): ... Is there a way to call these functions by using a string representing their name? e.g. 'filter_bunnies', 'filter_turtles', 'filter_narwhals'
[ "Are your function a part of an object? If so you could use getattr function:\n>> class A:\n def filter_bunnies(self, pets):\n print('bunnies')\n\n>>> getattr(A(), 'filter_bunnies')(1)\nbunnies\n\n", "Yes, you can use:\nglobals()['filter_bunnies']()\n\nto call 'filter_bunnies'.\n", "You can use the built-in function locals() to get a dictionary of variables and functions, here is an example:\ndef a(str):\n print(\"A\" + str)\n\ndef b(str):\n print(\"B\" + str)\n\ndef c(str):\n print(\"C\" + str)\n\nfor f in ['a', 'b', 'c']:\n locals()[f]('hello')\n\n", "My code crystal ball detects that there may be some commonality among your filter functions. Are they really different functions, or are they all the same with just a single filter value that is different? If you have substantial repetition in a program, stop and think if it is worth some refactoring into a single common function, which will be much more maintainable than a set of very similar functions. You could have a single function filterByType that takes 2 arguments, the list of pets and the filtering type, and then just define a dict to map input strings to the type object or class that you mean to filter by.\n", "using eval?\n", "See the eval function.\n", "The easiest and ugliest way would be to call it by using eval function, which would evaluate your string. Much cleaner solution is to use getattr function on a module to which function belongs to obtain function's reference, and then call it by reference.\nAnother way that just occurred to me to obtain function-s reference would be with use of eval function like this func = eval(\"filter_bunnies\")\nBe careful when you're using eval, especially if the value of eval is dependent on some sort of user input as it could make you execute unwanted/malicious code.\n", "Usually, when I need to dispatch a function call to one of several functions based on a string, I will make the functions elements of a dict. I've done this, for example, in writing a simple interpreter, where each keyword is implemented by a different function. You can even use decorators to elegantly take care of the assignments:\nKEYWORD_FUNCTIONS = {}\n\ndef MAKE_KEYWORD( f ):\n KEYWORD_FUNCTIONS[ f.func_name ] = f\n return f\n\n@MAKE_KEYWORD\ndef KEYWORD_A( arg ):\n print \"Keyword A with arg %s\" % arg\n\n@MAKE_KEYWORD\ndef KEYWORD_B( arg ):\n print \"Keyword B with arg %s\" % arg\n\nif __name__ == \"__main__\":\n KEYWORD_FUNCTIONS[ \"KEYWORD_A\" ]( \"first_argument\" )\n KEYWORD_FUNCTIONS[ \"KEYWORD_B\" ]( \"second_argument\" )\n\n" ]
[ 11, 4, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002818490_python.txt
Q: Cascading Dropdown List I am working on a web app and trying to code a form with two dropdown lists. The list in the second dropdown will be dependent on the selection from the first one. The task itself isn’t too complicated except that once the first selection is made, I need to make a database call to pull the data for the second dropdown. This is where I am having difficulty. Both lists are in fact populated from a database. I am working on this in a python script and have been trying to do this w/ an onChange javascript function. The web app is built in Zope and page templates may be an option along w/ the python scripts. A: you will have to use a combination of Ajax and javascript here. Onchange event of your select drop down call a javascript function. This javascript function will make a ajax request to a python script that will actually make a database hit and return you a response in a javascript variable. With this javascript variable you can edit you DOM and set the html of second select box. see if u can get some hint from this: http://www.satya-weblog.com/2007/04/dynamically-populate-select-list-by.html A: That's exactly what I did. Below is the javascript function I came up with. OnChange, I call getOptions and the pythonScript creates the second dropdown list. I am able to pass in a parameter to get the data I need for this dropdown. Thanks! function getOptions() { var code = 'code=' + $("dropdown1").getValue(); var myAjax = new Ajax.Updater('dropdown2', './pythonScript', { method: 'get', parameters: code }); }
Cascading Dropdown List
I am working on a web app and trying to code a form with two dropdown lists. The list in the second dropdown will be dependent on the selection from the first one. The task itself isn’t too complicated except that once the first selection is made, I need to make a database call to pull the data for the second dropdown. This is where I am having difficulty. Both lists are in fact populated from a database. I am working on this in a python script and have been trying to do this w/ an onChange javascript function. The web app is built in Zope and page templates may be an option along w/ the python scripts.
[ "you will have to use a combination of Ajax and javascript here. Onchange event of your select drop down call a javascript function. This javascript function will make a ajax request to a python script that will actually make a database hit and return you a response in a javascript variable. With this javascript variable you can edit you DOM and set the html of second select box.\nsee if u can get some hint from this:\nhttp://www.satya-weblog.com/2007/04/dynamically-populate-select-list-by.html\n", "That's exactly what I did. Below is the javascript function I came up with. OnChange, I call getOptions and the pythonScript creates the second dropdown list. I am able to pass in a parameter to get the data I need for this dropdown. Thanks!\n function getOptions() {\n var code = 'code=' + $(\"dropdown1\").getValue();\n var myAjax = new Ajax.Updater('dropdown2', './pythonScript', { method: 'get', parameters: code });\n }\n\n" ]
[ 1, 0 ]
[]
[]
[ "html", "javascript", "python", "rest", "zope" ]
stackoverflow_0002776415_html_javascript_python_rest_zope.txt
Q: Django urls conf So now I am still at the Django tutorial part 3: http://docs.djangoproject.com/en/1.1/intro/tutorial03/#intro-tutorial03 Trying to set up the urls.py with this piece of code provided by the tutorial from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^polls/$', 'mysite.polls.views.index'), (r'^polls/(?P<poll_id>\d+)/$', 'mysite.polls.views.detail'), (r'^polls/(?P<poll_id>\d+)/results/$', 'mysite.polls.views.results'), (r'^polls/(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'), (r'^admin/', include(admin.site.urls)), ) If I change my default urls.py (with nothing in it) with this code, the 127.0.0.1:8000/polls/ is showing up, but for some reason the 127.0.0.1:8000/admin is no longer there and gives me the following error: Exception Type: TemplateSyntaxError Exception Value: Caught an exception while rendering: Tried vote in module mysite.polls.views. Error was: 'module' object has no attribute 'vote' And this (Error line 30): Caught an exception while rendering: Tried vote in module mysite.polls.views. Error was: 'module' object has no attribute 'vote' 20 <!-- Header --> 21 <div id="header"> 22 <div id="branding"> 23 {% block branding %}{% endblock %} 24 </div> 25 {% if user.is_authenticated and user.is_staff %} 26 <div id="user-tools"> 27 {% trans 'Welcome,' %} 28 <strong>{% firstof user.first_name user.username %}</strong>. 29 {% block userlinks %} **30 {% url django-admindocs-docroot as docsroot %}** 31 {% if docsroot %} 32 <a href="{{ docsroot }}">{% trans 'Documentation' %}</a> / 33 {% endif %} 34 {% url admin:password_change as password_change_url %} 35 {% if password_change_url %} 36 <a href="{{ password_change_url }}"> 37 {% else %} 38 <a href="{{ root_path }}password_change/"> 39 {% endif %} 40 {% trans 'Change password' %}</a> / It seems to me that the error should be here: (r'^admin/', include(admin.site.urls)), But I cant find it. Thanks for the attention!! A: It's just that django does not seem to find the function vote inside your module views.
Django urls conf
So now I am still at the Django tutorial part 3: http://docs.djangoproject.com/en/1.1/intro/tutorial03/#intro-tutorial03 Trying to set up the urls.py with this piece of code provided by the tutorial from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^polls/$', 'mysite.polls.views.index'), (r'^polls/(?P<poll_id>\d+)/$', 'mysite.polls.views.detail'), (r'^polls/(?P<poll_id>\d+)/results/$', 'mysite.polls.views.results'), (r'^polls/(?P<poll_id>\d+)/vote/$', 'mysite.polls.views.vote'), (r'^admin/', include(admin.site.urls)), ) If I change my default urls.py (with nothing in it) with this code, the 127.0.0.1:8000/polls/ is showing up, but for some reason the 127.0.0.1:8000/admin is no longer there and gives me the following error: Exception Type: TemplateSyntaxError Exception Value: Caught an exception while rendering: Tried vote in module mysite.polls.views. Error was: 'module' object has no attribute 'vote' And this (Error line 30): Caught an exception while rendering: Tried vote in module mysite.polls.views. Error was: 'module' object has no attribute 'vote' 20 <!-- Header --> 21 <div id="header"> 22 <div id="branding"> 23 {% block branding %}{% endblock %} 24 </div> 25 {% if user.is_authenticated and user.is_staff %} 26 <div id="user-tools"> 27 {% trans 'Welcome,' %} 28 <strong>{% firstof user.first_name user.username %}</strong>. 29 {% block userlinks %} **30 {% url django-admindocs-docroot as docsroot %}** 31 {% if docsroot %} 32 <a href="{{ docsroot }}">{% trans 'Documentation' %}</a> / 33 {% endif %} 34 {% url admin:password_change as password_change_url %} 35 {% if password_change_url %} 36 <a href="{{ password_change_url }}"> 37 {% else %} 38 <a href="{{ root_path }}password_change/"> 39 {% endif %} 40 {% trans 'Change password' %}</a> / It seems to me that the error should be here: (r'^admin/', include(admin.site.urls)), But I cant find it. Thanks for the attention!!
[ "It's just that django does not seem to find the function vote inside your module views.\n" ]
[ 2 ]
[]
[]
[ "django", "django_urls", "python", "views" ]
stackoverflow_0002818959_django_django_urls_python_views.txt
Q: How to remove debugging from outputting with nosetests I am using nosetests to test several scripts. But when I run nosetests it prints out the logging. I know it stores logging info into sys.stderr. Does anyone know how to stop this from outputting to the screen? I just want the test results to output like when you run unittest normally. Thanks for any help A: Found the answer, nosetests test* --nologcapture --nocapture Run this in the command line. Thanks
How to remove debugging from outputting with nosetests
I am using nosetests to test several scripts. But when I run nosetests it prints out the logging. I know it stores logging info into sys.stderr. Does anyone know how to stop this from outputting to the screen? I just want the test results to output like when you run unittest normally. Thanks for any help
[ "Found the answer,\nnosetests test* --nologcapture --nocapture\n\nRun this in the command line.\nThanks\n" ]
[ 6 ]
[]
[]
[ "logging", "nosetests", "python", "stderr" ]
stackoverflow_0002818766_logging_nosetests_python_stderr.txt
Q: Json unicode decoding in python's simplejson I can't decode json strings like this: "\u0e4f\u0361\u032f\u0e4f" >>> import simplejson >>> simplejson.loads('"\u0e4f\u0361\u032f\u0e4f"', encoding='utf8') u'\u0e4f\u0361\u032f\u0e4f' However php json_decode works fine: json_decode('"\u0e4f\u0361\u032f\u0e4f"'); What am I doing wrong? A: Nothing. The Python REPL prints the repr() of the string, not the string itself. >>> print u'\u0e4f\u0361\u032f\u0e4f' ๏̯͡๏
Json unicode decoding in python's simplejson
I can't decode json strings like this: "\u0e4f\u0361\u032f\u0e4f" >>> import simplejson >>> simplejson.loads('"\u0e4f\u0361\u032f\u0e4f"', encoding='utf8') u'\u0e4f\u0361\u032f\u0e4f' However php json_decode works fine: json_decode('"\u0e4f\u0361\u032f\u0e4f"'); What am I doing wrong?
[ "Nothing. The Python REPL prints the repr() of the string, not the string itself.\n>>> print u'\\u0e4f\\u0361\\u032f\\u0e4f'\n๏̯͡๏\n\n" ]
[ 2 ]
[]
[]
[ "json", "python", "simplejson" ]
stackoverflow_0002819092_json_python_simplejson.txt
Q: Quickbooks integration: IPP/IDS: can these by used for actual data exchange? Poking around options for integrating an online app with Quickbooks, I've made a lot of headway with QBWC, but it's fairly ugly. From an end user perspective the usability of QBWC is pretty low. Intuit is now pushing Intuit Partner Platform (IPP) and Intuit Data Services (IDS). I can't quite figure out what these are about: Is IPP limited to using Flex, or can it work with existing web apps? Are there APIs for actual data exchange? Is it possible to interact with desktop Quickbooks using IPP or IDS? If there is sample code, particularly in Python, some pointers would be great. A: Is IPP limited to using Flex, or can it work with existing web apps? It is not limited to Flex. You can use IPP/IDS from any web application, as long as you federate your application (allow logins using SAML via workplace.intuit.com). There are two "types" of IPP applications: Native apps Native applications are applications written in Flex which utilize the Flex bindings for IPP. These applications run on Intuit's servers. Federated apps Federated applications are applications written in your language of choice, running on your servers, which utilize the language bindings of your choice to talk to IPP. All of the communication with IPP is via HTTP XML requests, so pretty much any language out there can talk to IPP without any problems. You'll need to implement a SAML gateway which allows your users to log in via workplace.intuit.com. Are there APIs for actual data exchange? Yes. IPP is actually made of up two parts that both provide different sorts of data exchange. IPP core stuff This involves user management, roles/permissions, access to QuickBase data stores, etc. IDS (Intuit Data Services) This involves actually exchanging data with QuickBooks. Right now, a subset of QuickBooks data is supported, but Intuit is rapidly adding support for accessing more data within QuickBooks. You can add/modify/delete/query QuickBooks data and the data is automatically synced back to the end-users QuickBooks file. Is it possible to interact with desktop Quickbooks using IPP or IDS? That depends on what you mean by "interact". Yes, you can exchange data with their QuickBooks data file. No, you can't do things like automatically open up a particular window within QuickBooks or something like that. If there is sample code, particularly in Python, some pointers would be great. There are many open-source IPP DevKits on code.intuit.com that should be helpful. In particular, you'll probably want to check out this one: Python DevKit You'll also need to implement a SAML gateway for authentication, and there is sample code for that as well: SAML Gateways I'm the project admin for the QuickBooks PHP DevKit: QuickBooks PHP DevKit There's a ton of additional information on the code.intuit.com website and tons of additional technical documentation on IPP/IDS with Federated applications on developer.intuit.com.
Quickbooks integration: IPP/IDS: can these by used for actual data exchange?
Poking around options for integrating an online app with Quickbooks, I've made a lot of headway with QBWC, but it's fairly ugly. From an end user perspective the usability of QBWC is pretty low. Intuit is now pushing Intuit Partner Platform (IPP) and Intuit Data Services (IDS). I can't quite figure out what these are about: Is IPP limited to using Flex, or can it work with existing web apps? Are there APIs for actual data exchange? Is it possible to interact with desktop Quickbooks using IPP or IDS? If there is sample code, particularly in Python, some pointers would be great.
[ "\nIs IPP limited to using Flex, or can it work with existing web apps?\n\nIt is not limited to Flex. You can use IPP/IDS from any web application, as long as you federate your application (allow logins using SAML via workplace.intuit.com). \nThere are two \"types\" of IPP applications:\n\nNative apps Native applications are applications written in Flex which utilize the Flex bindings for IPP. These applications run on Intuit's servers. \nFederated apps Federated applications are applications written in your language of choice, running on your servers, which utilize the language bindings of your choice to talk to IPP. All of the communication with IPP is via HTTP XML requests, so pretty much any language out there can talk to IPP without any problems. You'll need to implement a SAML gateway which allows your users to log in via workplace.intuit.com. \n\n\nAre there APIs for actual data exchange?\n\nYes. IPP is actually made of up two parts that both provide different sorts of data exchange. \n\nIPP core stuff This involves user management, roles/permissions, access to QuickBase data stores, etc. \nIDS (Intuit Data Services) This involves actually exchanging data with QuickBooks. Right now, a subset of QuickBooks data is supported, but Intuit is rapidly adding support for accessing more data within QuickBooks. You can add/modify/delete/query QuickBooks data and the data is automatically synced back to the end-users QuickBooks file.\n\n\nIs it possible to interact with desktop Quickbooks using IPP or IDS?\n\nThat depends on what you mean by \"interact\". Yes, you can exchange data with their QuickBooks data file. No, you can't do things like automatically open up a particular window within QuickBooks or something like that. \n\nIf there is sample code, particularly in Python, some pointers would be great.\n\nThere are many open-source IPP DevKits on code.intuit.com that should be helpful. In particular, you'll probably want to check out this one:\nPython DevKit\nYou'll also need to implement a SAML gateway for authentication, and there is sample code for that as well:\nSAML Gateways\nI'm the project admin for the QuickBooks PHP DevKit: QuickBooks PHP DevKit\nThere's a ton of additional information on the code.intuit.com website and tons of additional technical documentation on IPP/IDS with Federated applications on developer.intuit.com.\n" ]
[ 7 ]
[]
[]
[ "python", "qbwc", "quickbooks" ]
stackoverflow_0002786122_python_qbwc_quickbooks.txt
Q: django threadedcomments I would like to setup a comment systems on my site, using django threadedcomments, and I follow all the steps in the Tutorial, however, I get the following error: No module named newforms.util I am not sure what causing this issue, here is my configuration: #settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'myproject.myapp', 'threadedcomments', ) #urls.py from django.conf import settings from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^threadedcomments/', include('threadedcomments.urls')), ) Please let me know if there is another better choice for commenting, as long as the comment system is flexible and able to do lot of customization, as well as threadedcomment, of coz, integrating with Rating, I am happy to use the other one. Thanks guys. A: You are most probably using a very old version of one of your apps. The newforms module has disappeared from django a long time ago.
django threadedcomments
I would like to setup a comment systems on my site, using django threadedcomments, and I follow all the steps in the Tutorial, however, I get the following error: No module named newforms.util I am not sure what causing this issue, here is my configuration: #settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'myproject.myapp', 'threadedcomments', ) #urls.py from django.conf import settings from django.conf.urls.defaults import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), (r'^threadedcomments/', include('threadedcomments.urls')), ) Please let me know if there is another better choice for commenting, as long as the comment system is flexible and able to do lot of customization, as well as threadedcomment, of coz, integrating with Rating, I am happy to use the other one. Thanks guys.
[ "You are most probably using a very old version of one of your apps. The newforms module has disappeared from django a long time ago.\n" ]
[ 4 ]
[]
[]
[ "blogs", "comments", "django", "python" ]
stackoverflow_0002819130_blogs_comments_django_python.txt
Q: How do I open the default mail program with a subject in Python in a cross-platform way? I am trying to add the ability to send mails using the default mail client from my python app. It can be done with the webbrowser module by opening a 'mailto:' URI. But, is there a better and direct way to do this like java's Desktop.mail(URI). Thanks in advance. A: As far as my research goes, there is no proper solution. We currently use this solution, which is the recipe by Antonio Valentino with a few modifications. You're interested in the mailto function in that file.
How do I open the default mail program with a subject in Python in a cross-platform way?
I am trying to add the ability to send mails using the default mail client from my python app. It can be done with the webbrowser module by opening a 'mailto:' URI. But, is there a better and direct way to do this like java's Desktop.mail(URI). Thanks in advance.
[ "As far as my research goes, there is no proper solution. We currently use this solution, which is the recipe by Antonio Valentino with a few modifications.\nYou're interested in the mailto function in that file.\n" ]
[ 0 ]
[]
[]
[ "email", "python" ]
stackoverflow_0002818720_email_python.txt
Q: small python code refactor I am having this piece of code, which in my opinion is fairly ugly and I am wondering how it can be done better: if dic.get(key, None) is None: dic[key] = None Points for elegance ;-) A: d.setdefault(key) # sets d[key] to None if key is not in d A: if key not in dic: dic[key] = None This might not be as short as Olivier's code, but at least it's explicit and fast. Please, don't use dict as a variable name, it shadows built-in. A: import collections mydict = collections.defaultdict(lambda: None) Now, any access to mydict[akey] will (if akey was not present as a key in mydict) set mydict[akey] to None as a side effect. Note that defaultdict's initializer requires a no-arguments callable, whence the lambda.
small python code refactor
I am having this piece of code, which in my opinion is fairly ugly and I am wondering how it can be done better: if dic.get(key, None) is None: dic[key] = None Points for elegance ;-)
[ "d.setdefault(key) # sets d[key] to None if key is not in d\n\n", "if key not in dic:\n dic[key] = None\n\nThis might not be as short as Olivier's code, but at least it's explicit and fast.\nPlease, don't use dict as a variable name, it shadows built-in.\n", "import collections\n\nmydict = collections.defaultdict(lambda: None)\n\nNow, any access to mydict[akey] will (if akey was not present as a key in mydict) set mydict[akey] to None as a side effect.\nNote that defaultdict's initializer requires a no-arguments callable, whence the lambda.\n" ]
[ 10, 7, 3 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0002819627_dictionary_python.txt
Q: matplotlib - zebra-stripe a figure's background color? I'm building a simple line chart with matplotlib, and I'd like to zebra-stripe the background of the chart, so that each alternating row is colored differently. Is there a way to do this? My chart already has gridding, and has major ticks only. Edit: The code from my comment below, but more legible: yTicks = ax.get_yticks()[:-1] xTicks = ax.get_xticks() ax.barh(yTicks, [max(xTicks)-min(xTicks)] * len(yTicks), height=(yTicks[1]-yTicks[0]), left=min(xTicks), color=['w','#F0FFFF']) A: Here's a quick hack that uses a barchart (axes.barh) to simulate striping. import matplotlib.pyplot as plt # initial plot fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,3,4,5]) yTickPos,_ = plt.yticks() yTickPos = yTickPos[:-1] #slice off the last as it is the top of the plot # create bars at yTickPos that are the length of our greatest xtick and have a height equal to our tick spacing ax.barh(yTickPos, [max(plt.xticks()[0])] * len(yTickPos), height=(yTickPos[1]-yTickPos[0]), color=['g','w']) plt.show() Produces:
matplotlib - zebra-stripe a figure's background color?
I'm building a simple line chart with matplotlib, and I'd like to zebra-stripe the background of the chart, so that each alternating row is colored differently. Is there a way to do this? My chart already has gridding, and has major ticks only. Edit: The code from my comment below, but more legible: yTicks = ax.get_yticks()[:-1] xTicks = ax.get_xticks() ax.barh(yTicks, [max(xTicks)-min(xTicks)] * len(yTicks), height=(yTicks[1]-yTicks[0]), left=min(xTicks), color=['w','#F0FFFF'])
[ "Here's a quick hack that uses a barchart (axes.barh) to simulate striping.\nimport matplotlib.pyplot as plt\n\n# initial plot\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot([1,2,3,4,5])\n\nyTickPos,_ = plt.yticks()\nyTickPos = yTickPos[:-1] #slice off the last as it is the top of the plot\n# create bars at yTickPos that are the length of our greatest xtick and have a height equal to our tick spacing\nax.barh(yTickPos, [max(plt.xticks()[0])] * len(yTickPos), height=(yTickPos[1]-yTickPos[0]), color=['g','w'])\n\nplt.show()\n\nProduces:\n\n" ]
[ 5 ]
[]
[]
[ "charts", "matplotlib", "python" ]
stackoverflow_0002815455_charts_matplotlib_python.txt
Q: How to use a callable as the setup with timeit.Timer? I want to time some code that depends on some setup. The setup code looks a little like this: >>> b = range(1, 1001) And the code I want to time looks vaguely like this: >>> sorted(b) Except my code uses a different function than sorted. But that ain't important right now. Anyhow, I know how to time this code as long as I pass in strings to timeit: >>> import timeit >>> t = timeit.Timer("sorted(b)", "b = range(1, 1001)") >>> min(t.repeat(3, 100)) How do I use a setup callable and have it put stuff into the namespace that the stmt callable can access? In other words, how do I do the same thing as the code above, but with callables, and not strings containing callables? Incidentally, the bigger goal here is to reuse code from my unit tests to measure performance: import unittest class TestSorting(unittest.TestCase): def setUp(self): self.b = range(1, 1001) def test_sorted(self): sorted(self.b) I expect to do a little work. The timeit setup will need to make an instance of TestSorting and somehow the stmt code will have to use that particular instance. Once I understand how to have the timeit setup put stuff into the same namespace as the timeit stmt, I'll look into how to translate unittest.TestCase instances into something that can feed right into timeit.Timer. Matt A: In 2.6, you can "just do it", per the docs: Changed in version 2.6: The stmt and setup parameters can now also take objects that are callable without arguments. This will embed calls to them in a timer function that will then be executed by timeit(). Note that the timing overhead is a little larger in this case because of the extra function calls. Are you stuck using an old version of Python? In that case, I would suggest taking Python 2.6's timer.py sources and "backporting" them to the version you're stuck with -- should not be difficult if that version is 2.5 (gets harder the farther you need to travel back in time, of course). I would generally not recommend this for "production" code, but it's quite fine for code that supports testing, debugging, performance measurements, and the like. A: I've asked a variant of this question here and also got an answer that didn't solve my problem. I believe we are both failing to articulate the problem in terms Pythonic. I don't know if this is a hack, workaround, or how it is supposed to be done, but it does work: >>> import timeit >>> b = range(1, 1001) >>> t = timeit.Timer('sorted(b)', setup='from __main__ import b') >>> t.repeat(3, 100) [0.0024309158325195312, 0.0024671554565429688, 0.0024020671844482422] # was it really running 'sorted(b)'? let's compare' >>> t = timeit.Timer('pass', setup='from __main__ import b') >>> t.repeat(3, 100) [3.0994415283203125e-06, 2.1457672119140625e-06, 1.9073486328125e-06] # teeny times for 'pass', 'sorted(b)' took more time I have read timeit.py, it works by constructing a statement and then calls eval() on it using new namespaces which have (seemingly) no connection to your main namespace. Note that since sorted is a built-in, the eval'ed expression inside timeit.repeat() has access to the name; if it was your def you'd have to from __main__ import b, myfunc. I hope there is more proper way than this to achieve the end.
How to use a callable as the setup with timeit.Timer?
I want to time some code that depends on some setup. The setup code looks a little like this: >>> b = range(1, 1001) And the code I want to time looks vaguely like this: >>> sorted(b) Except my code uses a different function than sorted. But that ain't important right now. Anyhow, I know how to time this code as long as I pass in strings to timeit: >>> import timeit >>> t = timeit.Timer("sorted(b)", "b = range(1, 1001)") >>> min(t.repeat(3, 100)) How do I use a setup callable and have it put stuff into the namespace that the stmt callable can access? In other words, how do I do the same thing as the code above, but with callables, and not strings containing callables? Incidentally, the bigger goal here is to reuse code from my unit tests to measure performance: import unittest class TestSorting(unittest.TestCase): def setUp(self): self.b = range(1, 1001) def test_sorted(self): sorted(self.b) I expect to do a little work. The timeit setup will need to make an instance of TestSorting and somehow the stmt code will have to use that particular instance. Once I understand how to have the timeit setup put stuff into the same namespace as the timeit stmt, I'll look into how to translate unittest.TestCase instances into something that can feed right into timeit.Timer. Matt
[ "In 2.6, you can \"just do it\", per the docs:\n\nChanged in version 2.6: The stmt and\n setup parameters can now also take\n objects that are callable without\n arguments. This will embed calls to\n them in a timer function that will\n then be executed by timeit(). Note\n that the timing overhead is a little\n larger in this case because of the\n extra function calls.\n\nAre you stuck using an old version of Python? In that case, I would suggest taking Python 2.6's timer.py sources and \"backporting\" them to the version you're stuck with -- should not be difficult if that version is 2.5 (gets harder the farther you need to travel back in time, of course). I would generally not recommend this for \"production\" code, but it's quite fine for code that supports testing, debugging, performance measurements, and the like.\n", "I've asked a variant of this question here and also got an answer that didn't solve my problem. I believe we are both failing to articulate the problem in terms Pythonic.\nI don't know if this is a hack, workaround, or how it is supposed to be done, but it does work:\n>>> import timeit\n>>> b = range(1, 1001)\n>>> t = timeit.Timer('sorted(b)', setup='from __main__ import b')\n>>> t.repeat(3, 100)\n[0.0024309158325195312, 0.0024671554565429688, 0.0024020671844482422]\n# was it really running 'sorted(b)'? let's compare'\n>>> t = timeit.Timer('pass', setup='from __main__ import b')\n>>> t.repeat(3, 100) \n[3.0994415283203125e-06, 2.1457672119140625e-06, 1.9073486328125e-06] \n# teeny times for 'pass', 'sorted(b)' took more time\n\nI have read timeit.py, it works by constructing a statement and then calls eval() on it using new namespaces which have (seemingly) no connection to your main namespace. Note that since sorted is a built-in, the eval'ed expression inside timeit.repeat() has access to the name; if it was your def you'd have to from __main__ import b, myfunc.\nI hope there is more proper way than this to achieve the end.\n" ]
[ 1, 1 ]
[]
[]
[ "python", "timeit" ]
stackoverflow_0002819625_python_timeit.txt
Q: Handling KeyboardInterrupt when working with PyGame I have written a small Python application where I use PyGame for displaying some simple graphics. I have a somewhat simple PyGame loop going in the base of my application, like so: stopEvent = Event() # Just imagine that this eventually sets the stopEvent # as soon as the program is finished with its task. disp = SortDisplay(algorithm, stopEvent) def update(): """ Update loop; updates the screen every few seconds. """ while True: stopEvent.wait(options.delay) disp.update() if stopEvent.isSet(): break disp.step() t = Thread(target=update) t.start() while not stopEvent.isSet(): for event in pygame.event.get(): if event.type == pygame.QUIT: stopEvent.set() It works all fine and dandy for the normal program termination; if the PyGame window gets closed, the application closes; if the application finishes its task, the application closes. The trouble I'm having is, if I Ctrl-C in the Python console, the application throws a KeyboardInterrupt, but keeps on running. The question would therefore be: What have I done wrong in my update loop, and how do I rectify it so a KeyboardInterrupt causes the application to terminate? A: What about changing your final loop to...: while not stopEvent.isSet(): try: for event in pygame.event.get(): if event.type == pygame.QUIT: stopEvent.set() except KeyboardInterrupt: stopEvent.set() i.e., make sure you catch keyboard interrupts and treat them just the same as a quit event. A: Amending Alex's answer, note that you probably want to do this on all exceptions, to ensure that you shut down the thread if the main thread fails for any reason, not just KeyboardInterrupt. You also need to move the exception handler out, to avoid race conditions. For example, there might be a KeyboardInterrupt while calling stopEvent.isSet(). try: t = Thread(target=update) t.start() while not stopEvent.isSet(): for event in pygame.event.get(): if event.type == pygame.QUIT: stopEvent.set() finally: stopEvent.set() Doing this in finally makes it clearer: you can tell immediately that the event will always be set regardless of how you exit this code block. (I'm assuming setting the event twice is harmless.) If you don't want to show a stack trace on KeyboardError you should catch it and swallow it, but be sure to do that only in your outermost code to be sure the exception is propagated out fully.
Handling KeyboardInterrupt when working with PyGame
I have written a small Python application where I use PyGame for displaying some simple graphics. I have a somewhat simple PyGame loop going in the base of my application, like so: stopEvent = Event() # Just imagine that this eventually sets the stopEvent # as soon as the program is finished with its task. disp = SortDisplay(algorithm, stopEvent) def update(): """ Update loop; updates the screen every few seconds. """ while True: stopEvent.wait(options.delay) disp.update() if stopEvent.isSet(): break disp.step() t = Thread(target=update) t.start() while not stopEvent.isSet(): for event in pygame.event.get(): if event.type == pygame.QUIT: stopEvent.set() It works all fine and dandy for the normal program termination; if the PyGame window gets closed, the application closes; if the application finishes its task, the application closes. The trouble I'm having is, if I Ctrl-C in the Python console, the application throws a KeyboardInterrupt, but keeps on running. The question would therefore be: What have I done wrong in my update loop, and how do I rectify it so a KeyboardInterrupt causes the application to terminate?
[ "What about changing your final loop to...:\nwhile not stopEvent.isSet():\n try:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n stopEvent.set()\n except KeyboardInterrupt:\n stopEvent.set()\n\ni.e., make sure you catch keyboard interrupts and treat them just the same as a quit event.\n", "Amending Alex's answer, note that you probably want to do this on all exceptions, to ensure that you shut down the thread if the main thread fails for any reason, not just KeyboardInterrupt.\nYou also need to move the exception handler out, to avoid race conditions. For example, there might be a KeyboardInterrupt while calling stopEvent.isSet().\ntry:\n t = Thread(target=update)\n t.start()\n\n while not stopEvent.isSet():\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n stopEvent.set()\nfinally:\n stopEvent.set()\n\nDoing this in finally makes it clearer: you can tell immediately that the event will always be set regardless of how you exit this code block. (I'm assuming setting the event twice is harmless.)\nIf you don't want to show a stack trace on KeyboardError you should catch it and swallow it, but be sure to do that only in your outermost code to be sure the exception is propagated out fully.\n" ]
[ 3, 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0002819931_pygame_python.txt
Q: Appengine Python Bulk Export error This seems to run for ~42,200 records then fails: import datetime import time from google.appengine.ext import db from google.appengine.tools import bulkloader from google.appengine.api import datastore_types class SearchRec(db.Model): WebSite = db.StringProperty() WebPage = db.StringProperty() DateStamp = db.DateTimeProperty(auto_now_add=True) IP = db.StringProperty() UserAgent = db.StringProperty() class TrackerExporter(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'SearchRec', [('WebSite', str, None), ('WebPage', str, None), ('DateStamp', lambda x: str(datetime.datetime.strptime(x, '%d/%m/%Y').date()), None), ('IP', str, None) ]) exporters = [TrackerExporter] if __name__ == '__main__': bulkload.main(TrackerExporter) Error: File "tracker-export.py", line 89, in <lambda> ('DateStamp', lambda x: str(datetime.datetime.strptime(x, '%d/%m/%Y').date() ), None), TypeError: strptime() argument 1 must be string, not datetime.datetime A: I'm not sure why exactly that would be happening. I'm not too familiar with the Bulk Exporting facilities of App Engine, but it sounds like the DateStamp field is being given to the bulk exporter as a string (which is what your converter expects) for the first 42200 records and then, for some reason, it is given as a real datetime.datetime object. Anyway, here's a treatment for this particular symptom: lambda x: str((x if isinstance(x, datetime.datetime) else datetime.datetime.strptime(x, '%d/%m/%Y')).date()) That should do the right thing if given either a string or a datetime.datetime object. This might be a case where you should give it a dedicated function instead of torturing a lambda like that.
Appengine Python Bulk Export error
This seems to run for ~42,200 records then fails: import datetime import time from google.appengine.ext import db from google.appengine.tools import bulkloader from google.appengine.api import datastore_types class SearchRec(db.Model): WebSite = db.StringProperty() WebPage = db.StringProperty() DateStamp = db.DateTimeProperty(auto_now_add=True) IP = db.StringProperty() UserAgent = db.StringProperty() class TrackerExporter(bulkloader.Exporter): def __init__(self): bulkloader.Exporter.__init__(self, 'SearchRec', [('WebSite', str, None), ('WebPage', str, None), ('DateStamp', lambda x: str(datetime.datetime.strptime(x, '%d/%m/%Y').date()), None), ('IP', str, None) ]) exporters = [TrackerExporter] if __name__ == '__main__': bulkload.main(TrackerExporter) Error: File "tracker-export.py", line 89, in <lambda> ('DateStamp', lambda x: str(datetime.datetime.strptime(x, '%d/%m/%Y').date() ), None), TypeError: strptime() argument 1 must be string, not datetime.datetime
[ "I'm not sure why exactly that would be happening. I'm not too familiar with the Bulk Exporting facilities of App Engine, but it sounds like the DateStamp field is being given to the bulk exporter as a string (which is what your converter expects) for the first 42200 records and then, for some reason, it is given as a real datetime.datetime object.\nAnyway, here's a treatment for this particular symptom:\nlambda x: str((x if isinstance(x, datetime.datetime) else datetime.datetime.strptime(x, '%d/%m/%Y')).date())\n\nThat should do the right thing if given either a string or a datetime.datetime object. This might be a case where you should give it a dedicated function instead of torturing a lambda like that.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002819584_google_app_engine_python.txt
Q: appcfg.py upload_data is failing with expected even though I've got it I am having trouble getting the bulk uploader to work. I have been following the tutorial here:http://code.google.com/appengine/docs/ python/tools/uploadingdata.html. When I enter the following command (from Windows, using PowerShell) appcfg.py upload_data --config_file=src/friend_loader.py --filename=frienddata.csv --kind=Friend ./src/ I get the following error: Usage: appcfg.py [options] upload_data appcfg.py: error: Expected argument. This seems to happen no matter how I change the order of the arguments, where the files are or any other combination that I have tried. Any thoughts appreciated. A: Do you get any more information when you add "--noisy" ? Are you logged in before you run above line ? A: the last parameter ./src/ could you explain what are you using it for? the tools is expecting a parameter of: the app_Id of your app running on the google app engine or the root path of your applicacion generally is something like. /appcfg.py --config_file=person_loader.py --kind=person --filename=persons.csv --url=http://employee.appspot.com/remote_api download_data 2010employee010 where 2010employee010 is the app_ID or you can make it at this other way: /appcfg.py --config_file=person_loader.py --kind=person --filename=persons.csv --url=http://employee.appspot.com/remote_api download_data employee/ where employee/ is the root path where the app is running or it was started.
appcfg.py upload_data is failing with expected even though I've got it
I am having trouble getting the bulk uploader to work. I have been following the tutorial here:http://code.google.com/appengine/docs/ python/tools/uploadingdata.html. When I enter the following command (from Windows, using PowerShell) appcfg.py upload_data --config_file=src/friend_loader.py --filename=frienddata.csv --kind=Friend ./src/ I get the following error: Usage: appcfg.py [options] upload_data appcfg.py: error: Expected argument. This seems to happen no matter how I change the order of the arguments, where the files are or any other combination that I have tried. Any thoughts appreciated.
[ "Do you get any more information when you add \"--noisy\" ? Are you logged in before you run above line ?\n", "the last parameter ./src/ could you explain what are you using it for?\nthe tools is expecting a parameter of: the app_Id of your app running on the google app engine or the root path of your applicacion generally is something like.\n/appcfg.py --config_file=person_loader.py --kind=person --filename=persons.csv --url=http://employee.appspot.com/remote_api download_data 2010employee010\n\nwhere 2010employee010 is the app_ID or you can make it at this other way:\n/appcfg.py --config_file=person_loader.py --kind=person --filename=persons.csv --url=http://employee.appspot.com/remote_api download_data employee/\n\nwhere employee/ is the root path where the app is running or it was started.\n" ]
[ 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001753867_google_app_engine_python.txt
Q: How to achieve interaction between GUI class with logic class Im new to GUI programming, and haven't done much OOP. Im working on a basic calculator app to help me learn GUI design and to brush up on OOP. I understand that anything GUI related should be kept seperate from the logic, but Im unsure how to implement interaction between logic an GUI classes when needed i.e. basically passing variables back and forth... Im using TKinter and when I pass a tkinter variable to my logic it only seems to hold the string PY_VAR0. def on_equal_btn_click(self): self.entryVariable.set(self.entryVariable.get() + "=") calculator = Calc(self.entryVariable) self.entryVariable.set(calculator.calculate()) Im sure that im probably doing something fundamentally wrong and probabaly really stupid, I spent a considerable amount of time experimenting (and searching for answers online) but Im getting no where. Any help would be appreciated. Thanks, V The Full Program (well just enough to show the structure..) import Tkinter class Gui(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() self.create_widgets() """ grid config """ #self.grid_columnconfigure(0,weight=1,pad=0) self.resizable(False, False) def create_widgets(self): """row 0 of grid""" """Create Text Entry Box""" self.entryVariable = Tkinter.StringVar() self.entry = Tkinter.Entry(self,width=30,textvariable=self.entryVariable) self.entry.grid(column=0,row=0, columnspan = 3 ) self.entry.bind("<Return>", self.on_press_enter) """create equal button""" equal_btn = Tkinter.Button(self,text="=",width=4,command=self.on_equal_btn_click) equal_btn.grid(column=3, row=0) """row 1 of grid""" """create number 1 button""" number1_btn = Tkinter.Button(self,text="1",width=8,command=self.on_number1_btn_click) number1_btn.grid(column=0, row=1) def on_equal_btn_click(self): self.entryVariable.set(self.entryVariable.get() + "=") calculator = Calc(self.entryVariable.get()) self.entryVariable.set(calculator.calculate()) class Calc(): def __init__(self, equation): self.equation = equation def calculate(self): #TODO: parse string and calculate... return self.equation # define undefined functions for sufficiently liberal meanings of "define" Gui.on_press_enter = Gui.on_equal_btn_click Gui.on_number1_button_click = Gui.on_equal_btn_click if __name__ == "__main__": app = Gui(None) app.title('Calculator') app.mainloop() A: Corrected: My first answer was totally mistaken, ignore it. The problem was that you were accidentally overwriting your entry variable text with an a string representation of the entryVariable object. Note the addition of a get() in the call to Calc(): def on_equal_btn_click(self): print self.entryVariable.get() self.entryVariable.set(self.entryVariable.get() + "=") print self.entryVariable.get() calculator = Calc(self.entryVariable.get()) self.entryVariable.set(calculator.calculate()) welcome to weakly typed languages, that sort of bug can drive you up a wall. I find liberal use of print and repr() (or print('foo %r' % object)) to be invaluable in such times.
How to achieve interaction between GUI class with logic class
Im new to GUI programming, and haven't done much OOP. Im working on a basic calculator app to help me learn GUI design and to brush up on OOP. I understand that anything GUI related should be kept seperate from the logic, but Im unsure how to implement interaction between logic an GUI classes when needed i.e. basically passing variables back and forth... Im using TKinter and when I pass a tkinter variable to my logic it only seems to hold the string PY_VAR0. def on_equal_btn_click(self): self.entryVariable.set(self.entryVariable.get() + "=") calculator = Calc(self.entryVariable) self.entryVariable.set(calculator.calculate()) Im sure that im probably doing something fundamentally wrong and probabaly really stupid, I spent a considerable amount of time experimenting (and searching for answers online) but Im getting no where. Any help would be appreciated. Thanks, V The Full Program (well just enough to show the structure..) import Tkinter class Gui(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() self.create_widgets() """ grid config """ #self.grid_columnconfigure(0,weight=1,pad=0) self.resizable(False, False) def create_widgets(self): """row 0 of grid""" """Create Text Entry Box""" self.entryVariable = Tkinter.StringVar() self.entry = Tkinter.Entry(self,width=30,textvariable=self.entryVariable) self.entry.grid(column=0,row=0, columnspan = 3 ) self.entry.bind("<Return>", self.on_press_enter) """create equal button""" equal_btn = Tkinter.Button(self,text="=",width=4,command=self.on_equal_btn_click) equal_btn.grid(column=3, row=0) """row 1 of grid""" """create number 1 button""" number1_btn = Tkinter.Button(self,text="1",width=8,command=self.on_number1_btn_click) number1_btn.grid(column=0, row=1) def on_equal_btn_click(self): self.entryVariable.set(self.entryVariable.get() + "=") calculator = Calc(self.entryVariable.get()) self.entryVariable.set(calculator.calculate()) class Calc(): def __init__(self, equation): self.equation = equation def calculate(self): #TODO: parse string and calculate... return self.equation # define undefined functions for sufficiently liberal meanings of "define" Gui.on_press_enter = Gui.on_equal_btn_click Gui.on_number1_button_click = Gui.on_equal_btn_click if __name__ == "__main__": app = Gui(None) app.title('Calculator') app.mainloop()
[ "Corrected:\nMy first answer was totally mistaken, ignore it. The problem was that you were accidentally overwriting your entry variable text with an a string representation of the entryVariable object. Note the addition of a get() in the call to Calc():\ndef on_equal_btn_click(self):\n print self.entryVariable.get()\n self.entryVariable.set(self.entryVariable.get() + \"=\")\n print self.entryVariable.get()\n calculator = Calc(self.entryVariable.get())\n self.entryVariable.set(calculator.calculate())\n\nwelcome to weakly typed languages, that sort of bug can drive you up a wall. I find liberal use of print and repr() (or print('foo %r' % object)) to be invaluable in such times.\n" ]
[ 2 ]
[]
[]
[ "oop", "python", "tkinter", "user_interface" ]
stackoverflow_0002820417_oop_python_tkinter_user_interface.txt
Q: Is there a better way of making numpy.argmin() ignore NaN values I want to get the index of the min value of a numpy array that contains NaNs and I want them ignored >>> a = array([ nan, 2.5, 3., nan, 4., 5.]) >>> a array([ NaN, 2.5, 3. , NaN, 4. , 5. ]) if I run argmin, it returns the index of the first NaN >>> a.argmin() 0 I substitute NaNs with Infs and then run argmin >>> a[isnan(a)] = Inf >>> a array([ Inf, 2.5, 3. , Inf, 4. , 5. ]) >>> a.argmin() 1 My dilemma is the following: I'd rather not change NaNs to Infs and then back after I'm done with argmin (since NaNs have a meaning later on in the code). Is there a better way to do this? There is also a question of what should the result be if all of the original values of a are NaN? In my implementation the answer is 0 A: Sure! Use nanargmin: import numpy as np a = np.array([ np.nan, 2.5, 3., np.nan, 4., 5.]) print(np.nanargmin(a)) # 1 There is also nansum, nanmax, nanargmax, and nanmin, In scipy.stats, there is nanmean and nanmedian. For more ways to ignore nans, check out masked arrays.
Is there a better way of making numpy.argmin() ignore NaN values
I want to get the index of the min value of a numpy array that contains NaNs and I want them ignored >>> a = array([ nan, 2.5, 3., nan, 4., 5.]) >>> a array([ NaN, 2.5, 3. , NaN, 4. , 5. ]) if I run argmin, it returns the index of the first NaN >>> a.argmin() 0 I substitute NaNs with Infs and then run argmin >>> a[isnan(a)] = Inf >>> a array([ Inf, 2.5, 3. , Inf, 4. , 5. ]) >>> a.argmin() 1 My dilemma is the following: I'd rather not change NaNs to Infs and then back after I'm done with argmin (since NaNs have a meaning later on in the code). Is there a better way to do this? There is also a question of what should the result be if all of the original values of a are NaN? In my implementation the answer is 0
[ "Sure! Use nanargmin:\nimport numpy as np\na = np.array([ np.nan, 2.5, 3., np.nan, 4., 5.])\nprint(np.nanargmin(a))\n# 1\n\nThere is also nansum, nanmax, nanargmax, and nanmin,\nIn scipy.stats, there is nanmean and nanmedian.\nFor more ways to ignore nans, check out masked arrays.\n" ]
[ 54 ]
[]
[]
[ "arrays", "nan", "numpy", "python" ]
stackoverflow_0002821072_arrays_nan_numpy_python.txt
Q: How we get a session key from an access_token I got an access_token using facebook Graph API. https://graph.facebook.com/me?access_token=... I want session key. is there any method to get session key from access_token?. A: There is no such term infinite session keys. But you can ask user to give you offline access extended permission. If user approved the permission, then you can save the session key and later user. If you use new php sdk, then you'll find there is a method $facebook->setSession($session); You've to pass users's stored session to here.
How we get a session key from an access_token
I got an access_token using facebook Graph API. https://graph.facebook.com/me?access_token=... I want session key. is there any method to get session key from access_token?.
[ "There is no such term infinite session keys. But you can ask user to give you offline access extended permission. If user approved the permission, then you can save the session key and later user. \nIf you use new php sdk, then you'll find there is a method $facebook->setSession($session); You've to pass users's stored session to here.\n" ]
[ 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0002816733_facebook_python.txt
Q: change values in a list - python I have this code: a=[['a','b','c'],['a','f','c'],['a','c','d']] for x in a: for y in x: if 'a' in x: x.replace('a','*')` but the result is: a=[['a','b','c'],['a','f','c'],['a','c','d']] and bot a=[['b','c'],['f','c'],['c','d']] What should I do so the changes will last? A: If you want to remove all occurrences of 'a' from all nested sublists, you could do: >>> [[i for i in x if i != 'a'] for x in a] [['b', 'c'], ['f', 'c'], ['c', 'd']] if you want to replace them with asterisk: >>> [[i if i != 'a' else '*' for i in x] for x in a] [['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']] A: This isn't about the list. Python strings are immutable: > a = 'x' > a.replace('x', 'bye') > a 'x' You're replacing 'a' with '*' and then throwing away the result. Try something like: for i,value in enumerate(mylist): mylist[i] = value.replace('x', 'y') A: You really want to replace the element in the nested list, like so: a=[['a','b','c'],['a','f','c'],['a','c','d']] for row in a: for ix, char in enumerate(row): if char == 'a': row[ix] = '*' With the result: a = [['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']] A: Search for the function replace: str.replace(old, new[, count]) Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. A: This would work: a=[['a','b','c'],['a','f','c'],['a','c','d']] for x in a: for y in x: if y == 'a': x.remove(y) Or even simpler: y = 'a' a=[['a','b','c'],['a','f','c'],['a','c','d']] for x in a: x.remove(y) Which gives you a=[['b','c'],['f','c'],['c','d']]. Note: See the documentation on remove() for lists here. A: a=[['a','b','c'],['a','f','c'],['a','c','d']] b=[[subelt.replace('a','*') for subelt in elt] for elt in a] print(b) # [['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']]
change values in a list - python
I have this code: a=[['a','b','c'],['a','f','c'],['a','c','d']] for x in a: for y in x: if 'a' in x: x.replace('a','*')` but the result is: a=[['a','b','c'],['a','f','c'],['a','c','d']] and bot a=[['b','c'],['f','c'],['c','d']] What should I do so the changes will last?
[ "If you want to remove all occurrences of 'a' from all nested sublists, you could do:\n>>> [[i for i in x if i != 'a'] for x in a]\n[['b', 'c'], ['f', 'c'], ['c', 'd']]\n\nif you want to replace them with asterisk:\n>>> [[i if i != 'a' else '*' for i in x] for x in a]\n[['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']]\n\n", "This isn't about the list. Python strings are immutable:\n> a = 'x'\n> a.replace('x', 'bye')\n> a\n'x'\n\nYou're replacing 'a' with '*' and then throwing away the result.\nTry something like:\nfor i,value in enumerate(mylist):\n mylist[i] = value.replace('x', 'y')\n\n", "You really want to replace the element in the nested list, like so:\na=[['a','b','c'],['a','f','c'],['a','c','d']] \nfor row in a:\n for ix, char in enumerate(row):\n if char == 'a':\n row[ix] = '*'\n\nWith the result:\na = [['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']]\n\n", "Search for the function replace:\nstr.replace(old, new[, count])\n\n\nReturn a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the\n first count occurrences are replaced.\n\n", "This would work:\na=[['a','b','c'],['a','f','c'],['a','c','d']]\nfor x in a: \n for y in x: \n if y == 'a':\n x.remove(y)\n\nOr even simpler:\ny = 'a'\na=[['a','b','c'],['a','f','c'],['a','c','d']]\nfor x in a: \n x.remove(y)\n\nWhich gives you a=[['b','c'],['f','c'],['c','d']].\nNote: See the documentation on remove() for lists here.\n", "a=[['a','b','c'],['a','f','c'],['a','c','d']]\nb=[[subelt.replace('a','*') for subelt in elt] for elt in a]\nprint(b)\n\n# [['*', 'b', 'c'], ['*', 'f', 'c'], ['*', 'c', 'd']]\n\n" ]
[ 5, 4, 1, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002821329_list_python.txt
Q: Python print statement prints nothing with a carriage return I'm trying to write a simple tool that reads files from disc, does some image processing, and returns the result of the algorithm. Since the program can sometimes take awhile, I like to have a progress bar so I know where it is in the program. And since I don't like to clutter up my command line and I'm on a Unix platform, I wanted to use the '\r' character to print the progress bar on only one line. But when I have this code here, it prints nothing. # Files is a list with the filenames for i, f in enumerate(files): print '\r%d / %d' % (i, len(files)), # Code that takes a long time I have also tried: print '\r', i, '/', len(files), Now just to make sure this worked in python, I tried this: heartbeat = 1 while True: print '\rHello, world', heartbeat, heartbeat += 1 This code works perfectly. What's going on? My understanding of carriage returns on Linux was that it would just move the line feed character to the beginning and then I could overwrite old text that was written previously, as long as I don't print a newline anywhere. This doesn't seem to be happening though. Also, is there a better way to display a progress bar in a command line than what I'm current trying to do? A: Try adding sys.stdout.flush() after the print statement. It's possible that print isn't flushing the output until it writes a newline, which doesn't happen here. A: Handling of carriage returns in Linux differs greatly between terminal-emulators. Normally, one would use terminal escape codes that would tell the terminal emulator to move the virtual "carriage" around the screen (think full-screen programs running over BBS lines). The ones I'm aware of are the VT100 escape codes: \e[A: up \e[B: down \e[C: right \e[D: left \e[1~: home \e[4~: end Where \e is the escape character, \x1b. Try replacing all \r's with \e[1~ Also see this post A: If your terminal is line-buffered, you may need a sys.stdout.flush() to see your printing if you don't issue a linefeed.
Python print statement prints nothing with a carriage return
I'm trying to write a simple tool that reads files from disc, does some image processing, and returns the result of the algorithm. Since the program can sometimes take awhile, I like to have a progress bar so I know where it is in the program. And since I don't like to clutter up my command line and I'm on a Unix platform, I wanted to use the '\r' character to print the progress bar on only one line. But when I have this code here, it prints nothing. # Files is a list with the filenames for i, f in enumerate(files): print '\r%d / %d' % (i, len(files)), # Code that takes a long time I have also tried: print '\r', i, '/', len(files), Now just to make sure this worked in python, I tried this: heartbeat = 1 while True: print '\rHello, world', heartbeat, heartbeat += 1 This code works perfectly. What's going on? My understanding of carriage returns on Linux was that it would just move the line feed character to the beginning and then I could overwrite old text that was written previously, as long as I don't print a newline anywhere. This doesn't seem to be happening though. Also, is there a better way to display a progress bar in a command line than what I'm current trying to do?
[ "Try adding sys.stdout.flush() after the print statement. It's possible that print isn't flushing the output until it writes a newline, which doesn't happen here.\n", "Handling of carriage returns in Linux differs greatly between terminal-emulators.\nNormally, one would use terminal escape codes that would tell the terminal emulator to move the virtual \"carriage\" around the screen (think full-screen programs running over BBS lines). The ones I'm aware of are the VT100 escape codes:\n\\e[A: up\n\\e[B: down\n\\e[C: right\n\\e[D: left\n\\e[1~: home\n\\e[4~: end\nWhere \\e is the escape character, \\x1b.\nTry replacing all \\r's with \\e[1~\nAlso see this post\n", "If your terminal is line-buffered, you may need a sys.stdout.flush() to see your printing if you don't issue a linefeed.\n" ]
[ 10, 2, 2 ]
[]
[]
[ "carriage_return", "command_line", "python" ]
stackoverflow_0002821503_carriage_return_command_line_python.txt
Q: PyGTK: Doubleclick on CellRenderer In my PyGTK application I currently use 'editable' to make cells editable. But since my cell contents sometimes are really really large I want to ask the user for changes in a new window when he doubleclicks on a cell. But I could not find out how to hook on double-clicks on specific cellrenderers - I don't want to edit the whole row and I also don't want to set this callback for the whole row, only for columns where too long content can occur. How can I do this with CellRendererText() or something similar. My currently cell-generating code is: cols[i] = gtk.TreeViewColumn(coltitle) cells[i] = gtk.CellRendererText() cols[i].pack_start(cells[i]) cols[i].add_attribute(cells[i], 'text', i) cols[i].set_sizing(gtk.TREE_VIEW_COLUMN_FIXED) cols[i].set_fixed_width(100) cells[i].set_property('editable', True) cells[i].connect('edited', self.edited, (i, ls)) cols[i].set_resizable(True) mytreeview.append_column(cols[i]) Thanks! A: I believe this is not possible directly. However, you can connect to button-press-event on the gtk.TreeView. Then, when event.type equals to gtk.gdk._2BUTTON_PRESS, convert x and y to tree location using gtk.TreeView.get_path_at_pos(). This will return both a tree path indicating the row and gtk.TreeViewColumn object on which the click was made.
PyGTK: Doubleclick on CellRenderer
In my PyGTK application I currently use 'editable' to make cells editable. But since my cell contents sometimes are really really large I want to ask the user for changes in a new window when he doubleclicks on a cell. But I could not find out how to hook on double-clicks on specific cellrenderers - I don't want to edit the whole row and I also don't want to set this callback for the whole row, only for columns where too long content can occur. How can I do this with CellRendererText() or something similar. My currently cell-generating code is: cols[i] = gtk.TreeViewColumn(coltitle) cells[i] = gtk.CellRendererText() cols[i].pack_start(cells[i]) cols[i].add_attribute(cells[i], 'text', i) cols[i].set_sizing(gtk.TREE_VIEW_COLUMN_FIXED) cols[i].set_fixed_width(100) cells[i].set_property('editable', True) cells[i].connect('edited', self.edited, (i, ls)) cols[i].set_resizable(True) mytreeview.append_column(cols[i]) Thanks!
[ "I believe this is not possible directly. However, you can connect to button-press-event on the gtk.TreeView. Then, when event.type equals to gtk.gdk._2BUTTON_PRESS, convert x and y to tree location using gtk.TreeView.get_path_at_pos(). This will return both a tree path indicating the row and gtk.TreeViewColumn object on which the click was made.\n" ]
[ 3 ]
[]
[]
[ "cellrenderer", "double_click", "pygtk", "python" ]
stackoverflow_0002821584_cellrenderer_double_click_pygtk_python.txt
Q: Why does 'url' not work as a variable here? I originally had the variable cpanel named url and the code would not return anything. Any idea why? It doesn't seem to be used by anything else, but there's gotta be something I'm overlooking. import urllib2 cpanel = 'http://www.tas-tech.com/cpanel' req = urllib2.Request(cpanel) try: handle = urllib2.urlopen(req) except IOError, e: if hasattr(e, 'code'): if e.code != 401: print 'We got another error' print e.code else: print e.headers print e.headers['www-authenticate'] A: Note that urllib2.Request has a parameter named url, but that really shouldn't be the source of the problem, it works as expected: >>> import urllib2 >>> url = "http://www.google.com" >>> req = urllib2.Request(url) >>> urllib2.urlopen(req).code 200 Note that your code above functions identically when you switch cpanel for url. So the problem must have been elsewhere. A: I'm pretty sure that /cpanel (if it is the hosting control panel) actually redirects (302) you to http://www.tas-tech.com:2082/ or something like that. You should just update your thing to deal with the redirect (or better yet, just send the request to the real address).
Why does 'url' not work as a variable here?
I originally had the variable cpanel named url and the code would not return anything. Any idea why? It doesn't seem to be used by anything else, but there's gotta be something I'm overlooking. import urllib2 cpanel = 'http://www.tas-tech.com/cpanel' req = urllib2.Request(cpanel) try: handle = urllib2.urlopen(req) except IOError, e: if hasattr(e, 'code'): if e.code != 401: print 'We got another error' print e.code else: print e.headers print e.headers['www-authenticate']
[ "Note that urllib2.Request has a parameter named url, but that really shouldn't be the source of the problem, it works as expected:\n>>> import urllib2\n>>> url = \"http://www.google.com\"\n>>> req = urllib2.Request(url)\n>>> urllib2.urlopen(req).code\n200\n\nNote that your code above functions identically when you switch cpanel for url. So the problem must have been elsewhere.\n", "I'm pretty sure that /cpanel (if it is the hosting control panel) actually redirects (302) you to http://www.tas-tech.com:2082/ or something like that. You should just update your thing to deal with the redirect (or better yet, just send the request to the real address).\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002822199_python.txt
Q: Python copy a DLL to site-packages on Windows I am writing a python extension module that needs to link with a third-party DLL. How can I copy this DLL to the site-packages directory using distutils (i.e. in my setup.py file)? A: Put your DLL in the package_data argument of your setup() (see the Installing Package Data section of the distutils documentation for details). If you need to put the DLL outside of the package directory , you can use the data_files option. For example to put it in the site-packages directory: import distutils.sysconfig setup( # [...] data_files = [(distutils.sysconfig.get_python_lib(), ["/path/to/the/DLL"])], )
Python copy a DLL to site-packages on Windows
I am writing a python extension module that needs to link with a third-party DLL. How can I copy this DLL to the site-packages directory using distutils (i.e. in my setup.py file)?
[ "Put your DLL in the package_data argument of your setup() (see the Installing Package Data section of the distutils documentation for details).\nIf you need to put the DLL outside of the package directory , you can use the data_files option. For example to put it in the site-packages directory:\nimport distutils.sysconfig\n\nsetup(\n # [...]\n data_files = [(distutils.sysconfig.get_python_lib(), [\"/path/to/the/DLL\"])],\n)\n\n" ]
[ 8 ]
[]
[]
[ "dll", "python", "windows" ]
stackoverflow_0002822424_dll_python_windows.txt
Q: Program to find canonical cover or minimum number of functional dependencies I would like to find the canonical cover or minimum number of functional dependencies in a database. For example: If you have: Table = (A,B,C) <-- these are columns: A,B,C And dependencies: A → BC B → C A → B AB → C The canonical cover (or minimum number of dependencies) is: A → B B → C Is there a program that can accomplish this? If not, any code/pseudocode to help me write one would be appreciated. Prefer in Python or Java. A: Looking at your dependencies, it looks like you can view them as a partial order on A, B, C. What you want sounds a lot like (but not entirely) a topological sort (a partial order sort on a directed acyclic graph). A: Looks to me like you can refactor any rules of the form: A -> BC into A -> B and A -> C and any rules of the form: AB -> C into A -> C and B -> C After this refactoring, you should have a set of rules of the singleton pairs: X -> Y (Likely with lots of redundant copies you can immediately remove). This forms the partial order that rlotun seemed to referring to. For the example so far, you end up with: A -> B B -> C A -> C If you then minimize the partial order (e.g., remove any redundant links, any data structure books on partial should tell you how to do that), you'll have a minimal partial order, and I think that's the answer you want. Minimizing the partial order in the example, you'd delete A -> C from the partial order, ending with your answer.
Program to find canonical cover or minimum number of functional dependencies
I would like to find the canonical cover or minimum number of functional dependencies in a database. For example: If you have: Table = (A,B,C) <-- these are columns: A,B,C And dependencies: A → BC B → C A → B AB → C The canonical cover (or minimum number of dependencies) is: A → B B → C Is there a program that can accomplish this? If not, any code/pseudocode to help me write one would be appreciated. Prefer in Python or Java.
[ "Looking at your dependencies, it looks like you can view them as a partial order on A, B, C. What you want sounds a lot like (but not entirely) a topological sort (a partial order sort on a directed acyclic graph).\n", "Looks to me like you can refactor any rules of the form:\n A -> BC\n\ninto\n A -> B\n\nand \n A -> C\n\nand any rules of the form:\n AB -> C\n\ninto\n A -> C\n\nand \n B -> C\n\nAfter this refactoring, you should have a set of rules of the singleton pairs:\n X -> Y\n\n(Likely with lots of redundant copies you can immediately remove).\nThis forms the partial order that rlotun seemed to referring to.\nFor the example so far, you end up with:\n A -> B\n B -> C\n A -> C\n\nIf you then minimize the partial order (e.g., remove any redundant links,\nany data structure books on partial should tell you how to do that), you'll\nhave a minimal partial order, and I think that's the answer you want.\nMinimizing the partial order in the example, you'd delete A -> C from\nthe partial order, ending with your answer.\n" ]
[ 0, 0 ]
[]
[]
[ "database", "database_design", "java", "python" ]
stackoverflow_0002822809_database_database_design_java_python.txt
Q: call multiple c++ functions in python using threads Suppose I have a C(++) function taking an integer, and it is bound to (C)python with python api, so I can call it from python: import c_module c_module.f(10) now, I want to parallelize it. The problem is: how does the GIL work in this case? Suppose I have a queue of numbers to be processed, and some workers (threading.Thread) working in parallel, each of them calling c_module.f(number) where number is taken from a queue. The difference with the usual case, when GIL lock the interpreter, is that now you don't need the interpreter to evaluate c_module.f because it is compiled. So the question is: in this case the processing is really parallel? A: Threads currently executing the C extension code for which the GIL was explicitly released will run in parallel. See http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock for what you need to do in your extension. Python threads are most useful for I/O bound execution or for GUI responsiveness. I wouldn't do python-heavy execution with threads. If you want guaranteed parallelism, check out the multiprocessing library.
call multiple c++ functions in python using threads
Suppose I have a C(++) function taking an integer, and it is bound to (C)python with python api, so I can call it from python: import c_module c_module.f(10) now, I want to parallelize it. The problem is: how does the GIL work in this case? Suppose I have a queue of numbers to be processed, and some workers (threading.Thread) working in parallel, each of them calling c_module.f(number) where number is taken from a queue. The difference with the usual case, when GIL lock the interpreter, is that now you don't need the interpreter to evaluate c_module.f because it is compiled. So the question is: in this case the processing is really parallel?
[ "Threads currently executing the C extension code for which the GIL was explicitly released will run in parallel. See http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock for what you need to do in your extension.\nPython threads are most useful for I/O bound execution or for GUI responsiveness. I wouldn't do python-heavy execution with threads. If you want guaranteed parallelism, check out the multiprocessing library.\n" ]
[ 4 ]
[]
[]
[ "c++", "gil", "multithreading", "python" ]
stackoverflow_0002822636_c++_gil_multithreading_python.txt
Q: integrate / build 'weather radar' widget I'm looking to integrate a 'weather radar' widget into a site I'm building. The only available resource I can find is: http://www.meteoonline.co.uk/gadgets/Europe/Netherlands/135 which basically delivers a flash mov in a iframe ! urrrgh! - and 'permission denied' of course with any javascript interaction on the iframe.. Can anyone suggest an alternative resource / or approach ? I'm happy to work with the raw data if I can get it .. any ideas welcome ! site is like >[ html5 + jquery on django ] A: My suggestion would be to check Programmable Web to see what APIs are available for weather data. A quick scan shows they had a blog post about 5 weather APIs last year and filtering by 'weather' category I see 10 available now. I don't know if any of them have a radar but it would be a good place to start. A: -> Find an RSS feed of radar images for your target area this one works for me : http://rss.buienradar.nl/radar.php
integrate / build 'weather radar' widget
I'm looking to integrate a 'weather radar' widget into a site I'm building. The only available resource I can find is: http://www.meteoonline.co.uk/gadgets/Europe/Netherlands/135 which basically delivers a flash mov in a iframe ! urrrgh! - and 'permission denied' of course with any javascript interaction on the iframe.. Can anyone suggest an alternative resource / or approach ? I'm happy to work with the raw data if I can get it .. any ideas welcome ! site is like >[ html5 + jquery on django ]
[ "My suggestion would be to check Programmable Web to see what APIs are available for weather data. A quick scan shows they had a blog post about 5 weather APIs last year\nand filtering by 'weather' category I see 10 available now. I don't know if any of them have a radar but it would be a good place to start.\n", "-> Find an RSS feed of radar images for your target area\nthis one works for me : http://rss.buienradar.nl/radar.php\n" ]
[ 1, 0 ]
[]
[]
[ "django", "jquery", "python", "weather" ]
stackoverflow_0002820953_django_jquery_python_weather.txt
Q: Parsing a string representing a float *with an exponent* in Python I have a large file with numbers in the form of 6,52353753563E-7. So there's an exponent in that string. float() dies on this. While I could write custom code to pre-process the string into something float() can eat, I'm looking for the pythonic way of converting these into a float (something like a format string passed somewhere). I must say I'm surprised float() can't handle strings with such an exponent, this is pretty common stuff. I'm using python 2.6, but 3.1 is an option if need be. A: Nothing to do with exponent. Problem is comma instead of decimal point. >>> float("6,52353753563E-7") Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for float(): 6,52353753563E-7 >>> float("6.52353753563E-7") 6.5235375356299998e-07 For a general approach, see locale.atof() A: Your problem is not in the exponent but in the comma. with python 3.1: >>> a = "6.52353753563E-7" >>> float(a) 6.52353753563e-07
Parsing a string representing a float *with an exponent* in Python
I have a large file with numbers in the form of 6,52353753563E-7. So there's an exponent in that string. float() dies on this. While I could write custom code to pre-process the string into something float() can eat, I'm looking for the pythonic way of converting these into a float (something like a format string passed somewhere). I must say I'm surprised float() can't handle strings with such an exponent, this is pretty common stuff. I'm using python 2.6, but 3.1 is an option if need be.
[ "Nothing to do with exponent. Problem is comma instead of decimal point.\n>>> float(\"6,52353753563E-7\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: invalid literal for float(): 6,52353753563E-7\n>>> float(\"6.52353753563E-7\")\n6.5235375356299998e-07\n\nFor a general approach, see locale.atof()\n", "Your problem is not in the exponent but in the comma.\nwith python 3.1:\n>>> a = \"6.52353753563E-7\"\n>>> float(a)\n6.52353753563e-07\n\n" ]
[ 15, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002823269_python.txt
Q: Parsing dbpedia JSON in Python I'm trying to get my head around the dbpedia JSON schema and can't figure out an efficient way of extracting a specific node: This is what dbpedia gives me: http://dbpedia.org/data/Ceramic_art.json I've got the whole thing as a JSON object in Python but don't really understand how to get the english abstract from this data. I've gotten this far: u = "http://dbpedia.org/data/Ceramic_art.json" data = urlfetch.fetch(url=u) json_data = json.loads(data.content) for j in json_data["http://dbpedia.org/resource/Ceramic_art"]: if(j == "http://dbpedia.org/ontology/abstract"): print "it's here" Not sure how to proceed from here. As you can see there are multiple languages. I need to get the english abstract. Thanks for your help, g A: It's a list of dicts. Just iterate through the elements of the list until you find the one whose value for u'lang' is u'en'. A: print [abstract['value'] for abstract in json_data["http://dbpedia.org/resource/Ceramic_art"]["http://dbpedia.org/ontology/abstract"] if abstract['lang'] == 'en'][0] Obviously, you'd want to do more error checking than that, in case the data is bad, but that's the basic idea.
Parsing dbpedia JSON in Python
I'm trying to get my head around the dbpedia JSON schema and can't figure out an efficient way of extracting a specific node: This is what dbpedia gives me: http://dbpedia.org/data/Ceramic_art.json I've got the whole thing as a JSON object in Python but don't really understand how to get the english abstract from this data. I've gotten this far: u = "http://dbpedia.org/data/Ceramic_art.json" data = urlfetch.fetch(url=u) json_data = json.loads(data.content) for j in json_data["http://dbpedia.org/resource/Ceramic_art"]: if(j == "http://dbpedia.org/ontology/abstract"): print "it's here" Not sure how to proceed from here. As you can see there are multiple languages. I need to get the english abstract. Thanks for your help, g
[ "It's a list of dicts. Just iterate through the elements of the list until you find the one whose value for u'lang' is u'en'.\n", "\nprint [abstract['value'] for abstract in json_data[\"http://dbpedia.org/resource/Ceramic_art\"][\"http://dbpedia.org/ontology/abstract\"] if abstract['lang'] == 'en'][0]\n\nObviously, you'd want to do more error checking than that, in case the data is bad, but that's the basic idea.\n" ]
[ 3, 3 ]
[]
[]
[ "dbpedia", "json", "python" ]
stackoverflow_0002823214_dbpedia_json_python.txt
Q: How do I code this relationship in SQLAlchemy? I am new to SQLAlchemy (and SQL, for that matter). I can't figure out how to code the idea I have in my head. I am creating a database of performance-test results. A test run consists of a test type and a number (this is class TestRun below) A test suite consists the version string of the software being tested, and one or more TestRun objects (this is class TestSuite below). A test version consists of all test suites with the given version name. Here is my code, as simple as I can make it: from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref, sessionmaker Base = declarative_base() class TestVersion (Base): __tablename__ = 'versions' id = Column (Integer, primary_key=True) version_name = Column (String) def __init__ (self, version_name): self.version_name = version_name class TestRun (Base): __tablename__ = 'runs' id = Column (Integer, primary_key=True) suite_directory = Column (String, ForeignKey ('suites.directory')) suite = relationship ('TestSuite', backref=backref ('runs', order_by=id)) test_type = Column (String) rate = Column (Integer) def __init__ (self, test_type, rate): self.test_type = test_type self.rate = rate class TestSuite (Base): __tablename__ = 'suites' directory = Column (String, primary_key=True) version_id = Column (Integer, ForeignKey ('versions.id')) version_ref = relationship ('TestVersion', backref=backref ('suites', order_by=directory)) version_name = Column (String) def __init__ (self, directory, version_name): self.directory = directory self.version_name = version_name # Create a v1.0 suite suite1 = TestSuite ('dir1', 'v1.0') suite1.runs.append (TestRun ('test1', 100)) suite1.runs.append (TestRun ('test2', 200)) # Create a another v1.0 suite suite2 = TestSuite ('dir2', 'v1.0') suite2.runs.append (TestRun ('test1', 101)) suite2.runs.append (TestRun ('test2', 201)) # Create another suite suite3 = TestSuite ('dir3', 'v2.0') suite3.runs.append (TestRun ('test1', 102)) suite3.runs.append (TestRun ('test2', 202)) # Create the in-memory database engine = create_engine ('sqlite://') Session = sessionmaker (bind=engine) session = Session() Base.metadata.create_all (engine) # Add the suites in version1 = TestVersion (suite1.version_name) version1.suites.append (suite1) session.add (suite1) version2 = TestVersion (suite2.version_name) version2.suites.append (suite2) session.add (suite2) version3 = TestVersion (suite3.version_name) version3.suites.append (suite3) session.add (suite3) session.commit() # Query the suites for suite in session.query (TestSuite).order_by (TestSuite.directory): print "\nSuite directory %s, version %s has %d test runs:" % (suite.directory, suite.version_name, len (suite.runs)) for run in suite.runs: print " Test '%s', result %d" % (run.test_type, run.rate) # Query the versions for version in session.query (TestVersion).order_by (TestVersion.version_name): print "\nVersion %s has %d test suites:" % (version.version_name, len (version.suites)) for suite in version.suites: print " Suite directory %s, version %s has %d test runs:" % (suite.directory, suite.version_name, len (suite.runs)) for run in suite.runs: print " Test '%s', result %d" % (run.test_type, run.rate) The output of this program: Suite directory dir1, version v1.0 has 2 test runs: Test 'test1', result 100 Test 'test2', result 200 Suite directory dir2, version v1.0 has 2 test runs: Test 'test1', result 101 Test 'test2', result 201 Suite directory dir3, version v2.0 has 2 test runs: Test 'test1', result 102 Test 'test2', result 202 Version v1.0 has 1 test suites: Suite directory dir1, version v1.0 has 2 test runs: Test 'test1', result 100 Test 'test2', result 200 Version v1.0 has 1 test suites: Suite directory dir2, version v1.0 has 2 test runs: Test 'test1', result 101 Test 'test2', result 201 Version v2.0 has 1 test suites: Suite directory dir3, version v2.0 has 2 test runs: Test 'test1', result 102 Test 'test2', result 202 This is not correct, since there are two TestVersion objects with the name 'v1.0'. I hacked my way around this by adding a private list of TestVersion objects, and a function to find a matching one: versions = [] def find_or_create_version (version_name): # Find existing for version in versions: if version.version_name == version_name: return (version) # Create new version = TestVersion (version_name) versions.append (version) return (version) Then I modified my code that adds the records to use it: # Add the suites in version1 = find_or_create_version (suite1.version_name) version1.suites.append (suite1) session.add (suite1) version2 = find_or_create_version (suite2.version_name) version2.suites.append (suite2) session.add (suite2) version3 = find_or_create_version (suite3.version_name) version3.suites.append (suite3) session.add (suite3) Now the output is what I want: Suite directory dir1, version v1.0 has 2 test runs: Test 'test1', result 100 Test 'test2', result 200 Suite directory dir2, version v1.0 has 2 test runs: Test 'test1', result 101 Test 'test2', result 201 Suite directory dir3, version v2.0 has 2 test runs: Test 'test1', result 102 Test 'test2', result 202 Version v1.0 has 2 test suites: Suite directory dir1, version v1.0 has 2 test runs: Test 'test1', result 100 Test 'test2', result 200 Suite directory dir2, version v1.0 has 2 test runs: Test 'test1', result 101 Test 'test2', result 201 Version v2.0 has 1 test suites: Suite directory dir3, version v2.0 has 2 test runs: Test 'test1', result 102 Test 'test2', result 202 This feels wrong to me; it doesn't feel right that I am manually keeping track of the unique version names, and manually adding the suites to the appropriate TestVersion objects. Is this code even close to being correct? And what happens when I'm not building the entire database from scratch, as in this example. If the database already exists, do I have to query the database's TestVersion table to discover the unique version names? Thanks in advance. I know this is a lot of code to wade through, and I appreciate the help. A: I cannot understand what your question is, in large part because you haven't refined it. Your question is about a schema perhaps, and possibly its corresponding object relational model. So, here is the ORM stripped to its core: class TestVersion(Base): __tablename__ = 'versions' id = Column(Integer, primary_key=True) name = Column(String) class TestSuite(Base): __tablename__ = 'suites' directory = Column(String, primary_key=True) version = Column(Integer, ForeignKey ('versions.id')) parent = relationship(TestVersion, backref=backref('suites', order_by=directory)) class TestRun(Base): __tablename__ = 'runs' id = Column(Integer, primary_key=True) directory = Column(String, ForeignKey ('suites.directory')) parent = relationship(TestSuite, backref=backref('runs', order_by=id)) I took a lot of liberties with your declaration: throwing out columns unrelated to your issue, reordering the declarations to make the dependency chain more obvious, etc. Perhaps against this reduced model you can better describe your problem. Also, coding standards like PEP 8 exist for a reason: if you want your code to be understandable to others, use 4 space indentions and eschew spaces between a Name and a '(', limit lines to 79 characters, etc. Yes, this seems pedantic, but you just ran into a situation where your reader had more difficulty reading your code than you'd like.
How do I code this relationship in SQLAlchemy?
I am new to SQLAlchemy (and SQL, for that matter). I can't figure out how to code the idea I have in my head. I am creating a database of performance-test results. A test run consists of a test type and a number (this is class TestRun below) A test suite consists the version string of the software being tested, and one or more TestRun objects (this is class TestSuite below). A test version consists of all test suites with the given version name. Here is my code, as simple as I can make it: from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref, sessionmaker Base = declarative_base() class TestVersion (Base): __tablename__ = 'versions' id = Column (Integer, primary_key=True) version_name = Column (String) def __init__ (self, version_name): self.version_name = version_name class TestRun (Base): __tablename__ = 'runs' id = Column (Integer, primary_key=True) suite_directory = Column (String, ForeignKey ('suites.directory')) suite = relationship ('TestSuite', backref=backref ('runs', order_by=id)) test_type = Column (String) rate = Column (Integer) def __init__ (self, test_type, rate): self.test_type = test_type self.rate = rate class TestSuite (Base): __tablename__ = 'suites' directory = Column (String, primary_key=True) version_id = Column (Integer, ForeignKey ('versions.id')) version_ref = relationship ('TestVersion', backref=backref ('suites', order_by=directory)) version_name = Column (String) def __init__ (self, directory, version_name): self.directory = directory self.version_name = version_name # Create a v1.0 suite suite1 = TestSuite ('dir1', 'v1.0') suite1.runs.append (TestRun ('test1', 100)) suite1.runs.append (TestRun ('test2', 200)) # Create a another v1.0 suite suite2 = TestSuite ('dir2', 'v1.0') suite2.runs.append (TestRun ('test1', 101)) suite2.runs.append (TestRun ('test2', 201)) # Create another suite suite3 = TestSuite ('dir3', 'v2.0') suite3.runs.append (TestRun ('test1', 102)) suite3.runs.append (TestRun ('test2', 202)) # Create the in-memory database engine = create_engine ('sqlite://') Session = sessionmaker (bind=engine) session = Session() Base.metadata.create_all (engine) # Add the suites in version1 = TestVersion (suite1.version_name) version1.suites.append (suite1) session.add (suite1) version2 = TestVersion (suite2.version_name) version2.suites.append (suite2) session.add (suite2) version3 = TestVersion (suite3.version_name) version3.suites.append (suite3) session.add (suite3) session.commit() # Query the suites for suite in session.query (TestSuite).order_by (TestSuite.directory): print "\nSuite directory %s, version %s has %d test runs:" % (suite.directory, suite.version_name, len (suite.runs)) for run in suite.runs: print " Test '%s', result %d" % (run.test_type, run.rate) # Query the versions for version in session.query (TestVersion).order_by (TestVersion.version_name): print "\nVersion %s has %d test suites:" % (version.version_name, len (version.suites)) for suite in version.suites: print " Suite directory %s, version %s has %d test runs:" % (suite.directory, suite.version_name, len (suite.runs)) for run in suite.runs: print " Test '%s', result %d" % (run.test_type, run.rate) The output of this program: Suite directory dir1, version v1.0 has 2 test runs: Test 'test1', result 100 Test 'test2', result 200 Suite directory dir2, version v1.0 has 2 test runs: Test 'test1', result 101 Test 'test2', result 201 Suite directory dir3, version v2.0 has 2 test runs: Test 'test1', result 102 Test 'test2', result 202 Version v1.0 has 1 test suites: Suite directory dir1, version v1.0 has 2 test runs: Test 'test1', result 100 Test 'test2', result 200 Version v1.0 has 1 test suites: Suite directory dir2, version v1.0 has 2 test runs: Test 'test1', result 101 Test 'test2', result 201 Version v2.0 has 1 test suites: Suite directory dir3, version v2.0 has 2 test runs: Test 'test1', result 102 Test 'test2', result 202 This is not correct, since there are two TestVersion objects with the name 'v1.0'. I hacked my way around this by adding a private list of TestVersion objects, and a function to find a matching one: versions = [] def find_or_create_version (version_name): # Find existing for version in versions: if version.version_name == version_name: return (version) # Create new version = TestVersion (version_name) versions.append (version) return (version) Then I modified my code that adds the records to use it: # Add the suites in version1 = find_or_create_version (suite1.version_name) version1.suites.append (suite1) session.add (suite1) version2 = find_or_create_version (suite2.version_name) version2.suites.append (suite2) session.add (suite2) version3 = find_or_create_version (suite3.version_name) version3.suites.append (suite3) session.add (suite3) Now the output is what I want: Suite directory dir1, version v1.0 has 2 test runs: Test 'test1', result 100 Test 'test2', result 200 Suite directory dir2, version v1.0 has 2 test runs: Test 'test1', result 101 Test 'test2', result 201 Suite directory dir3, version v2.0 has 2 test runs: Test 'test1', result 102 Test 'test2', result 202 Version v1.0 has 2 test suites: Suite directory dir1, version v1.0 has 2 test runs: Test 'test1', result 100 Test 'test2', result 200 Suite directory dir2, version v1.0 has 2 test runs: Test 'test1', result 101 Test 'test2', result 201 Version v2.0 has 1 test suites: Suite directory dir3, version v2.0 has 2 test runs: Test 'test1', result 102 Test 'test2', result 202 This feels wrong to me; it doesn't feel right that I am manually keeping track of the unique version names, and manually adding the suites to the appropriate TestVersion objects. Is this code even close to being correct? And what happens when I'm not building the entire database from scratch, as in this example. If the database already exists, do I have to query the database's TestVersion table to discover the unique version names? Thanks in advance. I know this is a lot of code to wade through, and I appreciate the help.
[ "I cannot understand what your question is, in large part because you haven't refined it. Your question is about a schema perhaps, and possibly its corresponding object relational model. So, here is the ORM stripped to its core:\nclass TestVersion(Base):\n __tablename__ = 'versions'\n id = Column(Integer, primary_key=True)\n name = Column(String)\n\nclass TestSuite(Base):\n __tablename__ = 'suites'\n directory = Column(String, primary_key=True)\n version = Column(Integer, ForeignKey ('versions.id'))\n\n parent = relationship(TestVersion, backref=backref('suites',\n order_by=directory))\n\nclass TestRun(Base):\n __tablename__ = 'runs'\n id = Column(Integer, primary_key=True)\n directory = Column(String, ForeignKey ('suites.directory'))\n\n parent = relationship(TestSuite, backref=backref('runs',\n order_by=id))\n\nI took a lot of liberties with your declaration: throwing out columns unrelated to your issue, reordering the declarations to make the dependency chain more obvious, etc. Perhaps against this reduced model you can better describe your problem.\nAlso, coding standards like PEP 8 exist for a reason: if you want your code to be understandable to others, use 4 space indentions and eschew spaces between a Name and a '(', limit lines to 79 characters, etc. Yes, this seems pedantic, but you just ran into a situation where your reader had more difficulty reading your code than you'd like.\n" ]
[ 1 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0002822789_python_sql_sqlalchemy.txt
Q: Remove padding in wxPython's wxWizard I'm using wxPython to create a wizard using the wxWizard control. I'm trying to a draw a colored rectangle but when I run the app, there seems to be a about a 10px padding on each side of the rectangle. This goes for all other controls too. I have to offset them a bit so that they appear exactly where I want them to. Is there any way I could remove this padding? Here's the source of my base Wizard page. class SimplePage(wx.wizard.PyWizardPage): """ Simple wizard page with unlimited rows of text. """ def __init__(self, parent, title): wx.wizard.PyWizardPage.__init__(self, parent) self.next = self.prev = None #self.sizer = wx.BoxSizer(wx.VERTICAL) title = wx.StaticText(self, -1, title) title.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)) #self.sizer.AddWindow(title, 0, wx.ALIGN_LEFT|wx.ALL, padding) #self.sizer.AddWindow(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.ALL, padding) # self.SetSizer(self.sizer) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnPaint(self, evt): """set up the device context (DC) for painting""" self.dc = wx.PaintDC(self) self.dc.BeginDrawing() self.dc.SetPen(wx.Pen("grey",style=wx.TRANSPARENT)) self.dc.SetBrush(wx.Brush("grey", wx.SOLID)) # set x, y, w, h for rectangle self.dc.DrawRectangle(0,0,500, 500) self.dc.EndDrawing() del self.dc def SetNext(self, next): self.next = next def SetPrev(self, prev): self.prev = prev def GetNext(self): return self.next def GetPrev(self): return self.prev def Activated(self, evt): """ Executed when page is being activated. """ return def Blocked(self, evt): """ Executed when page is about to be switched. Switching can be blocked by returning True. """ return False def Cancel(self, evt): """ Executed when wizard is about to be canceled. Canceling can be blocked by returning False. """ return True Thanks guys. A: I can't verify this ( I would post as comment but i don't have enough reputation). On my system the above code with if __name__ == "__main__": app = wx.App(0) frame_1 = wx.wizard.Wizard(None) s = SimplePage(frame_1,"") app.SetTopWindow(frame_1) s.Show() frame_1.Show() app.MainLoop() Gives no border on the DC (there is a border that is part of the top level window decoration. I verified this on windows (wx 2.8.10.1 python 2.4.4) and linux (wx 2.8.6.1 gtk)
Remove padding in wxPython's wxWizard
I'm using wxPython to create a wizard using the wxWizard control. I'm trying to a draw a colored rectangle but when I run the app, there seems to be a about a 10px padding on each side of the rectangle. This goes for all other controls too. I have to offset them a bit so that they appear exactly where I want them to. Is there any way I could remove this padding? Here's the source of my base Wizard page. class SimplePage(wx.wizard.PyWizardPage): """ Simple wizard page with unlimited rows of text. """ def __init__(self, parent, title): wx.wizard.PyWizardPage.__init__(self, parent) self.next = self.prev = None #self.sizer = wx.BoxSizer(wx.VERTICAL) title = wx.StaticText(self, -1, title) title.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)) #self.sizer.AddWindow(title, 0, wx.ALIGN_LEFT|wx.ALL, padding) #self.sizer.AddWindow(wx.StaticLine(self, -1), 0, wx.EXPAND|wx.ALL, padding) # self.SetSizer(self.sizer) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnPaint(self, evt): """set up the device context (DC) for painting""" self.dc = wx.PaintDC(self) self.dc.BeginDrawing() self.dc.SetPen(wx.Pen("grey",style=wx.TRANSPARENT)) self.dc.SetBrush(wx.Brush("grey", wx.SOLID)) # set x, y, w, h for rectangle self.dc.DrawRectangle(0,0,500, 500) self.dc.EndDrawing() del self.dc def SetNext(self, next): self.next = next def SetPrev(self, prev): self.prev = prev def GetNext(self): return self.next def GetPrev(self): return self.prev def Activated(self, evt): """ Executed when page is being activated. """ return def Blocked(self, evt): """ Executed when page is about to be switched. Switching can be blocked by returning True. """ return False def Cancel(self, evt): """ Executed when wizard is about to be canceled. Canceling can be blocked by returning False. """ return True Thanks guys.
[ "I can't verify this ( I would post as comment but i don't have enough reputation). \nOn my system the above code with \nif __name__ == \"__main__\":\n app = wx.App(0)\n frame_1 = wx.wizard.Wizard(None)\n s = SimplePage(frame_1,\"\")\n\n app.SetTopWindow(frame_1)\n s.Show()\n frame_1.Show()\n app.MainLoop()\n\nGives no border on the DC (there is a border that is part of the top level window decoration. \nI verified this on windows (wx 2.8.10.1 python 2.4.4) and linux (wx 2.8.6.1 gtk)\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002816323_python_wxpython.txt
Q: Design question? I am building music app, where user can do several tasks including but not limited to listening song, like song, recommend song to a friend and extra. currently I have this model: class Activity(models.Model): activity = models.TextField() user = models.ForeignKey(User) date = models.DateTimeField(auto_now=True) so far I thought about two solutions. 1. saving a string to database. e.g "you listened song xyz". 2. create a dictionary about the activity and save to the database using pickle or json. e.g. dict_ = {"activity_type":"listening", "song":song_obj} I am leaning to the second implementation, but not quite sure. so what do you think about those two methods? do you know better way to achieve the goal? A: Looks like all you need is an enumeration to match a table in your database. So in your UserActivity table, you will have userid, activityid, songid, datetime etc etc A: What about GenericForeignKey? You could have userid, activityid and content_object on your UserActivity where content_object is a song, an user or something completely different. content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id')
Design question?
I am building music app, where user can do several tasks including but not limited to listening song, like song, recommend song to a friend and extra. currently I have this model: class Activity(models.Model): activity = models.TextField() user = models.ForeignKey(User) date = models.DateTimeField(auto_now=True) so far I thought about two solutions. 1. saving a string to database. e.g "you listened song xyz". 2. create a dictionary about the activity and save to the database using pickle or json. e.g. dict_ = {"activity_type":"listening", "song":song_obj} I am leaning to the second implementation, but not quite sure. so what do you think about those two methods? do you know better way to achieve the goal?
[ "Looks like all you need is an enumeration to match a table in your database.\nSo in your UserActivity table, you will have\nuserid, activityid, songid, datetime etc etc\n", "What about GenericForeignKey? You could have userid, activityid and content_object on your UserActivity where content_object is a song, an user or something completely different.\ncontent_type = models.ForeignKey(ContentType)\nobject_id = models.PositiveIntegerField()\ncontent_object = generic.GenericForeignKey('content_type', 'object_id')\n\n" ]
[ 0, 0 ]
[]
[]
[ "django", "json", "pickle", "python" ]
stackoverflow_0002823783_django_json_pickle_python.txt
Q: how do i add variables with logistic distributions? i have X, Y, random logistic variables, how do I add them given the mean and scale for each? Logistic distribution. i ran a simulation in python, but i cannot get it to be exact. i ran a simulation on getting a random number X, Y, and keep score on the value of X + Y. then i did the same for getting a single random number with X + Y and test another scale based on the original scales, but i cannot fix the new scale to make them match A: The sum of two logistic random variables does not have a logistic distribution. However, the sum is approximately logistic. You could justify this by arguing that a logistic distribution is approximately normal and the sum of two normal random variables is normal. (This post explains how close the normal and logistic distributions are.) Say X1 has mean m1 and scale s1 and X2 has mean m2 and scale s2. Then X1 + X2 has mean m1 + m2. X1 has variance pi^2 s1^2 / 3 and X2 has variance pi^2 s2^2 / 3, so X1 + X2 has variance pi^2 (s1^2 + s2^2)/3. This is exact. We know the mean and variance of the sum, though not its exact distribution. But if you're willing to assume that the sum has an approximately logistic distribution, then the corresponding logistic distribution would have mean m1 + m2 and scale sqrt(s1^2 + s2^2). A: The numpy.random module (sorry for the strange link, but numpy's own site seems to be down right now) has a logistic function that should generate random numbers with a logistic distribution correctly (haven't tested it personally, but I'd be amazed if such a widely used package as numpy made incorrect claims). However, as several comments mentioned, the sum of two logistic-distribution random variables doesn't have logistic distribution itself.
how do i add variables with logistic distributions?
i have X, Y, random logistic variables, how do I add them given the mean and scale for each? Logistic distribution. i ran a simulation in python, but i cannot get it to be exact. i ran a simulation on getting a random number X, Y, and keep score on the value of X + Y. then i did the same for getting a single random number with X + Y and test another scale based on the original scales, but i cannot fix the new scale to make them match
[ "The sum of two logistic random variables does not have a logistic distribution. However, the sum is approximately logistic. You could justify this by arguing that a logistic distribution is approximately normal and the sum of two normal random variables is normal. (This post explains how close the normal and logistic distributions are.)\nSay X1 has mean m1 and scale s1 and X2 has mean m2 and scale s2. Then X1 + X2 has mean m1 + m2. X1 has variance pi^2 s1^2 / 3 and X2 has variance pi^2 s2^2 / 3, so X1 + X2 has variance pi^2 (s1^2 + s2^2)/3. This is exact. We know the mean and variance of the sum, though not its exact distribution. But if you're willing to assume that the sum has an approximately logistic distribution, then the corresponding logistic distribution would have mean m1 + m2 and scale sqrt(s1^2 + s2^2). \n", "The numpy.random module (sorry for the strange link, but numpy's own site seems to be down right now) has a logistic function that should generate random numbers with a logistic distribution correctly (haven't tested it personally, but I'd be amazed if such a widely used package as numpy made incorrect claims). However, as several comments mentioned, the sum of two logistic-distribution random variables doesn't have logistic distribution itself.\n" ]
[ 6, 1 ]
[]
[]
[ "math", "python" ]
stackoverflow_0002823468_math_python.txt
Q: Idea for a small project, should I use Python? I have a project idea, but unsure if using Python would be a good idea. Firstly, I'm a C++ and C# developer with some SQL experience. My day job is C++. I have a project idea i'd like to create and was considering developing it in a language I don't know. Python seems to be popular and has piqued my interests. I definitely use OOP in programming and I understand Python would work fine with that style. I could be way off on this, I've only read small bits and pieces about the language. The project won't be public or anything, just purely something of my own creation do dabble in at home. So the project would essentially represent a simple game idea I have. The game would consist roughly these things: Data structures to hold specific information (would be strongly typed). A way to output the gamestate for the players. This is completely up in the air, it can be graphical or text based, I don't really care at this point. A way to save off game data for the players in something like a database or file system. A relatively easy way for me to input information and a 'GO' button which processes the changes and obviously creates a new gamestate. The game would function similar to a board game. Really nothing out of the ordinary when I look back at that list. Would this be a fun way to learn Python or should I select another language? A: I find that the best way to learn a new language is by doing something like this (small project of your own). Python is no different. Everything you wrote can be done in Python, so I can't find any reason not to use it, if you want to learn. A: Python seems very suitable to your purposes (e.g., pygame and other popular third party extensions make it easy to achieve nice graphics, and you can also choose curses for structured textual I/O, etc) with the single exception of what you probably mean by "strongly typed". Python is strongly typed (there is no way you can erroneously use a string for an operation for which an integer is required, and vice versa, for example), but it's dynamic strong typing: each object has a strong type, but names (in the wide sense, including barenames, compound names, items in containers, ...) do not have types -- each name refers to an object, the object has the type, not the name. You can rebind the name to a different object, and that object may have a different (strong;-) type than whatever object was previously bound to that same name. Dynamic languages all have this character, even though many go further than Python in "type laxity" ("confusing" strings and numbers, and different kinds of numbers, while Python distinguishes strings from integers from floating-point numbers, for example) -- Python is quite "type-picky"... in the dynamic sense where names, per se, have no types, though;-). A: I've already voted for del-boy's answer, but I would like to go further and say that if your goals are to (1) have fun, (2) learn a new language, and (3) write your own game, then Python is a slam-dunk, no-brainer, awesome choice to achieve all three. The language excels at all the things you seem to be looking for (see Alex Martelli's answer for the caveat on strong typing), and in my opinion is not much of a "stretch" from the C family of languages (I think you will find most things simply easier, rather than strange), compared to other good languages such as Ruby or Lua. A: Well, if you do C++/C#, I'd say go for it - I personally love C++ because it is (in my opinion) self-intuitive and easy. The 'grammar' of Python doesn't make much sense. Plus, if you already know another language, why learn Python for fun? I mean, if you want to create a simple project for fun, it's really not worth it, and you'll end up working for several weeks at least, before you can begin your game. So yeah, you should definitely use C++. However, if you're just trying to learn a new language, there's nothing wrong with that; Python certainly is pretty popular. Javascript is pretty easy as well, as it uses automatic inference and all that jazz.
Idea for a small project, should I use Python?
I have a project idea, but unsure if using Python would be a good idea. Firstly, I'm a C++ and C# developer with some SQL experience. My day job is C++. I have a project idea i'd like to create and was considering developing it in a language I don't know. Python seems to be popular and has piqued my interests. I definitely use OOP in programming and I understand Python would work fine with that style. I could be way off on this, I've only read small bits and pieces about the language. The project won't be public or anything, just purely something of my own creation do dabble in at home. So the project would essentially represent a simple game idea I have. The game would consist roughly these things: Data structures to hold specific information (would be strongly typed). A way to output the gamestate for the players. This is completely up in the air, it can be graphical or text based, I don't really care at this point. A way to save off game data for the players in something like a database or file system. A relatively easy way for me to input information and a 'GO' button which processes the changes and obviously creates a new gamestate. The game would function similar to a board game. Really nothing out of the ordinary when I look back at that list. Would this be a fun way to learn Python or should I select another language?
[ "I find that the best way to learn a new language is by doing something like this (small project of your own). Python is no different. \nEverything you wrote can be done in Python, so I can't find any reason not to use it, if you want to learn.\n", "Python seems very suitable to your purposes (e.g., pygame and other popular third party extensions make it easy to achieve nice graphics, and you can also choose curses for structured textual I/O, etc) with the single exception of what you probably mean by \"strongly typed\".\nPython is strongly typed (there is no way you can erroneously use a string for an operation for which an integer is required, and vice versa, for example), but it's dynamic strong typing: each object has a strong type, but names (in the wide sense, including barenames, compound names, items in containers, ...) do not have types -- each name refers to an object, the object has the type, not the name. You can rebind the name to a different object, and that object may have a different (strong;-) type than whatever object was previously bound to that same name.\nDynamic languages all have this character, even though many go further than Python in \"type laxity\" (\"confusing\" strings and numbers, and different kinds of numbers, while Python distinguishes strings from integers from floating-point numbers, for example) -- Python is quite \"type-picky\"... in the dynamic sense where names, per se, have no types, though;-).\n", "I've already voted for del-boy's answer, but I would like to go further and say that if your goals are to (1) have fun, (2) learn a new language, and (3) write your own game, then Python is a slam-dunk, no-brainer, awesome choice to achieve all three.\nThe language excels at all the things you seem to be looking for (see Alex Martelli's answer for the caveat on strong typing), and in my opinion is not much of a \"stretch\" from the C family of languages (I think you will find most things simply easier, rather than strange), compared to other good languages such as Ruby or Lua.\n", "Well, if you do C++/C#, I'd say go for it - I personally love C++ because it is (in my opinion) self-intuitive and easy. The 'grammar' of Python doesn't make much sense. Plus, if you already know another language, why learn Python for fun? I mean, if you want to create a simple project for fun, it's really not worth it, and you'll end up working for several weeks at least, before you can begin your game. So yeah, you should definitely use C++. \n\nHowever, if you're just trying to learn a new language, there's nothing wrong with that; Python certainly is pretty popular. Javascript is pretty easy as well, as it uses automatic inference and all that jazz. \n" ]
[ 6, 5, 3, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002823983_oop_python.txt
Q: Dynamically add items to Tkinter Canvas I'm attempting to learn Tkinter with the goal of being able to create a 'real-time' scope to plot data. As a test, I'm trying to draw a polygon on the canvas every time the 'draw' button is pressed. The triangle position is randomized. I have two problems: There is a triangle on the canvas as soon as the program starts, why and how do I fix this? It doesn't draw any triangles when I press the button, at least none that I can see. Code: from Tkinter import * from random import randint class App: def __init__(self,master): #frame = Frame(master) #frame.pack(side = LEFT) self.plotspc = Canvas(master,height = 100, width = 200, bg = "white") self.plotspc.grid(row=0,column = 2, rowspan = 5) self.button = Button(master, text = "Quit", fg = "red", \ command = master.quit) self.button.grid(row=0,column=0) self.drawbutton = Button(master, text = "Draw", command = \ self.pt([50,50])) self.drawbutton.grid(row = 0, column = 1) def pt(self, coords): coords[0] = coords[0] + randint(-20,20) coords[1] = coords[1] + randint(-20,20) x = (0,5,10) y = (0,10,0) xp = [coords[0] + xv for xv in x] yp = [coords[1] + yv for yv in y] ptf = zip(xp,yp) self.plotspc.create_polygon(*ptf) if __name__ == "__main__": root = Tk() app = App(root) root.mainloop() A: command=self.pt([50,50]) (that you use in the Button call which builds the Draw button) immediately executes the call you're telling it to execute, and binds the result (None) to command. Use, instead, in that same: , command=lambda: self.pt([50, 50]) ) to delay the execution of the call to each time that button will be pressed.
Dynamically add items to Tkinter Canvas
I'm attempting to learn Tkinter with the goal of being able to create a 'real-time' scope to plot data. As a test, I'm trying to draw a polygon on the canvas every time the 'draw' button is pressed. The triangle position is randomized. I have two problems: There is a triangle on the canvas as soon as the program starts, why and how do I fix this? It doesn't draw any triangles when I press the button, at least none that I can see. Code: from Tkinter import * from random import randint class App: def __init__(self,master): #frame = Frame(master) #frame.pack(side = LEFT) self.plotspc = Canvas(master,height = 100, width = 200, bg = "white") self.plotspc.grid(row=0,column = 2, rowspan = 5) self.button = Button(master, text = "Quit", fg = "red", \ command = master.quit) self.button.grid(row=0,column=0) self.drawbutton = Button(master, text = "Draw", command = \ self.pt([50,50])) self.drawbutton.grid(row = 0, column = 1) def pt(self, coords): coords[0] = coords[0] + randint(-20,20) coords[1] = coords[1] + randint(-20,20) x = (0,5,10) y = (0,10,0) xp = [coords[0] + xv for xv in x] yp = [coords[1] + yv for yv in y] ptf = zip(xp,yp) self.plotspc.create_polygon(*ptf) if __name__ == "__main__": root = Tk() app = App(root) root.mainloop()
[ "command=self.pt([50,50]) (that you use in the Button call which builds the Draw button) immediately executes the call you're telling it to execute, and binds the result (None) to command. Use, instead, in that same:\n, command=lambda: self.pt([50, 50]) )\n\nto delay the execution of the call to each time that button will be pressed.\n" ]
[ 5 ]
[]
[]
[ "dynamic", "python", "tkinter_canvas" ]
stackoverflow_0002824041_dynamic_python_tkinter_canvas.txt
Q: Word XML to RTF conversion I am in a need of programatically convert an Word-XML file into a RTF file. It has become a requirement, because of some third party libraries. Any API/Library that can do that? Actually the language is not a problem because I just need to work done. But Java, .NET languages or Python are preferred. A: A Python/linux way: You need the OpenOffice Uno Bride (On server you could run OO in headless mode). As a result you can convert every OO-readable format to every OO-writeable: see http://wiki.services.openoffice.org/wiki/Framework/Article/Filter/FilterList_OOo_3_0 Run Example Code /usr/lib64/openoffice.org/program/soffice.bin -accept=socket,host=localhost,port=8100\;urp -headless Python Example: import uno from os.path import abspath, isfile, splitext from com.sun.star.beans import PropertyValue from com.sun.star.task import ErrorCodeIOException from com.sun.star.connection import NoConnectException FAMILY_TEXT = "Text" FAMILY_SPREADSHEET = "Spreadsheet" FAMILY_PRESENTATION = "Presentation" FAMILY_DRAWING = "Drawing" DEFAULT_OPENOFFICE_PORT = 8100 FILTER_MAP = { "pdf": { FAMILY_TEXT: "writer_pdf_Export", FAMILY_SPREADSHEET: "calc_pdf_Export", FAMILY_PRESENTATION: "impress_pdf_Export", FAMILY_DRAWING: "draw_pdf_Export" }, "html": { FAMILY_TEXT: "HTML (StarWriter)", FAMILY_SPREADSHEET: "HTML (StarCalc)", FAMILY_PRESENTATION: "impress_html_Export" }, "odt": { FAMILY_TEXT: "writer8" }, "doc": { FAMILY_TEXT: "MS Word 97" }, "rtf": { FAMILY_TEXT: "Rich Text Format" }, "txt": { FAMILY_TEXT: "Text" }, "docx": { FAMILY_TEXT: "MS Word 2007 XML" }, "ods": { FAMILY_SPREADSHEET: "calc8" }, "xls": { FAMILY_SPREADSHEET: "MS Excel 97" }, "odp": { FAMILY_PRESENTATION: "impress8" }, "ppt": { FAMILY_PRESENTATION: "MS PowerPoint 97" }, "swf": { FAMILY_PRESENTATION: "impress_flash_Export" } } class DocumentConverter: def __init__(self, port=DEFAULT_OPENOFFICE_PORT): localContext = uno.getComponentContext() resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext) try: self.context = resolver.resolve("uno:socket,host=localhost,port=%s;urp;StarOffice.ComponentContext" % port) except NoConnectException: raise Exception, "failed to connect to OpenOffice.org on port %s" % port self.desktop = self.context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", self.context) def convert(self, inputFile, outputFile): inputUrl = self._toFileUrl(inputFile) outputUrl = self._toFileUrl(outputFile) document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, self._toProperties(Hidden=True)) #document.setPropertyValue("DocumentTitle", "saf" ) TODO: Check how this can be set and set doc update mode to FULL_UPDATE if self._detectFamily(document) == FAMILY_TEXT: indexes = document.getDocumentIndexes() for i in range(0, indexes.getCount()): index = indexes.getByIndex(i) index.update() try: document.refresh() except AttributeError: pass indexes = document.getDocumentIndexes() for i in range(0, indexes.getCount()): index = indexes.getByIndex(i) index.update() outputExt = self._getFileExt(outputFile) filterName = self._filterName(document, outputExt) try: document.storeToURL(outputUrl, self._toProperties(FilterName=filterName)) finally: document.close(True) def _filterName(self, document, outputExt): family = self._detectFamily(document) try: filterByFamily = FILTER_MAP[outputExt] except KeyError: raise Exception, "unknown output format: '%s'" % outputExt try: return filterByFamily[family] except KeyError: raise Exception, "unsupported conversion: from '%s' to '%s'" % (family, outputExt) def _detectFamily(self, document): if document.supportsService("com.sun.star.text.GenericTextDocument"): # NOTE: a GenericTextDocument is either a TextDocument, a WebDocument, or a GlobalDocument # but this further distinction doesn't seem to matter for conversions return FAMILY_TEXT if document.supportsService("com.sun.star.sheet.SpreadsheetDocument"): return FAMILY_SPREADSHEET if document.supportsService("com.sun.star.presentation.PresentationDocument"): return FAMILY_PRESENTATION if document.supportsService("com.sun.star.drawing.DrawingDocument"): return FAMILY_DRAWING raise Exception, "unknown document family: %s" % document def _getFileExt(self, path): ext = splitext(path)[1] if ext is not None: return ext[1:].lower() def _toFileUrl(self, path): return uno.systemPathToFileUrl(abspath(path)) def _toProperties(self, **args): props = [] for key in args: prop = PropertyValue() prop.Name = key prop.Value = args[key] props.append(prop) return tuple(props) if __name__ == "__main__": from sys import argv, exit if len(argv) < 3: print "USAGE: python %s <input-file> <output-file>" % argv[0] exit(255) if not isfile(argv[1]): print "no such input file: %s" % argv[1] exit(1) try: converter = DocumentConverter() converter.convert(argv[1], argv[2]) except Exception, exception: print "ERROR!" + str(exception) exit(1) A: Java I've used Apache POI in the past to parse Word Documents. It seemed to work pretty well. Then here are some libraries to write to RTF. .Net Here's an article about writing to a Word Document in .Net. I'm sure you could use the same library for reading. Python Here is an article for Python. Related Question Also, here is a related if not duplicate question. A: have a look at Docvert. You'll have to set it up for yourself because the demo only lets you upload open office documents, i believe. A: You can use AutoIt to automate opening the XML files in word and doing a save as RTF. I've used the user defined functions for Word to save RTF files as plain text for conversion and it works good. The syntax is very easy. http://www.autoitscript.com/autoit3/index.shtml A: From java, you could use Docmosis to do conversion and optional populating. It sits over openoffice to perform the format conversions. If you install openoffice and manually load and save a few example documents you'll get a feel for whether the format conversions are good enough for you. If so, you can use Docmosis to drive it from Java.
Word XML to RTF conversion
I am in a need of programatically convert an Word-XML file into a RTF file. It has become a requirement, because of some third party libraries. Any API/Library that can do that? Actually the language is not a problem because I just need to work done. But Java, .NET languages or Python are preferred.
[ "A Python/linux way:\nYou need the OpenOffice Uno Bride (On server you could run OO in headless mode).\nAs a result you can convert every OO-readable format to every OO-writeable:\nsee http://wiki.services.openoffice.org/wiki/Framework/Article/Filter/FilterList_OOo_3_0\nRun Example Code\n/usr/lib64/openoffice.org/program/soffice.bin -accept=socket,host=localhost,port=8100\\;urp -headless\n\nPython Example:\nimport uno\nfrom os.path import abspath, isfile, splitext\nfrom com.sun.star.beans import PropertyValue\nfrom com.sun.star.task import ErrorCodeIOException\nfrom com.sun.star.connection import NoConnectException\n\nFAMILY_TEXT = \"Text\"\nFAMILY_SPREADSHEET = \"Spreadsheet\"\nFAMILY_PRESENTATION = \"Presentation\"\nFAMILY_DRAWING = \"Drawing\"\nDEFAULT_OPENOFFICE_PORT = 8100\n\nFILTER_MAP = {\n \"pdf\": {\n FAMILY_TEXT: \"writer_pdf_Export\",\n FAMILY_SPREADSHEET: \"calc_pdf_Export\",\n FAMILY_PRESENTATION: \"impress_pdf_Export\",\n FAMILY_DRAWING: \"draw_pdf_Export\"\n },\n \"html\": {\n FAMILY_TEXT: \"HTML (StarWriter)\",\n FAMILY_SPREADSHEET: \"HTML (StarCalc)\",\n FAMILY_PRESENTATION: \"impress_html_Export\"\n },\n \"odt\": { FAMILY_TEXT: \"writer8\" },\n \"doc\": { FAMILY_TEXT: \"MS Word 97\" },\n \"rtf\": { FAMILY_TEXT: \"Rich Text Format\" },\n \"txt\": { FAMILY_TEXT: \"Text\" },\n \"docx\": { FAMILY_TEXT: \"MS Word 2007 XML\" },\n \"ods\": { FAMILY_SPREADSHEET: \"calc8\" },\n \"xls\": { FAMILY_SPREADSHEET: \"MS Excel 97\" },\n \"odp\": { FAMILY_PRESENTATION: \"impress8\" },\n \"ppt\": { FAMILY_PRESENTATION: \"MS PowerPoint 97\" },\n \"swf\": { FAMILY_PRESENTATION: \"impress_flash_Export\" }\n}\n\nclass DocumentConverter:\n\n def __init__(self, port=DEFAULT_OPENOFFICE_PORT):\n localContext = uno.getComponentContext()\n resolver = localContext.ServiceManager.createInstanceWithContext(\"com.sun.star.bridge.UnoUrlResolver\", localContext)\n try:\n self.context = resolver.resolve(\"uno:socket,host=localhost,port=%s;urp;StarOffice.ComponentContext\" % port)\n except NoConnectException:\n raise Exception, \"failed to connect to OpenOffice.org on port %s\" % port\n self.desktop = self.context.ServiceManager.createInstanceWithContext(\"com.sun.star.frame.Desktop\", self.context)\n\n def convert(self, inputFile, outputFile):\n\n inputUrl = self._toFileUrl(inputFile)\n outputUrl = self._toFileUrl(outputFile)\n\n document = self.desktop.loadComponentFromURL(inputUrl, \"_blank\", 0, self._toProperties(Hidden=True))\n #document.setPropertyValue(\"DocumentTitle\", \"saf\" ) TODO: Check how this can be set and set doc update mode to FULL_UPDATE\n\n if self._detectFamily(document) == FAMILY_TEXT:\n indexes = document.getDocumentIndexes()\n for i in range(0, indexes.getCount()):\n index = indexes.getByIndex(i)\n index.update()\n\n try:\n document.refresh()\n except AttributeError:\n pass\n\n indexes = document.getDocumentIndexes()\n for i in range(0, indexes.getCount()):\n index = indexes.getByIndex(i)\n index.update()\n\n outputExt = self._getFileExt(outputFile)\n filterName = self._filterName(document, outputExt)\n\n try:\n document.storeToURL(outputUrl, self._toProperties(FilterName=filterName))\n finally:\n document.close(True)\n\n def _filterName(self, document, outputExt):\n family = self._detectFamily(document)\n try:\n filterByFamily = FILTER_MAP[outputExt]\n except KeyError:\n raise Exception, \"unknown output format: '%s'\" % outputExt\n try:\n return filterByFamily[family]\n except KeyError:\n raise Exception, \"unsupported conversion: from '%s' to '%s'\" % (family, outputExt)\n\n def _detectFamily(self, document):\n if document.supportsService(\"com.sun.star.text.GenericTextDocument\"):\n # NOTE: a GenericTextDocument is either a TextDocument, a WebDocument, or a GlobalDocument\n # but this further distinction doesn't seem to matter for conversions\n return FAMILY_TEXT\n if document.supportsService(\"com.sun.star.sheet.SpreadsheetDocument\"):\n return FAMILY_SPREADSHEET\n if document.supportsService(\"com.sun.star.presentation.PresentationDocument\"):\n return FAMILY_PRESENTATION\n if document.supportsService(\"com.sun.star.drawing.DrawingDocument\"):\n return FAMILY_DRAWING\n raise Exception, \"unknown document family: %s\" % document\n\n def _getFileExt(self, path):\n ext = splitext(path)[1]\n if ext is not None:\n return ext[1:].lower()\n\n def _toFileUrl(self, path):\n return uno.systemPathToFileUrl(abspath(path))\n\n def _toProperties(self, **args):\n props = []\n for key in args:\n prop = PropertyValue()\n prop.Name = key\n prop.Value = args[key]\n props.append(prop)\n return tuple(props)\n\nif __name__ == \"__main__\":\n from sys import argv, exit\n\n if len(argv) < 3:\n print \"USAGE: python %s <input-file> <output-file>\" % argv[0]\n exit(255)\n if not isfile(argv[1]):\n print \"no such input file: %s\" % argv[1]\n exit(1)\n\n try:\n converter = DocumentConverter() \n converter.convert(argv[1], argv[2])\n except Exception, exception:\n print \"ERROR!\" + str(exception)\n exit(1)\n\n", "Java\nI've used Apache POI in the past to parse Word Documents. It seemed to work pretty well. Then here are some libraries to write to RTF. \n.Net\nHere's an article about writing to a Word Document in .Net. I'm sure you could use the same library for reading. \nPython\nHere is an article for Python.\nRelated Question\nAlso, here is a related if not duplicate question.\n", "have a look at Docvert. You'll have to set it up for yourself because the demo only lets you upload open office documents, i believe.\n", "You can use AutoIt to automate opening the XML files in word and doing a save as RTF.\nI've used the user defined functions for Word to save RTF files as plain text for conversion and it works good. The syntax is very easy.\nhttp://www.autoitscript.com/autoit3/index.shtml\n", "From java, you could use Docmosis to do conversion and optional populating. It sits over openoffice to perform the format conversions. If you install openoffice and manually load and save a few example documents you'll get a feel for whether the format conversions are good enough for you. If so, you can use Docmosis to drive it from Java.\n" ]
[ 2, 0, 0, 0, 0 ]
[]
[]
[ ".net", "java", "python", "rtf", "xml" ]
stackoverflow_0002612915_.net_java_python_rtf_xml.txt
Q: Python module shared between multiple products I'm working on a python class that is being shared between two products. 90% of the functionality applies to both products. For the 10% that's different the code is littered with this kind of thing: #Start of file project = 'B' #Some line of code if project == 'A': import moduleA elif project == 'B': import moduleB #Many lines of code if project == 'A': print moduleA.doA(2) elif project == 'B': print moduleB.doB(2) This doesn't seem very elegant or very readable, has anyone encountered this sort of thing before? Are there better ways of doing it? A: No, as this is very poor design. If your module's behavior is influenced by the project in which it is used, then it should accept an object, function, or other callback for the project-specific behavior. My suggestion is to factor out the pieces that are shared and make them into a single module, and for anything that is project-specific, add a dependency on an object that needs to be passed in, and require that the object conform to some interface. Then, wrap your project-specific behaviors in an object that conforms to the required interface and pass it to the common, shared module. A: Your shared module should implement a base class with the functionality common to both using modules, then each using module will subclass that base class and add or tweak what's necessary. There are other good approaches (such as the suggestion in @Michael's answer, which is known as the Dependency Injection design patterns), but usually subclassing and overriding is the simplest way to "customize" functionality for different specific needs (it does lead to high and rigid coupling, but that's often quite acceptable as the cost of simplicity). A: Another possible approach, if neither of the two answers given so far are practical, is to define the interface at the import level. For instance: if project == 'A': from moduleA import doA as doproject elif project == 'B': from moduleB import doB as doproject # many lines of code doproject(2) This concept (although not this specific problem) is one of the things that "import X as Y" is really good for. You could also get cleverer with constructing imports based on the project name, making a dictionary keyed by project that had as its value the module to call, and that sort of thing. But I wouldn't go that direction unless I was really sure that refactoring so I could pass in the modules I need wouldn't work.
Python module shared between multiple products
I'm working on a python class that is being shared between two products. 90% of the functionality applies to both products. For the 10% that's different the code is littered with this kind of thing: #Start of file project = 'B' #Some line of code if project == 'A': import moduleA elif project == 'B': import moduleB #Many lines of code if project == 'A': print moduleA.doA(2) elif project == 'B': print moduleB.doB(2) This doesn't seem very elegant or very readable, has anyone encountered this sort of thing before? Are there better ways of doing it?
[ "No, as this is very poor design. If your module's behavior is influenced by the project in which it is used, then it should accept an object, function, or other callback for the project-specific behavior. My suggestion is to factor out the pieces that are shared and make them into a single module, and for anything that is project-specific, add a dependency on an object that needs to be passed in, and require that the object conform to some interface. Then, wrap your project-specific behaviors in an object that conforms to the required interface and pass it to the common, shared module.\n", "Your shared module should implement a base class with the functionality common to both using modules, then each using module will subclass that base class and add or tweak what's necessary. There are other good approaches (such as the suggestion in @Michael's answer, which is known as the Dependency Injection design patterns), but usually subclassing and overriding is the simplest way to \"customize\" functionality for different specific needs (it does lead to high and rigid coupling, but that's often quite acceptable as the cost of simplicity).\n", "Another possible approach, if neither of the two answers given so far are practical, is to define the interface at the import level. For instance:\nif project == 'A':\n from moduleA import doA as doproject\nelif project == 'B':\n from moduleB import doB as doproject\n\n# many lines of code\n\ndoproject(2)\n\nThis concept (although not this specific problem) is one of the things that \"import X as Y\" is really good for.\nYou could also get cleverer with constructing imports based on the project name, making a dictionary keyed by project that had as its value the module to call, and that sort of thing. But I wouldn't go that direction unless I was really sure that refactoring so I could pass in the modules I need wouldn't work.\n" ]
[ 3, 0, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0002823465_module_python.txt
Q: Python features Is there any article/paper on what features the Python language has to offer? Why should one go with Python instead of any other language? What are the strong and the weak points of Python? A: Why Python and Why Python so Choose Python (import this) A: Probably the prime reason I use Python is because it's very good at self-documenting. There are lots of other reasons too, but probably the best way to find out is to do something with it. Find a project and see what it takes to do it in Python. It may not be great Python code, but you'll learn more about how it suits you than from an essay. I know the first time I looked at Python, I didn't give it much chance (just looked like Matlab as far as I was concerned), but after using it for a couple of years, I have to say I have no regrets. A: Paul Prescod Why I Promote Python has many good points why python is a good choice. A: Why Python? Because all the cool kids are doing it. Disclaimer: I just noticed "popularity-contest" running on my machine so I investigated. Although quite useful for QA and planning, one can't actually derive any meaning from that graph which could at least as well be explained by the rise of Ubuntu installations and their Python based administrative tools. This link is for amusement purposes only, void in Idaho and Nebraska.
Python features
Is there any article/paper on what features the Python language has to offer? Why should one go with Python instead of any other language? What are the strong and the weak points of Python?
[ "Why Python\nand\nWhy Python\nso\nChoose Python (import this)\n", "Probably the prime reason I use Python is because it's very good at self-documenting. There are lots of other reasons too, but probably the best way to find out is to do something with it. Find a project and see what it takes to do it in Python. It may not be great Python code, but you'll learn more about how it suits you than from an essay. I know the first time I looked at Python, I didn't give it much chance (just looked like Matlab as far as I was concerned), but after using it for a couple of years, I have to say I have no regrets.\n", "Paul Prescod Why I Promote Python has many good points why python is a good choice.\n", "Why Python? Because all the cool kids are doing it.\nDisclaimer: I just noticed \"popularity-contest\" running on my machine so I investigated. Although quite useful for QA and planning, one can't actually derive any meaning from that graph which could at least as well be explained by the rise of Ubuntu installations and their Python based administrative tools. This link is for amusement purposes only, void in Idaho and Nebraska.\n" ]
[ 5, 3, 2, 1 ]
[]
[]
[ "language_comparisons", "language_features", "python" ]
stackoverflow_0002820705_language_comparisons_language_features_python.txt
Q: Python program to search for specific strings in hash values (coding help) Trying to write a code that searches hash values for specific string's (input by user) and returns the hash if searchquery is present in that line. Doing this to kind of just learn python a bit more, but it could be a real world application used by an HR department to search a .csv resume database for specific words in each resume. I'd like this program to look through a .csv file that has three entries per line (id#;applicant name;resume text) I set it up so that it creates a hash, then created a string for the resume text hash entry, and am trying to use the .find() function to return the entire hash for each instance. What i'd like is if the word "gpa" is used as a search query and it is found in s['resumetext'] for three applicants(rows in .csv file), it prints the id, name, and resume for every row that has it.(All three applicants) As it is right now, my program prints the first row in the .csv file(print resume['id'], resume['name'], resume['resumetext']) no matter what the searchquery is, whether it's in the resumetext or not. lastly, are there better ways to doing this, by searching word documents, pdf's and .txt files in a folder for specific words using python (i've just started reading about the re module and am wondering if this may be the route, rather than putting everything in a .csv file.) def find_details(id2find): resumes_f=open("resume_data.csv") for each_line in resumes_f: s={} (s['id'], s['name'], s['resumetext']) = each_line.split(";") resumetext = str(s['resumetext']) if resumetext.find(id2find): return(s) else: print "No data matches your search query. Please try again" searchquery = raw_input("please enter your search term") resume = find_details(searchquery) if resume: print resume['id'], resume['name'], resume['resumetext'] A: What @Justin Peel said. Also to be more pythonic I would say change if resumetext.find(id2find) != -1: to if id2find in resumetext: A few more changes: you might want to lower case the comparison and user input so it matches GPA, gpa, Gpa, etc. You can do this by doing searchquery = raw_input("please enter your search term").lower() and resumetext = s['resumetext'].lower(). You'll note I removed the explicit cast around s['resumetext'] as it's not needed. A: The line resumetext = str(s['resumetext']) is redundant, because s['resumetext'] is already a string (since it comes as one of the results from a .split call). So, you can merge this line and the next into if id2find in s['resumetext']: ... Your following else is misaligned -- with it placed like that, you'll print the message over and over again. You want to place it after the for loop (and the else isn't needed, though it would work), so I'd suggest: for each_line in resumes_f: s = dict(zip('id name resumetext'.split(), each_line.split(";")) if id2find in s['resumetext']: return(s) print "No data matches your search query. Please try again" I've also shown an alternative way to build dict s, although yours is fine too. A: One change that I recommend for your code is changing if resumetext.find(id2find): to if resumetext.find(id2find) != -1: because find() returns -1 if id2find wasn't in resumetext. Otherwise, it returns the index where id2find is first found in resumetext, which could be 0. As @Personman commented, this would give you the false positive because -1 is interpreted as True in Python. I think that problem has something to do with the fact that find_details() only returns the first entry for which the search string is found in resumetext. It might be good to make find_details() into a generator instead and then you could iterate over it and print the found records out one by one.
Python program to search for specific strings in hash values (coding help)
Trying to write a code that searches hash values for specific string's (input by user) and returns the hash if searchquery is present in that line. Doing this to kind of just learn python a bit more, but it could be a real world application used by an HR department to search a .csv resume database for specific words in each resume. I'd like this program to look through a .csv file that has three entries per line (id#;applicant name;resume text) I set it up so that it creates a hash, then created a string for the resume text hash entry, and am trying to use the .find() function to return the entire hash for each instance. What i'd like is if the word "gpa" is used as a search query and it is found in s['resumetext'] for three applicants(rows in .csv file), it prints the id, name, and resume for every row that has it.(All three applicants) As it is right now, my program prints the first row in the .csv file(print resume['id'], resume['name'], resume['resumetext']) no matter what the searchquery is, whether it's in the resumetext or not. lastly, are there better ways to doing this, by searching word documents, pdf's and .txt files in a folder for specific words using python (i've just started reading about the re module and am wondering if this may be the route, rather than putting everything in a .csv file.) def find_details(id2find): resumes_f=open("resume_data.csv") for each_line in resumes_f: s={} (s['id'], s['name'], s['resumetext']) = each_line.split(";") resumetext = str(s['resumetext']) if resumetext.find(id2find): return(s) else: print "No data matches your search query. Please try again" searchquery = raw_input("please enter your search term") resume = find_details(searchquery) if resume: print resume['id'], resume['name'], resume['resumetext']
[ "What @Justin Peel said. Also to be more pythonic I would say change\nif resumetext.find(id2find) != -1: to if id2find in resumetext:\nA few more changes: you might want to lower case the comparison and user input so it matches GPA, gpa, Gpa, etc. You can do this by doing searchquery = raw_input(\"please enter your search term\").lower() and resumetext = s['resumetext'].lower(). You'll note I removed the explicit cast around s['resumetext'] as it's not needed.\n", "The line\nresumetext = str(s['resumetext'])\n\nis redundant, because s['resumetext'] is already a string (since it comes as one of the results from a .split call). So, you can merge this line and the next into\nif id2find in s['resumetext']: ...\n\nYour following else is misaligned -- with it placed like that, you'll print the message over and over again. You want to place it after the for loop (and the else isn't needed, though it would work), so I'd suggest:\nfor each_line in resumes_f:\n s = dict(zip('id name resumetext'.split(), each_line.split(\";\"))\n if id2find in s['resumetext']:\n return(s)\nprint \"No data matches your search query. Please try again\"\n\nI've also shown an alternative way to build dict s, although yours is fine too.\n", "One change that I recommend for your code is changing \nif resumetext.find(id2find):\n\nto\nif resumetext.find(id2find) != -1:\n\nbecause find() returns -1 if id2find wasn't in resumetext. Otherwise, it returns the index where id2find is first found in resumetext, which could be 0. As @Personman commented, this would give you the false positive because -1 is interpreted as True in Python.\nI think that problem has something to do with the fact that find_details() only returns the first entry for which the search string is found in resumetext. It might be good to make find_details() into a generator instead and then you could iterate over it and print the found records out one by one.\n" ]
[ 1, 1, 0 ]
[]
[]
[ "full_text_search", "hash", "parsing", "python", "regex" ]
stackoverflow_0002824360_full_text_search_hash_parsing_python_regex.txt
Q: Handle iterable and non-iterable seamlessly Could you let me know how I can optimize the following code? def f(y, list_or_elem): if getattr(list_or_elem, '__iter__'): y = max(y, *list_or_elem) else: y = max(y, list_or_elem) A: The best optimization of all would be to avoid such silliness as taking "either a list or a single element" as an argument. But, if you insist, it's better to use a try/except to remove the anomaly ASAP and make what's sure to be an iterable: try: iter(list_or_elem) except TypeError: iterable = [list_or_elem] else: iterable = list_or_elem y = max(y, *iterable) A: if you are willing to have add flatten function in your code (theres a good one here) which can basically take a list of lists of lists of... and bring it down to a single list, you can do something like y = max(flatten([y, list_or_elem]))
Handle iterable and non-iterable seamlessly
Could you let me know how I can optimize the following code? def f(y, list_or_elem): if getattr(list_or_elem, '__iter__'): y = max(y, *list_or_elem) else: y = max(y, list_or_elem)
[ "The best optimization of all would be to avoid such silliness as taking \"either a list or a single element\" as an argument. But, if you insist, it's better to use a try/except to remove the anomaly ASAP and make what's sure to be an iterable:\ntry: iter(list_or_elem)\nexcept TypeError: iterable = [list_or_elem]\nelse: iterable = list_or_elem\ny = max(y, *iterable)\n\n", "if you are willing to have add flatten function in your code (theres a good one here) which can basically take a list of lists of lists of... and bring it down to a single list, you can do something like\ny = max(flatten([y, list_or_elem]))\n\n" ]
[ 1, 0 ]
[]
[]
[ "iterable", "python" ]
stackoverflow_0002824612_iterable_python.txt
Q: Sqlalchemy: Many to Many relationship error Dear everyone, I am following the Many to many relationship described on http://www.sqlalchemy.org/docs/mappers.html#many-to-many #This is actually a VIEW tb_mapping_uGroups_uProducts = Table( 'mapping_uGroups_uProducts', metadata, Column('upID', Integer, ForeignKey('uProductsInfo.upID')), Column('ugID', Integer, ForeignKey('uGroupsInfo.ugID')) ) tb_uProducts = Table( 'uProductsInfo', metadata, Column('upID', Integer, primary_key=True) ) mapper( UnifiedProduct, tb_uProducts) tb_uGroupsInfo = Table( 'uGroupsInfo', metadata, Column('ugID', Integer, primary_key=True) ) mapper( UnifiedGroup, tb_uGroupsInfo, properties={ 'unifiedProducts': relation(UnifiedProduct, secondary=tb_mapping_uGroups_uProducts, backref="unifiedGroups") }) where the relationship between uProduct and uGroup are N:M. When I run the following sess.query(UnifiedProduct).join(UnifiedGroup).distinct()[:10] I am getting the error: sqlalchemy.exc.ArgumentError: Can't find any foreign key relationships between 'uProductsInfo' and 'uGroupsInfo' What am I doing wrong? EDIT: I am on MyISAM which doesn't support forigen keys A: Existence of foreign key definitions in SQLAlchemy schema is enough, they are not mandatory in actual table. There is no direct foreign relation between your models, so SQLAlchemy fails to find them. Specify the relation to join on explicitly: sess.query(UnifiedProduct).join(UnifiedProduct.unifiedGroups).distinct()[:10]
Sqlalchemy: Many to Many relationship error
Dear everyone, I am following the Many to many relationship described on http://www.sqlalchemy.org/docs/mappers.html#many-to-many #This is actually a VIEW tb_mapping_uGroups_uProducts = Table( 'mapping_uGroups_uProducts', metadata, Column('upID', Integer, ForeignKey('uProductsInfo.upID')), Column('ugID', Integer, ForeignKey('uGroupsInfo.ugID')) ) tb_uProducts = Table( 'uProductsInfo', metadata, Column('upID', Integer, primary_key=True) ) mapper( UnifiedProduct, tb_uProducts) tb_uGroupsInfo = Table( 'uGroupsInfo', metadata, Column('ugID', Integer, primary_key=True) ) mapper( UnifiedGroup, tb_uGroupsInfo, properties={ 'unifiedProducts': relation(UnifiedProduct, secondary=tb_mapping_uGroups_uProducts, backref="unifiedGroups") }) where the relationship between uProduct and uGroup are N:M. When I run the following sess.query(UnifiedProduct).join(UnifiedGroup).distinct()[:10] I am getting the error: sqlalchemy.exc.ArgumentError: Can't find any foreign key relationships between 'uProductsInfo' and 'uGroupsInfo' What am I doing wrong? EDIT: I am on MyISAM which doesn't support forigen keys
[ "Existence of foreign key definitions in SQLAlchemy schema is enough, they are not mandatory in actual table. There is no direct foreign relation between your models, so SQLAlchemy fails to find them. Specify the relation to join on explicitly:\nsess.query(UnifiedProduct).join(UnifiedProduct.unifiedGroups).distinct()[:10]\n\n" ]
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002824322_python_sqlalchemy.txt
Q: catch output from linux telnet to a python script My problem is that i want to do something like this in linux console telnet 192.168.255.28 > process.py i.e i would like to do some transformation with console telnet output using python script. I'm see Popen in python for this case, but i can't understand how can i get input from telnet if it do not stop all time.. Pleas any ideas. A: Have you considered telnetlib? It seems like pretty much exactly what you're looking for? A: If you can adapt your solution, telnetlib seems like the right way to do it -- +1 to xitrium. That said, though, if you're dead set on piping the output of telnet into your Python script, it'll be coming in on standard in. That means you can do something like this: try: while True: line = raw_input() do_stuff(line) except EOFError: pass # the telnet process finished; there's no more input which will grab the output from telnet, one line at a time. If you want finer control, you can get the input using sys.stdin.read(). Important: In your question, you said (for example) telnet 192.168.255.28 > process.py. This is wrong; instead of piping the output from telnet into your script, it will save the output to file, overwriting your script. What you want is a pipe: telnet 192.168.255.28 | process.py. A: As xitrium mentioned, it would be better if you used telnetlib. You can dispense with the whole mess of shell redirection etc. If you do something like telnet foo | process.py, you can read your programs stdin (sys.stdin) to get the output of the telnet program. When you're happy, you can exit and terminate the pipeline. subprocess.Popen would be used if you're trying to open the telnet program as a subprocess of the interpreter. I'm not sure you wanted that. In any case, telnetlib is the right way to go it seems. If you simply want an output text processor, consider perl. It's strengths lean in that direction.
catch output from linux telnet to a python script
My problem is that i want to do something like this in linux console telnet 192.168.255.28 > process.py i.e i would like to do some transformation with console telnet output using python script. I'm see Popen in python for this case, but i can't understand how can i get input from telnet if it do not stop all time.. Pleas any ideas.
[ "Have you considered telnetlib? It seems like pretty much exactly what you're looking for?\n", "If you can adapt your solution, telnetlib seems like the right way to do it -- +1 to xitrium.\nThat said, though, if you're dead set on piping the output of telnet into your Python script, it'll be coming in on standard in. That means you can do something like this:\ntry:\n while True:\n line = raw_input()\n do_stuff(line)\nexcept EOFError:\n pass # the telnet process finished; there's no more input\n\nwhich will grab the output from telnet, one line at a time. If you want finer control, you can get the input using sys.stdin.read().\nImportant: In your question, you said (for example) telnet 192.168.255.28 > process.py. This is wrong; instead of piping the output from telnet into your script, it will save the output to file, overwriting your script. What you want is a pipe: telnet 192.168.255.28 | process.py.\n", "As xitrium mentioned, it would be better if you used telnetlib. You can dispense with the whole mess of shell redirection etc.\nIf you do something like telnet foo | process.py, you can read your programs stdin (sys.stdin) to get the output of the telnet program. When you're happy, you can exit and terminate the pipeline. subprocess.Popen would be used if you're trying to open the telnet program as a subprocess of the interpreter. I'm not sure you wanted that. \nIn any case, telnetlib is the right way to go it seems. If you simply want an output text processor, consider perl. It's strengths lean in that direction.\n" ]
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002825100_python.txt
Q: How can I add dynamic field in the model in django? I'm using django to create a application download site. I try to write a model, that the admin can add the different download content dynamically in the admin page. For example I have a software named foobar, it have 3 different version: 1.1, 1.2, 1.3. I would like the user can admin the model by using an add button to add the download link with a download version. But I don't know how to do this in django. A: Set up your models to have a main model and ancillary models that have foreign keys to the main model: class DownloadItem(models.Model): name = models.CharField( etc etc) ... other attributes here ... class DownloadItemFile(models.Model): parent = models.ForeignKey('DownloadItem', related_name="versions") version = models.CharField( etc etc) file = models.FileField(upload='path/to/uploaddir/') then, when you have an instance of your DownloadItem model, you can get hold of your various file versions with: mydownloaditem.versions.all() To be able to add files via the Admin, you will need to use an inline. In your admin.py for the app in question, you'll need to add something like: class DownloadItemFileInline(admin.TabularInline): model = DownloadItemFile class DownloadItemAdminOptions(admin.ModelAdmin): inlines = [ DownloadItemFileInline, ] ...other admin options here... admin.site.register(DownloadItem, DownloadItem AdminOptions)
How can I add dynamic field in the model in django?
I'm using django to create a application download site. I try to write a model, that the admin can add the different download content dynamically in the admin page. For example I have a software named foobar, it have 3 different version: 1.1, 1.2, 1.3. I would like the user can admin the model by using an add button to add the download link with a download version. But I don't know how to do this in django.
[ "Set up your models to have a main model and ancillary models that have foreign keys to the main model:\nclass DownloadItem(models.Model):\n\n name = models.CharField( etc etc)\n ... other attributes here ...\n\n\nclass DownloadItemFile(models.Model):\n parent = models.ForeignKey('DownloadItem', related_name=\"versions\")\n version = models.CharField( etc etc)\n file = models.FileField(upload='path/to/uploaddir/')\n\nthen, when you have an instance of your DownloadItem model, you can get hold of your various file versions with:\nmydownloaditem.versions.all()\n\nTo be able to add files via the Admin, you will need to use an inline. In your admin.py for the app in question, you'll need to add something like:\nclass DownloadItemFileInline(admin.TabularInline):\n model = DownloadItemFile\n\nclass DownloadItemAdminOptions(admin.ModelAdmin):\n inlines = [ DownloadItemFileInline, ]\n ...other admin options here... \n\nadmin.site.register(DownloadItem, DownloadItem AdminOptions) \n\n" ]
[ 1 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0002825435_database_django_python.txt
Q: Any experience with the Deliverance system? My new boss went to a speech where Deliverance, a kind of proxy allowing to add skin to any html output on the fly, was presented. He decided to use it right after that, no matter how young it is. More here : http://www.openplans.org/projects/deliverance/introduction In theory, the system sounds great when you want a newbie to tweak your plone theme without having to teach him all the complex mechanisms behind the zope products. And apply the same theme on a Drupal web site in one row. But I don't believe in theory, and would like to know if anybody tried this out in the real world :-) A: Having used Plone professionally for the last 4 years or so, and Deliverance on 4 commercial sites, I would advise all new front end developers (and old hands alike) to use Deliverance to theme Plone sites. It is much easier to learn (a couple of weeks Vs couple of months) and potentially much more powerful than the old, confused, methods - few of which you will still need (and even then at a much later point in the life of the site). Not only that, but it uses XPath and CSS selectors and can be used on non-Plone sites, so the time invested is easily transferable. A: Note, plone.org uses xdv, a version of deliverance that compiles down to xslt. The simplest way to try it is with http://pypi.python.org/pypi/collective.xdv though plone.org runs the xslt in a (patched) Nginx. A: The plone website itself (http://plone.org) is themed using deliverance. So far as I know, it is the first large-scale production plone site using deliverance. A: I will start answering this question here while we perform tests but I'd love to have feedback from other users. Install We have spent a small afternoon from tuto to "how to" to finally install and run the thing on a virtual machine. This one is ok : http://www.openplans.org/projects/deliverance/getting-started There are setuptools packages but this does not works out of the box (and certainly not without compiling anything). We had to install : setuptools >= 0.6c5 (tested with 0.6c9 from http://pypi.python.org/pypi/setuptools/). of course, compilation implies installing gcc, linux-header et lib6-dev libxslt in dev (we used libxslt1-dev) linking with zl so zlib (we used zlib1g-dev) you'd better install Pastescript BEFORE starting the Deliverance install installing python-nose is not mandatory but it helps to check if everything went fine We did not manage to make it works with python-virtualenv to we definitly messed up the debian system but it seems to run ok. Hope it can help.
Any experience with the Deliverance system?
My new boss went to a speech where Deliverance, a kind of proxy allowing to add skin to any html output on the fly, was presented. He decided to use it right after that, no matter how young it is. More here : http://www.openplans.org/projects/deliverance/introduction In theory, the system sounds great when you want a newbie to tweak your plone theme without having to teach him all the complex mechanisms behind the zope products. And apply the same theme on a Drupal web site in one row. But I don't believe in theory, and would like to know if anybody tried this out in the real world :-)
[ "Having used Plone professionally for the last 4 years or so, and Deliverance on 4 commercial sites, I would advise all new front end developers (and old hands alike) to use Deliverance to theme Plone sites.\nIt is much easier to learn (a couple of weeks Vs couple of months) and potentially much more powerful than the old, confused, methods - few of which you will still need (and even then at a much later point in the life of the site).\nNot only that, but it uses XPath and CSS selectors and can be used on non-Plone sites, so the time invested is easily transferable.\n", "Note, plone.org uses xdv, a version of deliverance that compiles down to xslt. The simplest way to try it is with http://pypi.python.org/pypi/collective.xdv though plone.org runs the xslt in a (patched) Nginx.\n", "The plone website itself (http://plone.org) is themed using deliverance. So far as I know, it is the first large-scale production plone site using deliverance. \n", "I will start answering this question here while we perform tests but I'd love to have feedback from other users.\nInstall\nWe have spent a small afternoon from tuto to \"how to\" to finally install and run the thing on a virtual machine.\nThis one is ok : http://www.openplans.org/projects/deliverance/getting-started\nThere are setuptools packages but this does not works out of the box (and certainly not without compiling anything). We had to install :\n\nsetuptools >= 0.6c5 (tested with 0.6c9 from http://pypi.python.org/pypi/setuptools/). \nof course, compilation implies installing gcc, linux-header et lib6-dev\nlibxslt in dev (we used libxslt1-dev)\nlinking with zl so zlib (we used zlib1g-dev)\nyou'd better install Pastescript BEFORE starting the Deliverance install\ninstalling python-nose is not mandatory but it helps to check if everything went fine\n\nWe did not manage to make it works with python-virtualenv to we definitly messed up the debian system but it seems to run ok.\nHope it can help.\n" ]
[ 5, 2, 1, 0 ]
[]
[]
[ "deliverance", "html", "python" ]
stackoverflow_0000204570_deliverance_html_python.txt
Q: deploying a war to tomcat using python I'm trying to deploy a war to a Apache Tomcat server (Build 6.0.24) using python (2.4.2) as part of a build process. I'm using the following code import urllib2 import base64 war_file_contents = open('war_file.war','rb').read() username='some_user' password='some_pwd' base64string = base64.encodestring('%s:%s' % (username, password))[:-1] authheader = "Basic %s" % base64string opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request('http://localhost:8080/manager/deploy?path=war_file', data=war_file_contents) request.add_header('Content-Type', 'application/octet-stream') request.add_header("Authorization", authheader) request.get_method = lambda: 'PUT' url = opener.open(request) the url.code is 200, and the url.msg is "OK". However the web archive doesn't appear on the manager list applications page. Thanks. A: Okay, figured it out. The urllib2.Request line needs to have a slash in front of the path so:- request = urllib2.Request('http://localhost:8080/manager/deploy?path=/war_file', data=war_file_contents) All then works fine.
deploying a war to tomcat using python
I'm trying to deploy a war to a Apache Tomcat server (Build 6.0.24) using python (2.4.2) as part of a build process. I'm using the following code import urllib2 import base64 war_file_contents = open('war_file.war','rb').read() username='some_user' password='some_pwd' base64string = base64.encodestring('%s:%s' % (username, password))[:-1] authheader = "Basic %s" % base64string opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request('http://localhost:8080/manager/deploy?path=war_file', data=war_file_contents) request.add_header('Content-Type', 'application/octet-stream') request.add_header("Authorization", authheader) request.get_method = lambda: 'PUT' url = opener.open(request) the url.code is 200, and the url.msg is "OK". However the web archive doesn't appear on the manager list applications page. Thanks.
[ "Okay, figured it out.\nThe urllib2.Request line needs to have a slash in front of the path so:-\nrequest = urllib2.Request('http://localhost:8080/manager/deploy?path=/war_file', data=war_file_contents)\n\nAll then works fine.\n" ]
[ 2 ]
[]
[]
[ "deployment", "python", "tomcat", "urllib2" ]
stackoverflow_0002825350_deployment_python_tomcat_urllib2.txt
Q: Spotting similarities and patterns within a string - Python this is the use case I'm trying to figure this out for. I have a list of spam subscriptions to a service and they are killing conversion rate and other usability studies. The emails inserted look like the following: rogerep_dyeepvu@hotmail.com rogeram_ingramameb@hotmail.com rogerew_jonesewct@hotmail.com roger[...]_surname[...]@hotmail.com What would be your suggestions on spotting these entries by using an automated script? It feels a little more complicated than it actually looks. Help would be very much appreciated! A: I don't think you can easily check for this. It's not likely to be a simple string matching problem that you can throw a regular expression at because I would guess that your use of the name 'Roger' was just an example, and that any number of names can appear in that position. You could also run one of the regular expressions supplied by the other posters, parameterising it with every permutation of obvious first name and last name. This will probably take somewhere between "too long" and "forever", and will flag up plenty of false positives. Another approach, which works with the pattern you posted above, would be to take the last 4 letters of the username, and compare them against something. Spotting characters that are random as opposed to arranged sensibly (given a specific language) can be done by training a Markov Chain on legitimate text which can then allow you to calculate the probability of a given 4 letters appearing in that order in that language. For random letters, this probability will typically come in far lower than for a legitimate name (although if there are special characters or digits in there, all bets are off). Another way might be to use a Bayesian filter (eg. something like Reverend in Python, though there are others) trained on the last 4 letters of legitimate email addresses. This would probably spot 95% of the ones which were just random, providing you made the data usable. eg. Submitting not just the 4 letters but each of the 2-letter and 3-letter substrings inside it, to capture the context of each letter. I don't think this would work as well as the Markov-style method though. Whatever check you do, you can cut false positives by only submitting certain email addresses for it (eg. only those at webmail addresses, which contain an underscore, with at least 3 characters before the underscore and 5 characters after it.) But ultimately, you can never know whether it's a spam address or a real one for sure until it gets used for one purpose or the other. So if possible I'd suggest giving up on trying to analyse the content and fix the problem somewhere else. In what way are they killing conversion rate? If you're counting these dummy accounts in some sort of metric, you'd be best off adding a verification stage first and only caring about metrics for accounts that pass verification. Some people really do have addresses like rogerep_dyeepvu@hotmail.com, after all. A: I don't think you can do more than flag it as a potential problem, by checking for: ^roger([a-z]{2})_([a-z]+)@hotmail.com using regular expressions, if that's the pattern that the spammer is using repeatedly. Looks like they're using 2 lower-case alphabetic characters after roger, so I've built that in. Not sure how you'd go about matching what dictionary of surnames they're using, so matching the last part (which appears to be surname then 4 lower-case alphabetic characters) might be hard, though you could perhaps do: ^roger([a-z]{2})_([a-z]{5,})@hotmail.com which assumes that all their surnames at least have one character in. A: Sounds like a job for regular expressions: if re.match("^roger[a-z]+_[a-z]+@hotmail.com$", email_address): # might be your spammer (If you've never used regular expressions, here's a quick rundown of what that means: ^ matches the beginning of the string and $ matches the end, so we're requiring that everything between those symbols is a pattern describing the entire string. [a-z] matches any lower-case letter, and + means "one or more times", so [a-z]+ matches one or more lower-case letters. Putting it all together, our regex matches if the string can be described as "the beginning of the string, followed by the letters roger, followed one or more lower-case letters, followed by an underscore, followed by one or more lower-case letters, followed by @hotmail.com, followed by the end of the string." If the regex matches, the email address fits the pattern you described in your question.) Of course, if he catches on and changes up his pattern (for example, by switching first names), this method will fail and you'll have to fall back on more traditional spam-prevention techniques like employing a CAPTCHA.
Spotting similarities and patterns within a string - Python
this is the use case I'm trying to figure this out for. I have a list of spam subscriptions to a service and they are killing conversion rate and other usability studies. The emails inserted look like the following: rogerep_dyeepvu@hotmail.com rogeram_ingramameb@hotmail.com rogerew_jonesewct@hotmail.com roger[...]_surname[...]@hotmail.com What would be your suggestions on spotting these entries by using an automated script? It feels a little more complicated than it actually looks. Help would be very much appreciated!
[ "I don't think you can easily check for this. It's not likely to be a simple string matching problem that you can throw a regular expression at because I would guess that your use of the name 'Roger' was just an example, and that any number of names can appear in that position. You could also run one of the regular expressions supplied by the other posters, parameterising it with every permutation of obvious first name and last name. This will probably take somewhere between \"too long\" and \"forever\", and will flag up plenty of false positives.\nAnother approach, which works with the pattern you posted above, would be to take the last 4 letters of the username, and compare them against something. Spotting characters that are random as opposed to arranged sensibly (given a specific language) can be done by training a Markov Chain on legitimate text which can then allow you to calculate the probability of a given 4 letters appearing in that order in that language. For random letters, this probability will typically come in far lower than for a legitimate name (although if there are special characters or digits in there, all bets are off).\nAnother way might be to use a Bayesian filter (eg. something like Reverend in Python, though there are others) trained on the last 4 letters of legitimate email addresses. This would probably spot 95% of the ones which were just random, providing you made the data usable. eg. Submitting not just the 4 letters but each of the 2-letter and 3-letter substrings inside it, to capture the context of each letter. I don't think this would work as well as the Markov-style method though.\nWhatever check you do, you can cut false positives by only submitting certain email addresses for it (eg. only those at webmail addresses, which contain an underscore, with at least 3 characters before the underscore and 5 characters after it.)\nBut ultimately, you can never know whether it's a spam address or a real one for sure until it gets used for one purpose or the other. So if possible I'd suggest giving up on trying to analyse the content and fix the problem somewhere else. In what way are they killing conversion rate? If you're counting these dummy accounts in some sort of metric, you'd be best off adding a verification stage first and only caring about metrics for accounts that pass verification. Some people really do have addresses like rogerep_dyeepvu@hotmail.com, after all.\n", "I don't think you can do more than flag it as a potential problem, by checking for:\n^roger([a-z]{2})_([a-z]+)@hotmail.com\nusing regular expressions, if that's the pattern that the spammer is using repeatedly.\nLooks like they're using 2 lower-case alphabetic characters after roger, so I've built that in. Not sure how you'd go about matching what dictionary of surnames they're using, so matching the last part (which appears to be surname then 4 lower-case alphabetic characters) might be hard, though you could perhaps do:\n^roger([a-z]{2})_([a-z]{5,})@hotmail.com\nwhich assumes that all their surnames at least have one character in.\n", "Sounds like a job for regular expressions:\nif re.match(\"^roger[a-z]+_[a-z]+@hotmail.com$\", email_address):\n # might be your spammer\n\n(If you've never used regular expressions, here's a quick rundown of what that means: ^ matches the beginning of the string and $ matches the end, so we're requiring that everything between those symbols is a pattern describing the entire string. [a-z] matches any lower-case letter, and + means \"one or more times\", so [a-z]+ matches one or more lower-case letters. Putting it all together, our regex matches if the string can be described as \"the beginning of the string, followed by the letters roger, followed one or more lower-case letters, followed by an underscore, followed by one or more lower-case letters, followed by @hotmail.com, followed by the end of the string.\" If the regex matches, the email address fits the pattern you described in your question.)\nOf course, if he catches on and changes up his pattern (for example, by switching first names), this method will fail and you'll have to fall back on more traditional spam-prevention techniques like employing a CAPTCHA.\n" ]
[ 3, 1, 1 ]
[]
[]
[ "pattern_matching", "python", "spam_prevention", "string" ]
stackoverflow_0002825520_pattern_matching_python_spam_prevention_string.txt
Q: python check value not in unicode list I have a list and a value and want to check if the value is not in the list. list = [u'first record', u'second record'] value = 'first record' if value not in list: do something however this is not working and I think it has something to do with the list values having a u at the start, how can I fix this? And before someone suggests the list is returned from Django queryset so I can't just take the u out of the code :) Thanks A: unicode(value) transforms your 'first record' into u'first record'. That might fix your issues. However, depending on the contents this might fail and you'll have to use the .encode('charset') function strings have. PS: Your example is bad as those strings are equal in unicode and non-unicode and thus your example works fine. A: I can't see why it would not work: s1 = 'hello' s2 = u'hello' s1 == s2 # True
python check value not in unicode list
I have a list and a value and want to check if the value is not in the list. list = [u'first record', u'second record'] value = 'first record' if value not in list: do something however this is not working and I think it has something to do with the list values having a u at the start, how can I fix this? And before someone suggests the list is returned from Django queryset so I can't just take the u out of the code :) Thanks
[ "unicode(value) transforms your 'first record' into u'first record'. That might fix your issues. However, depending on the contents this might fail and you'll have to use the .encode('charset') function strings have.\nPS: Your example is bad as those strings are equal in unicode and non-unicode and thus your example works fine.\n", "I can't see why it would not work:\ns1 = 'hello'\ns2 = u'hello'\ns1 == s2 # True\n\n" ]
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002825884_python.txt
Q: Django + Apache wsgi = paths problem I have this view which generates interface language options menu def lang_menu(request,language): lang_choices = [] import os.path for lang in settings.LANGUAGES: if os.path.isfile("gui/%s.py" % lang) or os.path.isfile("gui/%s.pyc" % lang): langimport = "from gui.%s import menu" % lang try: exec(langimport) except ImportError: lang_choices.append({'error':'invalid language file'}) else: lang_choices.append(menu) else: lang_choices.append({'error':'lang file not found'}) t = loader.get_template('gui/blocks/lang_menu_options.html') data = '' for lang in lang_choices: if not 'error' in lang: data = "%s\n%s" % (data,t.render(Context(lang))) if not data: data = "Error! No languages configured or incorrect language files!" return Context({'content':data}) When I'am using development server (python manage.py runserver ...) it works fine. But when I ported my app to apache wsgi server I've got error "No languages configured or incorrect language files!" Here is my Apache config <VirtualHost *:9999> WSGIScriptAlias / "/usr/local/etc/django/terminal/django.wsgi" <Directory "/usr/local/etc/django/terminal"> Options +ExecCGI Allow From All </Directory> Alias /media/ "/usr/local/lib/python2.5/site-packages/django/contrib/admin/media/" <Location /media/> SetHandler None </Location> <Directory "/usr/local/lib/python2.5/site-packages/django/contrib/admin/media/> Allow from all </Directory> Alias /static/ "/usr/local/etc/django/terminal/media/" <Location /static/> SetHandler None </Location> ServerName ******* ServerAlias ******* ErrorLog /var/log/django.error.log TransferLog /var/log/django.access.log </VirtualHost> django.wsgi: import os, sys sys.path.append('/usr/local/etc/django') sys.path.append('/usr/local/etc/django/terminal') os.environ['DJANGO_SETTINGS_MODULE'] = 'terminal.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() It's look like as problem with path configuration but I'm stuck here ... A: Does this give you the right path if you call it in lang_menu? os.path.abspath(os.path.dirname(__file__)) If this indeed points to the directory your view module lives in, you can build from there to create an absolute path, e.g.: here = lambda *x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x) if os.path.isfile(here('gui', '%s.py' % lang)): ... A: It's hard to see what's going on, because although you are storing useful errors in your loop you are then overwriting them all with a generic error at the end. It would be more helpful to actually list the errors encountered. I would also question why you're managing language files manually, instead of using the built-in internationalization/localization handling. A: The problem may be in the os.path.isfile("gui/%s.py" % lang) line. You are using a relative path here. Use an absolute path instead and you should be fine. Some other pieces of advice: Don't use exec to import files. Use __import__ instead Don't look for files to decide over a configuration! it's slow and unreliable. Store the data in a database, for example.
Django + Apache wsgi = paths problem
I have this view which generates interface language options menu def lang_menu(request,language): lang_choices = [] import os.path for lang in settings.LANGUAGES: if os.path.isfile("gui/%s.py" % lang) or os.path.isfile("gui/%s.pyc" % lang): langimport = "from gui.%s import menu" % lang try: exec(langimport) except ImportError: lang_choices.append({'error':'invalid language file'}) else: lang_choices.append(menu) else: lang_choices.append({'error':'lang file not found'}) t = loader.get_template('gui/blocks/lang_menu_options.html') data = '' for lang in lang_choices: if not 'error' in lang: data = "%s\n%s" % (data,t.render(Context(lang))) if not data: data = "Error! No languages configured or incorrect language files!" return Context({'content':data}) When I'am using development server (python manage.py runserver ...) it works fine. But when I ported my app to apache wsgi server I've got error "No languages configured or incorrect language files!" Here is my Apache config <VirtualHost *:9999> WSGIScriptAlias / "/usr/local/etc/django/terminal/django.wsgi" <Directory "/usr/local/etc/django/terminal"> Options +ExecCGI Allow From All </Directory> Alias /media/ "/usr/local/lib/python2.5/site-packages/django/contrib/admin/media/" <Location /media/> SetHandler None </Location> <Directory "/usr/local/lib/python2.5/site-packages/django/contrib/admin/media/> Allow from all </Directory> Alias /static/ "/usr/local/etc/django/terminal/media/" <Location /static/> SetHandler None </Location> ServerName ******* ServerAlias ******* ErrorLog /var/log/django.error.log TransferLog /var/log/django.access.log </VirtualHost> django.wsgi: import os, sys sys.path.append('/usr/local/etc/django') sys.path.append('/usr/local/etc/django/terminal') os.environ['DJANGO_SETTINGS_MODULE'] = 'terminal.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() It's look like as problem with path configuration but I'm stuck here ...
[ "Does this give you the right path if you call it in lang_menu?\nos.path.abspath(os.path.dirname(__file__))\n\nIf this indeed points to the directory your view module lives in, you can build from there to create an absolute path, e.g.:\nhere = lambda *x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)\nif os.path.isfile(here('gui', '%s.py' % lang)):\n ...\n\n", "It's hard to see what's going on, because although you are storing useful errors in your loop you are then overwriting them all with a generic error at the end. It would be more helpful to actually list the errors encountered.\nI would also question why you're managing language files manually, instead of using the built-in internationalization/localization handling.\n", "The problem may be in the os.path.isfile(\"gui/%s.py\" % lang) line. You are using a relative path here. Use an absolute path instead and you should be fine.\nSome other pieces of advice:\n\nDon't use exec to import files. Use __import__ instead\nDon't look for files to decide over a configuration! it's slow and unreliable. Store the data in a database, for example.\n\n" ]
[ 2, 1, 1 ]
[]
[]
[ "django", "path", "python", "wsgi" ]
stackoverflow_0002825678_django_path_python_wsgi.txt
Q: Is there any graphics library in a higher level than OpenGL I am looking for a graphics library for 3D reconstruction research to develop my specific viewer based on some library. OpenGL seems in a low level and I have to remake the wheel everywhere. And I also tried VTK(visualization toolkit). However, it seems too abstract that I need to master many conceptions before I start. Is there any other graphics library? I prefer to program in python. So I would like the library has a python wrapper. I think something like O3D would be better. But O3D is for javascript and it seems that Google already stops the development. A: Panda3D seems to be a nice 3D graphics library designed to be used in Python, although it's mostly game oriented. I've browsed the manuals a few times and it's very polished and of a high quality, it has even been used in some big studio's games (like Disney's Pirates of the Caribbean online, if I remember well). A: Have you tried Pyglet with PyOpenGL? The two goes very well together. Wheaties' suggest is quite good as well, although PyOgre also has a steep learning curve, as it is indeed higher-level. On another thought, there is also PyGame, which is a Python wrapper of SDL. I personally prefer PyOpenGL, and you can use WxPython or PyQT to create your rendering context. Also, there is PyProcessing, which is still in early stages, but very, very nifty. A: You could try mlab / Mayavi (a wrapper for VTK). There's some examples here: http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html
Is there any graphics library in a higher level than OpenGL
I am looking for a graphics library for 3D reconstruction research to develop my specific viewer based on some library. OpenGL seems in a low level and I have to remake the wheel everywhere. And I also tried VTK(visualization toolkit). However, it seems too abstract that I need to master many conceptions before I start. Is there any other graphics library? I prefer to program in python. So I would like the library has a python wrapper. I think something like O3D would be better. But O3D is for javascript and it seems that Google already stops the development.
[ "Panda3D seems to be a nice 3D graphics library designed to be used in Python, although it's mostly game oriented. I've browsed the manuals a few times and it's very polished and of a high quality, it has even been used in some big studio's games (like Disney's Pirates of the Caribbean online, if I remember well).\n", "Have you tried Pyglet with PyOpenGL? The two goes very well together. Wheaties' suggest is quite good as well, although PyOgre also has a steep learning curve, as it is indeed higher-level. On another thought, there is also PyGame, which is a Python wrapper of SDL.\nI personally prefer PyOpenGL, and you can use WxPython or PyQT to create your rendering context.\nAlso, there is PyProcessing, which is still in early stages, but very, very nifty.\n", "You could try mlab / Mayavi (a wrapper for VTK). There's some examples here: http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html\n" ]
[ 2, 1, 0 ]
[ "I have no personal experience with this, but I have heard some decent things about Pyglet\n", "I used openGL with C++ a few years back - found it quite low level. I also have used Java3D which seemed to be a bit higher level. If you are not stuck on using python - try Java3D - very simple to get up and running.\n" ]
[ -1, -1 ]
[ "graphics", "opengl", "python" ]
stackoverflow_0002823907_graphics_opengl_python.txt
Q: Simple XML over http web service I have a simple html service, developed in django. You enter your name - it posts this, and returns a value (male/female). I need to ofer this as a web service. I have no idea where to start. I want to accept a xml request, and provide an xml response - thats it. Can anyone give ma any pointers - Googling it is difficult when you dont know what your searching for. A: You probably want Piston, which is framework for exposing Django apps as web services. A: See the Generating non-HTML content in the django book for instructions. Basically, it's as simple as this: def get_data(request, xml_data): data = parse_xml_data(xml_data) return_data = create_xml_blob(data) return HttpResponse(return_data, mimetype='application/xml') Edit: You can send a post with xml_data set to the XML string, or you can send an XML request. Here's some code for sending XML data to a web service, adapted from this site: xml_data = """<?xml version="1.0" encoding="UTF-8"?> <root>my data here</root> """ #construct and send the header webservice = httplib.HTTP("example.com") webservice.putrequest("POST", "/rcx-ws/rcx") webservice.putheader("Host", "example.com") webservice.putheader("User-Agent", "Python post") webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"") webservice.putheader("Content-length", "%d" % len(xml_data)) webservice.endheaders() webservice.send(xml_data) From django, you'd use request.raw_post_data to get at the XML directly.
Simple XML over http web service
I have a simple html service, developed in django. You enter your name - it posts this, and returns a value (male/female). I need to ofer this as a web service. I have no idea where to start. I want to accept a xml request, and provide an xml response - thats it. Can anyone give ma any pointers - Googling it is difficult when you dont know what your searching for.
[ "You probably want Piston, which is framework for exposing Django apps as web services.\n", "See the Generating non-HTML content in the django book for instructions.\nBasically, it's as simple as this:\ndef get_data(request, xml_data):\n data = parse_xml_data(xml_data)\n return_data = create_xml_blob(data)\n return HttpResponse(return_data, mimetype='application/xml')\n\nEdit:\nYou can send a post with xml_data set to the XML string, or you can send an XML request.\nHere's some code for sending XML data to a web service, adapted from this site:\nxml_data = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>my data here</root>\n\"\"\"\n\n#construct and send the header\n\nwebservice = httplib.HTTP(\"example.com\")\nwebservice.putrequest(\"POST\", \"/rcx-ws/rcx\")\nwebservice.putheader(\"Host\", \"example.com\")\nwebservice.putheader(\"User-Agent\", \"Python post\")\nwebservice.putheader(\"Content-type\", \"text/xml; charset=\\\"UTF-8\\\"\")\nwebservice.putheader(\"Content-length\", \"%d\" % len(xml_data))\nwebservice.endheaders()\nwebservice.send(xml_data)\n\nFrom django, you'd use request.raw_post_data to get at the XML directly.\n" ]
[ 2, 1 ]
[]
[]
[ "django", "python", "web_services", "xml" ]
stackoverflow_0002826004_django_python_web_services_xml.txt
Q: Creating a document tree before or after adding the subelements I am using lxml and Python for writing XML files. I was wondering what is the accepted practice: creating a document tree first and then adding the sub elements OR adding the sub elements and creating the tree later? I know this hardly makes any difference as to the output, but I was interested in knowing what is the accepted norm in this from a coding-style point of view. Sample code: page = etree.Element('root') #first create the tree doc = etree.ElementTree(page) #add the subelements headElt = etree.SubElement(page, 'head') Or this: page = etree.Element('root') headElt = etree.SubElement(page, 'head') #create the tree in the end doc = etree.ElementTree(page) A: Since tree construction is typically a recursive action, I would say that the tree root could get created last, once the subtree is done. However, I don't see any reason why that should be any better than creating the tree first. I honestly don't think there's an accepted norm for this, and rather than trying to find one I would advise you to write your code in such a way that it makes sense for you and anyone else that might need to read and understand it later.
Creating a document tree before or after adding the subelements
I am using lxml and Python for writing XML files. I was wondering what is the accepted practice: creating a document tree first and then adding the sub elements OR adding the sub elements and creating the tree later? I know this hardly makes any difference as to the output, but I was interested in knowing what is the accepted norm in this from a coding-style point of view. Sample code: page = etree.Element('root') #first create the tree doc = etree.ElementTree(page) #add the subelements headElt = etree.SubElement(page, 'head') Or this: page = etree.Element('root') headElt = etree.SubElement(page, 'head') #create the tree in the end doc = etree.ElementTree(page)
[ "Since tree construction is typically a recursive action, I would say that the tree root could get created last, once the subtree is done. However, I don't see any reason why that should be any better than creating the tree first. I honestly don't think there's an accepted norm for this, and rather than trying to find one I would advise you to write your code in such a way that it makes sense for you and anyone else that might need to read and understand it later. \n" ]
[ 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0002825988_lxml_python.txt
Q: Python to Java translation i get quite short code of algorithm in python, but i need to translate it to Java. I didnt find any program to do that, so i will really appreciate to help translating it. I learned python a very little to know the idea how algorithm work. The biggest problem is because in python all is object and some things are made really very confuzing like sum(self.flow[(source, vertex)] for vertex, capacity in self.get_edges(source)) and "self.adj" is like hashmap with multiple values which i have no idea how to put all together. Is any better collection for this code in java? code is: class FlowNetwork(object): def __init__(self): self.adj, self.flow, = {},{} def add_vertex(self, vertex): self.adj[vertex] = [] def get_edges(self, v): return self.adj[v] def add_edge(self, u,v,w=0): self.adj[u].append((v,w)) self.adj[v].append((u,0)) self.flow[(u,v)] = self.flow[(v,u)] = 0 def find_path(self, source, sink, path): if source == sink: return path for vertex, capacity in self.get_edges(source): residual = capacity - self.flow[(source,vertex)] edge = (source,vertex,residual) if residual > 0 and not edge in path: result = self.find_path(vertex, sink, path + [edge]) if result != None: return result def max_flow(self, source, sink): path = self.find_path(source, sink, []) while path != None: flow = min(r for u,v,r in path) for u,v,_ in path: self.flow[(u,v)] += flow self.flow[(v,u)] -= flow path = self.find_path(source, sink, []) return sum(self.flow[(source, vertex)] for vertex, capacity in self.get_edges(source)) g = FlowNetwork() map(g.add_vertex, ['s','o','p','q','r','t']) g.add_edge('s','o',3) g.add_edge('s','p',3) g.add_edge('o','p',2) g.add_edge('o','q',3) g.add_edge('p','r',2) g.add_edge('r','t',3) g.add_edge('q','r',4) g.add_edge('q','t',2) print g.max_flow('s','t') result of this example is "5". algorithm find max flow in graph(linked list or whatever) from source vertex "s" to destination "t". Many thanks for any idea A: Java doesn't have anything like Python's comprehension syntax. You'll have to replace it with code that loops over the list and aggregates the value of sum as it goes. Also, self.flow looks like a dictionary indexed by pairs. The only way to match this, AFAIK, is to create a class with two fields that implements hashCode and equals to use as a key for a HashMap.
Python to Java translation
i get quite short code of algorithm in python, but i need to translate it to Java. I didnt find any program to do that, so i will really appreciate to help translating it. I learned python a very little to know the idea how algorithm work. The biggest problem is because in python all is object and some things are made really very confuzing like sum(self.flow[(source, vertex)] for vertex, capacity in self.get_edges(source)) and "self.adj" is like hashmap with multiple values which i have no idea how to put all together. Is any better collection for this code in java? code is: class FlowNetwork(object): def __init__(self): self.adj, self.flow, = {},{} def add_vertex(self, vertex): self.adj[vertex] = [] def get_edges(self, v): return self.adj[v] def add_edge(self, u,v,w=0): self.adj[u].append((v,w)) self.adj[v].append((u,0)) self.flow[(u,v)] = self.flow[(v,u)] = 0 def find_path(self, source, sink, path): if source == sink: return path for vertex, capacity in self.get_edges(source): residual = capacity - self.flow[(source,vertex)] edge = (source,vertex,residual) if residual > 0 and not edge in path: result = self.find_path(vertex, sink, path + [edge]) if result != None: return result def max_flow(self, source, sink): path = self.find_path(source, sink, []) while path != None: flow = min(r for u,v,r in path) for u,v,_ in path: self.flow[(u,v)] += flow self.flow[(v,u)] -= flow path = self.find_path(source, sink, []) return sum(self.flow[(source, vertex)] for vertex, capacity in self.get_edges(source)) g = FlowNetwork() map(g.add_vertex, ['s','o','p','q','r','t']) g.add_edge('s','o',3) g.add_edge('s','p',3) g.add_edge('o','p',2) g.add_edge('o','q',3) g.add_edge('p','r',2) g.add_edge('r','t',3) g.add_edge('q','r',4) g.add_edge('q','t',2) print g.max_flow('s','t') result of this example is "5". algorithm find max flow in graph(linked list or whatever) from source vertex "s" to destination "t". Many thanks for any idea
[ "Java doesn't have anything like Python's comprehension syntax. You'll have to replace it with code that loops over the list and aggregates the value of sum as it goes.\nAlso, self.flow looks like a dictionary indexed by pairs. The only way to match this, AFAIK, is to create a class with two fields that implements hashCode and equals to use as a key for a HashMap.\n" ]
[ 2 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002826196_java_python.txt
Q: Django and JSON request In a template I have the following code. <script> var url="/mypjt/my_timer" $.post(url, paramarr, function callbackHandler(dict) { alert('got response back'); if (dict.flag == 2) { alert('1'); $.jGrowl("Data could not be saved"); } else if(dict.ret_status == 1) { alert('2'); $.jGrowl("Data saved successfully"); window.location = "/mypjt/display/" + dict.rid; } }, "json" ); </script> In views I have the following code, def my_timer(request): dict={} try: a = timer.objects.get(pk=1) dict({'flag':1}) return HttpResponse(simplejson.dumps(dict), mimetype='application/javascript') except: dict({'flag':1}) return HttpResponse(simplejson.dumps(dict), mimetype='application/javascript') Since we are making a JSON request and in the try block, after setting the flag, can't we return a page directly as return render_to_response('mypjt/display.html',context_instance=RequestContext(request,{'dict': dict})) instead of sending the response, because on success again in the HTML page we redirect the code? Also if there is a exception then only can we return the JSON request. My only concern is that the interaction between client and server should be minimal. A: If I understand rightly, you're sniffing the return code in the JavaScript, and then redirecting depending on the results. You can do a redirect from Django, so I would do that instead of worrying about return codes. When you've got both a "flag" and a "ret_status", that is a hint you should re-think your design. :) Also, shadowing the built-in dict object in the Python code should be avoided. A: If you do the response like you said, return render_to_response('mypjt/display.html',context_instance=RequestContext(request,{'dict': dict})) the JavaScript code will receive your response, not the navigator. I think you can do somethink like this: <script> $(document).ready(function() { $('#yourForm').submit(); }); </script> <form id="yourForm" action="/mypjt/my_timer" method="post"> ... your fields with data, even they are hidden ... </form> So, in Django you can do the response like you said: def my_timer(request): dict={} try: a= timer.objects.get(pk=1) dict({'flag':1}) return render_to_response('mypjt/display.html',context_instance=RequestContext(request,{'dict': dict})) except: dict({'flag':0}) return render_to_response('mypjt/error_not_found.html',context_instance=RequestContext(request,{'dict': dict})) Or, you can do like you were doing but if the query "timer.objects.get(pk=1)" fails, for example, you send back a boolean flag response. So, when it is OK you redirect to the page you prefer. I hope it could be useful to you!
Django and JSON request
In a template I have the following code. <script> var url="/mypjt/my_timer" $.post(url, paramarr, function callbackHandler(dict) { alert('got response back'); if (dict.flag == 2) { alert('1'); $.jGrowl("Data could not be saved"); } else if(dict.ret_status == 1) { alert('2'); $.jGrowl("Data saved successfully"); window.location = "/mypjt/display/" + dict.rid; } }, "json" ); </script> In views I have the following code, def my_timer(request): dict={} try: a = timer.objects.get(pk=1) dict({'flag':1}) return HttpResponse(simplejson.dumps(dict), mimetype='application/javascript') except: dict({'flag':1}) return HttpResponse(simplejson.dumps(dict), mimetype='application/javascript') Since we are making a JSON request and in the try block, after setting the flag, can't we return a page directly as return render_to_response('mypjt/display.html',context_instance=RequestContext(request,{'dict': dict})) instead of sending the response, because on success again in the HTML page we redirect the code? Also if there is a exception then only can we return the JSON request. My only concern is that the interaction between client and server should be minimal.
[ "If I understand rightly, you're sniffing the return code in the JavaScript, and then redirecting depending on the results.\nYou can do a redirect from Django, so I would do that instead of worrying about return codes. When you've got both a \"flag\" and a \"ret_status\", that is a hint you should re-think your design. :)\nAlso, shadowing the built-in dict object in the Python code should be avoided.\n", "If you do the response like you said,\n\nreturn\n render_to_response('mypjt/display.html',context_instance=RequestContext(request,{'dict':\n dict}))\n\nthe JavaScript code will receive your response, not the navigator. I think you can do somethink like this:\n<script>\n $(document).ready(function()\n {\n $('#yourForm').submit();\n });\n</script>\n\n<form id=\"yourForm\" action=\"/mypjt/my_timer\" method=\"post\">\n...\nyour fields with data, even they are hidden\n...\n</form>\n\nSo, in Django you can do the response like you said:\n def my_timer(request):\n dict={}\n try:\n a= timer.objects.get(pk=1)\n\n dict({'flag':1})\n return render_to_response('mypjt/display.html',context_instance=RequestContext(request,{'dict': dict}))\n except:\n dict({'flag':0})\n return render_to_response('mypjt/error_not_found.html',context_instance=RequestContext(request,{'dict': dict}))\n\nOr, you can do like you were doing but if the query \"timer.objects.get(pk=1)\" fails, for example, you send back a boolean flag response. So, when it is OK you redirect to the page you prefer.\nI hope it could be useful to you!\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_views", "json", "jsonresult", "python" ]
stackoverflow_0002822599_django_django_views_json_jsonresult_python.txt
Q: Explain Python extensions multithreading Python interpreter has a Global Interpreter Lock, and it is my understanding that extensions must acquire it in a multi-threaded environment. But Boost.Python HOWTO page says the extension function must release the GIL and reacquire it on exit. I want to resist temptation to guess here, so I would like to know what should be GIL locking patterns in the following scenarios: Extension is called from python (presumably running in a python thread). And extension's background thread calls back into Py_* functions. And a final question is, why the linked document says the GIL should be released and re-acquired? A: Whenever Python is interpreting bytecode the GIL is being held by the currently running thread. No other Python thread can run until it manages to acquire the GIL. When the interpreter has called into native code that code has two options regarding the GIL: It could do nothing at all. It could release the GIL while it works and then reacquire it before returning to Python If the native code makes a lot of calls back to Python's runtime it should take option 1: you can never call Python's runtime safely unless you hold the GIL (with a few exceptions such as making the call to acquire the GIL if you don't have it). If the native code does a lot of work which doesn't involve Python in any way then you can use option 2: as soon as you release the GIL Python will be able to schedule another Python thread so you get some parallelism. If you don't release the GIL then none of Python's other threads can execute while your Boost code is running: that's why the docs tell you to release and reacquire the GIL. If you go this way then you must be careful to make all your access to Py_* functions before you release the GIL or after you reacquire it. This may mean you have to make local copies of data as you cannot safely access Python data types such as list or dictionary elements while the GIL is released. If your Boost code needs to call back into Python while the GIL is released then you need to acquire the GIL, make the call, release the GIL. Try to avoid making such calls from threads that weren't created by Python as they need additional work to be able to acquire the GIL.
Explain Python extensions multithreading
Python interpreter has a Global Interpreter Lock, and it is my understanding that extensions must acquire it in a multi-threaded environment. But Boost.Python HOWTO page says the extension function must release the GIL and reacquire it on exit. I want to resist temptation to guess here, so I would like to know what should be GIL locking patterns in the following scenarios: Extension is called from python (presumably running in a python thread). And extension's background thread calls back into Py_* functions. And a final question is, why the linked document says the GIL should be released and re-acquired?
[ "Whenever Python is interpreting bytecode the GIL is being held by the currently running thread. No other Python thread can run until it manages to acquire the GIL.\nWhen the interpreter has called into native code that code has two options regarding the GIL:\n\nIt could do nothing at all.\nIt could release the GIL while it works and then reacquire it before returning to Python\n\nIf the native code makes a lot of calls back to Python's runtime it should take option 1: you can never call Python's runtime safely unless you hold the GIL (with a few exceptions such as making the call to acquire the GIL if you don't have it).\nIf the native code does a lot of work which doesn't involve Python in any way then you can use option 2: as soon as you release the GIL Python will be able to schedule another Python thread so you get some parallelism. If you don't release the GIL then none of Python's other threads can execute while your Boost code is running: that's why the docs tell you to release and reacquire the GIL.\nIf you go this way then you must be careful to make all your access to Py_* functions before you release the GIL or after you reacquire it. This may mean you have to make local copies of data as you cannot safely access Python data types such as list or dictionary elements while the GIL is released.\nIf your Boost code needs to call back into Python while the GIL is released then you need to acquire the GIL, make the call, release the GIL. Try to avoid making such calls from threads that weren't created by Python as they need additional work to be able to acquire the GIL.\n" ]
[ 6 ]
[]
[]
[ "boost_python", "c++", "multithreading", "python" ]
stackoverflow_0002825362_boost_python_c++_multithreading_python.txt
Q: Does Google appengine cache external requests? I have a very simple application running on appengine that requests a web page every five minutes and parses for a specific piece of data. Everything works fine except that the response I get back from the external request (using urllib2) doesn't reflect the latest changes to the page. Sometimes it takes a few minutes to get the latest, sometimes over an hour. Is there a transparent layer of caching that appengine puts in place? Or is there something else I am missing here? I've looked at the caching headers of the requested page and there is no Expires, LastModified or ETags headers sent. Update: Sometimes, it will get the new version of the page for a number of requests and then randomly later get an old out of date version. A: It appears that this is an issue the App Engine team is aware of. The suggested workaround is to set Cache-Control header with max-age in seconds: result = urlfetch.fetch(url, headers = {'Cache-Control' : 'max-age=240'}) should hopefully work for you.
Does Google appengine cache external requests?
I have a very simple application running on appengine that requests a web page every five minutes and parses for a specific piece of data. Everything works fine except that the response I get back from the external request (using urllib2) doesn't reflect the latest changes to the page. Sometimes it takes a few minutes to get the latest, sometimes over an hour. Is there a transparent layer of caching that appengine puts in place? Or is there something else I am missing here? I've looked at the caching headers of the requested page and there is no Expires, LastModified or ETags headers sent. Update: Sometimes, it will get the new version of the page for a number of requests and then randomly later get an old out of date version.
[ "It appears that this is an issue the App Engine team is aware of. The suggested workaround is to set Cache-Control header with max-age in seconds:\nresult = urlfetch.fetch(url, headers = {'Cache-Control' : 'max-age=240'})\n\nshould hopefully work for you.\n" ]
[ 8 ]
[]
[]
[ "caching", "google_app_engine", "python", "urllib2" ]
stackoverflow_0002826238_caching_google_app_engine_python_urllib2.txt
Q: Django URL matching Can anyone see why this wouldn't be working? I'm fairly new to Django so any help would be much appreciated. Actual URL: http://127.0.0.1:8000/2010/may/12/my-second-blog-post/ urls.py: (r'(?P<year>d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-w]+)/$', 'object_detail', dict(info_dict, slug_field='slug',template_name='blog/detail.html')), A: r'(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\w{1,2})/(?P<slug>[\w-]+)/$', 'object_detail', dict(info_dict, slug_field='slug',template_name='blog/detail.html')), You seem to have forgotten the backslashes. A: Are you specifying this in an app context or in the project url routing? You may need to start your regular expression with a ^. (r'^foo/$', 'foo'),
Django URL matching
Can anyone see why this wouldn't be working? I'm fairly new to Django so any help would be much appreciated. Actual URL: http://127.0.0.1:8000/2010/may/12/my-second-blog-post/ urls.py: (r'(?P<year>d{4})/(?P<month>[a-z]{3})/(?P<day>w{1,2})/(?P<slug>[-w]+)/$', 'object_detail', dict(info_dict, slug_field='slug',template_name='blog/detail.html')),
[ "r'(?P<year>\\d{4})/(?P<month>[a-z]{3})/(?P<day>\\w{1,2})/(?P<slug>[\\w-]+)/$', \n'object_detail', \ndict(info_dict, slug_field='slug',template_name='blog/detail.html')),\n\nYou seem to have forgotten the backslashes.\n", "Are you specifying this in an app context or in the project url routing?\nYou may need to start your regular expression with a ^.\n(r'^foo/$', 'foo'),\n\n" ]
[ 12, 0 ]
[]
[]
[ "django", "python", "regex", "url" ]
stackoverflow_0002827158_django_python_regex_url.txt
Q: how execute a Python Script with activeresource? I need to execute this python script: http://superjared.com/static/code/googleMX.py I installed pyactiveresource, but when I executed it: python googleMX.py I had this response. Traceback (most recent call last): File "googleMX.py", line 15, in ? from pyactiveresource import ActiveResource ImportError: cannot import name ActiveResource A: by Responding myself... It was using an older version of pyactiveresource. The author (Lucky) creates another one http://gist.github.com/330832
how execute a Python Script with activeresource?
I need to execute this python script: http://superjared.com/static/code/googleMX.py I installed pyactiveresource, but when I executed it: python googleMX.py I had this response. Traceback (most recent call last): File "googleMX.py", line 15, in ? from pyactiveresource import ActiveResource ImportError: cannot import name ActiveResource
[ "by Responding myself...\nIt was using an older version of pyactiveresource. The author (Lucky) creates another one http://gist.github.com/330832\n" ]
[ 0 ]
[]
[]
[ "activeresource", "python" ]
stackoverflow_0002435778_activeresource_python.txt
Q: Python and Excel - check if file is open hey guys, I need help considering win32com in Python: I have a routine that opens a Workbook, creates a sheet and puts some data on it. If everything runs fine the woorkbook is saved and closed - If not the python session is terminated but the woorkbook is left open. So the reference is lost. Now when restarting the code Excel prompts you with the msg "workbook still open do you want to re-open?". So what I want is to suppress this msg. I found a solution that works for me when python terminates before writing to the sheet: open_copys = self.xlApp.Workbooks.Count if open_copys > 0: """ Check if any copy is the desired one""" for i in range(0, open_copys): if(self.xlApp.Workbooks[i].FullName == self.file_path): self.xlBook = self.xlApp.Workbooks[i] else: self.xlBook = self.xlApp.Workbooks.Open(self.file_path) But if any changes were made on the EXCEL sheet this method is obsolet. Anyone got an ides how to get back a reference to an open and changed worksheet from a new python session? thx A: I'm not familiar with Python but have done some Excel/Word COM code in other languages. Excel's Application.DisplayAlerts property might help. Setting it to False suppresses most messages that Excel might normally show, and auto-chooses a default response, though I think there are some exceptions. Looking at your existing code, I guess you'd insert this line before opening the workbook: self.xlApp.DisplayAlerts = False A: Have you tried to remove all references to your COM objects before terminating the Python interpreter ? You can force them to be garbage collected (using gc.collect()) to be really sure they are gone. This way the workbook shouldn't remain open in memory and you won't have the error message. Try adding a "close()" method to your class, with something like the following, and call it before the end of your script. import gc ... def close(self): del self.xlApp if hasattr(self, 'xlBook'): del self.xlBook gc.collect() A: You're going about this the wrong way. You do NOT want to let Python terminate, leaving orphaned Excel processes. This is especially important if you are going to install and run this code on other machines. Instead, find your errors and handle them - then you'll never have orphaned processes to deal with. That said, there are a few things you can consider. You can choose either to instantiate a new Excel process each time (Dispatch) or work with an existing one (DispatchEx). This lets you do things like see what workbooks are open and to close them, or ensures that your process will not interfere with others. Also as Scott said, the Excel Application has some interesting properties, like suppressing errors for unattended running, that are worth learning.
Python and Excel - check if file is open
hey guys, I need help considering win32com in Python: I have a routine that opens a Workbook, creates a sheet and puts some data on it. If everything runs fine the woorkbook is saved and closed - If not the python session is terminated but the woorkbook is left open. So the reference is lost. Now when restarting the code Excel prompts you with the msg "workbook still open do you want to re-open?". So what I want is to suppress this msg. I found a solution that works for me when python terminates before writing to the sheet: open_copys = self.xlApp.Workbooks.Count if open_copys > 0: """ Check if any copy is the desired one""" for i in range(0, open_copys): if(self.xlApp.Workbooks[i].FullName == self.file_path): self.xlBook = self.xlApp.Workbooks[i] else: self.xlBook = self.xlApp.Workbooks.Open(self.file_path) But if any changes were made on the EXCEL sheet this method is obsolet. Anyone got an ides how to get back a reference to an open and changed worksheet from a new python session? thx
[ "I'm not familiar with Python but have done some Excel/Word COM code in other languages.\nExcel's Application.DisplayAlerts property might help. Setting it to False suppresses most messages that Excel might normally show, and auto-chooses a default response, though I think there are some exceptions.\nLooking at your existing code, I guess you'd insert this line before opening the workbook: \n self.xlApp.DisplayAlerts = False\n", "Have you tried to remove all references to your COM objects before terminating the Python interpreter ? You can force them to be garbage collected (using gc.collect()) to be really sure they are gone. This way the workbook shouldn't remain open in memory and you won't have the error message.\nTry adding a \"close()\" method to your class, with something like the following, and call it before the end of your script.\nimport gc\n\n...\n\ndef close(self):\n del self.xlApp\n if hasattr(self, 'xlBook'):\n del self.xlBook\n gc.collect()\n\n", "You're going about this the wrong way. You do NOT want to let Python terminate, leaving orphaned Excel processes. This is especially important if you are going to install and run this code on other machines. Instead, find your errors and handle them - then you'll never have orphaned processes to deal with.\nThat said, there are a few things you can consider. You can choose either to instantiate a new Excel process each time (Dispatch) or work with an existing one (DispatchEx). This lets you do things like see what workbooks are open and to close them, or ensures that your process will not interfere with others. Also as Scott said, the Excel Application has some interesting properties, like suppressing errors for unattended running, that are worth learning.\n" ]
[ 3, 1, 1 ]
[]
[]
[ "excel", "python" ]
stackoverflow_0002816530_excel_python.txt
Q: what if i keep my class members are public? In c++ instance variables are private by default,in Python variables are public by default i have two questions regarding the same:- 1: why Python have all the members are public by default? 2: People say you should your member data should be private what if i make my data to be public? what are the disadvantages of this approch? why it is a bad design? A: You can use a leading underscore in the name to tell readers of the code that the name in question is an internal detail and they must not rely on it remaining in future versions. Such a convention is really all you need -- why weigh the language down with an enforcement mechanism? Data, just like methods, should be public (named without a leading underscore) if they're part of your class's designed API which you intend to support going forward. In C++, or Java, that's unlikely to happen because if you want to change the data member into an accessor method, you're out of luck -- you'll have to break your API and every single client of the class will have to change. In Python, and other languages supporting a property-like construct, that's not the case -- you can always replace a data member with a property which calls accessor methods transparently, the API does not change, nor does client code. So, in Python and other languages with property-like constructs (I believe .NET languages are like that, at source-code level though not necessarily at bytecode level), you may as well leave your data public when it's part of the API and no accessors are currently needed (you can always add accessor methods to later implementation releases if need be, and not break the API). So it's not really a general OO issue, it's language specific: does a given language support a property-like construct. Python does. A: I can't comment on Python, but in C++, structs provide public access by default. The primary reason you want a private part of your class is that, without one, it is impossible to guarantee your invariants are satisfied. If you have a string class, for instance, that is supposed to keep track of the length of the string, you need to be able to track insertions. But if the underlying char* member is public, you can't do that. Anybody can just come along and tack something onto the end, or overwrite your null terminator, or call delete[] on it, or whatever. When you call your length() member, you just have to hope for the best. A: It's really a question of language design philosophies. I favour the Python camp so might come down a little heavy handedly on the C++ style but the bottom line is that in C++ it's possible to forcibly prevent users of your class from accessing certain internal parts. In Python, it's a matter of convention and stating that it's internal. Some applications might want to access the internal member for non-malignant purposes (eg. documentation generators). Some users who know what they're doing might want to do the same. People who want to shoot themselves in the foot twiddling with the internal details are not protected from suicide. Like Dennis said "Anybody can just come along and tack something onto the end, or overwrite your null terminator". Python treats the user like an adult and expects her to take care of herself. C++ protects the user as one would a child. A: This is why.
what if i keep my class members are public?
In c++ instance variables are private by default,in Python variables are public by default i have two questions regarding the same:- 1: why Python have all the members are public by default? 2: People say you should your member data should be private what if i make my data to be public? what are the disadvantages of this approch? why it is a bad design?
[ "You can use a leading underscore in the name to tell readers of the code that the name in question is an internal detail and they must not rely on it remaining in future versions. Such a convention is really all you need -- why weigh the language down with an enforcement mechanism?\nData, just like methods, should be public (named without a leading underscore) if they're part of your class's designed API which you intend to support going forward. In C++, or Java, that's unlikely to happen because if you want to change the data member into an accessor method, you're out of luck -- you'll have to break your API and every single client of the class will have to change.\nIn Python, and other languages supporting a property-like construct, that's not the case -- you can always replace a data member with a property which calls accessor methods transparently, the API does not change, nor does client code. So, in Python and other languages with property-like constructs (I believe .NET languages are like that, at source-code level though not necessarily at bytecode level), you may as well leave your data public when it's part of the API and no accessors are currently needed (you can always add accessor methods to later implementation releases if need be, and not break the API).\nSo it's not really a general OO issue, it's language specific: does a given language support a property-like construct. Python does.\n", "I can't comment on Python, but in C++, structs provide public access by default. \nThe primary reason you want a private part of your class is that, without one, it is impossible to guarantee your invariants are satisfied. If you have a string class, for instance, that is supposed to keep track of the length of the string, you need to be able to track insertions. But if the underlying char* member is public, you can't do that. Anybody can just come along and tack something onto the end, or overwrite your null terminator, or call delete[] on it, or whatever. When you call your length() member, you just have to hope for the best.\n", "It's really a question of language design philosophies. I favour the Python camp so might come down a little heavy handedly on the C++ style but the bottom line is that in C++ it's possible to forcibly prevent users of your class from accessing certain internal parts. \nIn Python, it's a matter of convention and stating that it's internal. Some applications might want to access the internal member for non-malignant purposes (eg. documentation generators). Some users who know what they're doing might want to do the same. People who want to shoot themselves in the foot twiddling with the internal details are not protected from suicide. \nLike Dennis said \"Anybody can just come along and tack something onto the end, or overwrite your null terminator\". Python treats the user like an adult and expects her to take care of herself. C++ protects the user as one would a child. \n", "This is why.\n" ]
[ 13, 3, 1, 0 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0002824579_c++_python.txt
Q: delete all records except the id I have in a python list I want to delete all records in a mysql db except the record id's I have in a list. The length of that list can vary and could easily contain 2000+ id's, ... Currently I convert my list to a string so it fits in something like this: cursor.execute("""delete from table where id not in (%s)""",(list)) Which doesn't feel right and I have no idea how long list is allowed to be, .... What's the most efficient way of doing this from python? Altering the structure of table with an extra field to mark/unmark records for deletion would be great but not an option. Having a dedicated table storing the id's would indeed be helpful then this can just be done through a sql query... but I would really like to avoid these options if possible. Thanks, A: If the db table is not too large, just read in all the ids, and make a list of the ones you want to delete: keep_ids=[...] cursor.execute('SELECT id FROM table') delete_ids=[] for (row_id,) in cursor: if row_id not in keep_ids: delete_ids.append(row_id) cursor.executemany('DELETE FROM table WHERE id = %s',delete_ids) If the db table is huge, then recreate the table: keep_ids=[...] cursor.execute('CREATE TABLE IF NOT EXISTS temp_table LIKE table') cursor.executemany('INSERT INTO temp_table (SELECT * FROM table WHERE id = %s)',keep_ids) cursor.execute('DROP TABLE table') cursor.execute('ALTER TABLE temp_table RENAME table') A: Have you exhausted the possibility of doing your computation in SQL directly? If so, I don't see another way to do this without doing what you are already doing. Be sure, of course, that you are creating valid SQL, which if you're plugging in: ','.join(str(int(x)) for x in ids) you certainly are, if substituted in your statement directly. I'm not sure if there's a limit to the number of ids in the NOT IN (...) clause but would doubt it, since you can use an arbitrarily long list when using a subquery to populate that list. A: I'd add a "todelete tinyint(1) not null default 1" column to the table, update it to 0 for those id's which have to be kept, then delete from table where todelete;. It's faster than not in. Or, create a table with the same structure as yours, insert the kept rows there and rename tables. Then, drop the old one.
delete all records except the id I have in a python list
I want to delete all records in a mysql db except the record id's I have in a list. The length of that list can vary and could easily contain 2000+ id's, ... Currently I convert my list to a string so it fits in something like this: cursor.execute("""delete from table where id not in (%s)""",(list)) Which doesn't feel right and I have no idea how long list is allowed to be, .... What's the most efficient way of doing this from python? Altering the structure of table with an extra field to mark/unmark records for deletion would be great but not an option. Having a dedicated table storing the id's would indeed be helpful then this can just be done through a sql query... but I would really like to avoid these options if possible. Thanks,
[ "If the db table is not too large, just read in all the ids, and\nmake a list of the ones you want to delete:\nkeep_ids=[...]\ncursor.execute('SELECT id FROM table')\ndelete_ids=[]\nfor (row_id,) in cursor:\n if row_id not in keep_ids:\n delete_ids.append(row_id)\ncursor.executemany('DELETE FROM table WHERE id = %s',delete_ids)\n\nIf the db table is huge, then recreate the table:\nkeep_ids=[...]\ncursor.execute('CREATE TABLE IF NOT EXISTS temp_table LIKE table')\ncursor.executemany('INSERT INTO temp_table (SELECT * FROM table WHERE id = %s)',keep_ids)\ncursor.execute('DROP TABLE table')\ncursor.execute('ALTER TABLE temp_table RENAME table')\n\n", "Have you exhausted the possibility of doing your computation in SQL directly? If so, I don't see another way to do this without doing what you are already doing. Be sure, of course, that you are creating valid SQL, which if you're plugging in:\n','.join(str(int(x)) for x in ids)\n\nyou certainly are, if substituted in your statement directly. I'm not sure if there's a limit to the number of ids in the NOT IN (...) clause but would doubt it, since you can use an arbitrarily long list when using a subquery to populate that list.\n", "I'd add a \"todelete tinyint(1) not null default 1\" column to the table, update it to 0 for those id's which have to be kept, then delete from table where todelete;. It's faster than not in.\nOr, create a table with the same structure as yours, insert the kept rows there and rename tables. Then, drop the old one.\n" ]
[ 4, 1, 0 ]
[ "That's what temporary tables are for. You create a temporary table containing your exclusion list and use the DBM to do your selection for you. A simple example:\nCREATE TABLE words (id integer primary key not null, word string);\nCREATE TEMPORARY TABLE exclusion (word string);\nINSERT INTO words VALUES ... # 100,000 of these\nINSERT INTO exclusion VALUES ... # 1000 of these\nDELETE FROM words WHERE words.word NOT IN (SELECT word FROM exclusion);\n# 99,000 records now in words, table exclusion evaporates when the session is over\n\nSomeone who actually knows SQL can probably improve on my last line. If you are doing selections in application space, something is wrong. MySQL has temporary tables, but even if you didn't a CREATE/DROP exclusions would still be better than an overlong statement.\nIncidentally, I hacked this up in Python only because I had a huge wordlist handy. The code is boring so not posted.\n" ]
[ -2 ]
[ "mysql", "python" ]
stackoverflow_0002826387_mysql_python.txt
Q: Application with both console and gui mode I have a python console app. Like most python console apps it uses the OptionParser module to take arguments. I've now developed a GUI for my app using wxPython and i'd like to integrate the two. I'd like my app to be run both from the console and from the OS's UI. When it is invoked from the console it runs as a console app and when it is double clicked in the OS's UI, it runs as a GUI app. How could I do something like this? Could someone show me a a snippet of what the __main__ block should be like? Thanks a ton. A: can you pass args to the app then use the arg parser? if __name__ == "__main__": from optparse import OptionParser parser = OptionParser() parser.add_option("-g","--gui_mode", dest="guimode", help="start program in gui mode", action="store_true") (options,args) = parser.parse_args() if (options.guimode): print "start wx app" else: print "start cmd line app" Edit: Sorry, misread, i thought you wanted to start from another Wx App. rather than from the "OS UI" I don't know of a great, cross platform way to do this. The issue is that in windows .py files are usually associated with the python.exe .pyw files are similar, but don't have a console window. So you would actually have to modify the OS to support this behaviour. For example you could create a shortcut (in windows/gnome/kde) that launches the program with --gui_mode or use a mechanism like @Austin suggested in an *nix OS. Some of this stuff can be automated by disttools if you are installing an application A: Try: import os print os.environ and have it output os.environ['TERM'] to a tkinter window when you execute the script by double-clicking it. For me, it's 'xterm-color'. What operating system are you using? How do you ensure that double-clicking a .py file will result in its execution?
Application with both console and gui mode
I have a python console app. Like most python console apps it uses the OptionParser module to take arguments. I've now developed a GUI for my app using wxPython and i'd like to integrate the two. I'd like my app to be run both from the console and from the OS's UI. When it is invoked from the console it runs as a console app and when it is double clicked in the OS's UI, it runs as a GUI app. How could I do something like this? Could someone show me a a snippet of what the __main__ block should be like? Thanks a ton.
[ "can you pass args to the app then use the arg parser? \nif __name__ == \"__main__\":\n from optparse import OptionParser\n\n parser = OptionParser() \n parser.add_option(\"-g\",\"--gui_mode\",\n dest=\"guimode\",\n help=\"start program in gui mode\",\n action=\"store_true\")\n\n (options,args) = parser.parse_args()\n\n if (options.guimode):\n print \"start wx app\"\n else:\n print \"start cmd line app\"\n\nEdit:\nSorry, misread, i thought you wanted to start from another Wx App. rather than from the \"OS UI\"\nI don't know of a great, cross platform way to do this. The issue is that in windows .py files are usually associated with the python.exe .pyw files are similar, but don't have a console window.\nSo you would actually have to modify the OS to support this behaviour. For example you could create a shortcut (in windows/gnome/kde) that launches the program with --gui_mode or use a mechanism like @Austin suggested in an *nix OS. \nSome of this stuff can be automated by disttools if you are installing an application\n", "Try:\nimport os\nprint os.environ\n\nand have it output os.environ['TERM'] to a tkinter window when you execute the script by double-clicking it.\nFor me, it's 'xterm-color'.\nWhat operating system are you using? How do you ensure that double-clicking a .py file will result in its execution?\n" ]
[ 2, 0 ]
[]
[]
[ "console_application", "optionparser", "python", "user_interface", "wxpython" ]
stackoverflow_0002827582_console_application_optionparser_python_user_interface_wxpython.txt
Q: python logparse search specific text I am using this function in my code to return the strings i want from reading the log file, I want to grep the "exim" process and return the results, but running the code gives no error, but the output is limited to three lines, how can i just get the output only related to exim process.. #output: {'date': '13', 'process': 'syslogd', 'time': '06:27:33', 'month': 'May'} {'date': '13', 'process': 'exim[23168]:', 'time': '06:27:33', 'month': 'May'} {'May': ['syslogd']} #function: def generate_log_report(logfile): report_dict = {} for line in logfile: line_dict = dictify_logline(line) print line_dict try: month = line_dict['month'] date = line_dict['date'] time = line_dict['time'] #process = line_dict['process'] if "exim" in line_dict['process']: process = line_dict['process'] break else: process = line_dict['process'] except ValueError: continue report_dict.setdefault(month, []).append(process) return report_dict A: It's because you have a break statement inside the if that checks for "exim". As soon as you find a line with "exim", you will stop processing entirely, which sounds like the opposite of what you want! I think you want to remove the break and put your printout inside the if. If your question is about the return value of the function, you need to make much more significant changes, probably removing report_dict entirely and simply creating a list of line_dicts that have exim in their process fields. A: i changed the code to this, but it gives me just one line as output??? anything missing... #!/usr/bin/env python import sys def generate_log_report(logfile): for line in logfile: line_split = line.split() list = [line_split[0], line_split[1], line_split[2], line_split[4]] if "exim" in list[3]: l = [line_split[0], line_split[1], line_split[2], line_split[4]] else: li = [line_split[0], line_split[1], line_split[2], line_split[4]] return l if __name__ == "__main__": if not len(sys.argv) > 1: print __doc__ sys.exit(1) infile_name = sys.argv[1] try: infile = open(infile_name, "r") except IOError: print "you must specify a valid file" print __doc__ sys.exit(1) log_report = generate_log_report(infile) print log_report infile.close()
python logparse search specific text
I am using this function in my code to return the strings i want from reading the log file, I want to grep the "exim" process and return the results, but running the code gives no error, but the output is limited to three lines, how can i just get the output only related to exim process.. #output: {'date': '13', 'process': 'syslogd', 'time': '06:27:33', 'month': 'May'} {'date': '13', 'process': 'exim[23168]:', 'time': '06:27:33', 'month': 'May'} {'May': ['syslogd']} #function: def generate_log_report(logfile): report_dict = {} for line in logfile: line_dict = dictify_logline(line) print line_dict try: month = line_dict['month'] date = line_dict['date'] time = line_dict['time'] #process = line_dict['process'] if "exim" in line_dict['process']: process = line_dict['process'] break else: process = line_dict['process'] except ValueError: continue report_dict.setdefault(month, []).append(process) return report_dict
[ "It's because you have a break statement inside the if that checks for \"exim\". As soon as you find a line with \"exim\", you will stop processing entirely, which sounds like the opposite of what you want!\nI think you want to remove the break and put your printout inside the if. If your question is about the return value of the function, you need to make much more significant changes, probably removing report_dict entirely and simply creating a list of line_dicts that have exim in their process fields.\n", "i changed the code to this, but it gives me just one line as output??? anything missing...\n#!/usr/bin/env python\n\nimport sys\n\ndef generate_log_report(logfile):\n for line in logfile:\n line_split = line.split()\n list = [line_split[0], line_split[1], line_split[2], line_split[4]]\n if \"exim\" in list[3]:\n l = [line_split[0], line_split[1], line_split[2], line_split[4]]\n else:\n li = [line_split[0], line_split[1], line_split[2], line_split[4]]\n return l\n\n\nif __name__ == \"__main__\":\n if not len(sys.argv) > 1:\n print __doc__\n sys.exit(1)\n infile_name = sys.argv[1]\n try:\n infile = open(infile_name, \"r\")\n except IOError:\n print \"you must specify a valid file\"\n print __doc__\n sys.exit(1)\n log_report = generate_log_report(infile)\n print log_report\n infile.close()\n\n" ]
[ 0, 0 ]
[]
[]
[ "logging", "parsing", "python" ]
stackoverflow_0002826742_logging_parsing_python.txt
Q: How do I find difference between times in different timezones in Python? I am trying to calculate difference(in seconds) between two date/times formatted as following: 2010-05-11 17:07:33 UTC 2010-05-11 17:07:33 EDT time1 = '2010-05-11 17:07:33 UTC' time2 = '2010-05-11 17:07:33 EDT' delta = time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M:%S %Z"))-\ time.mktime(time.strptime(time2, "%Y-%m-%d %H:%M:%S %Z")) The problem I got is EDT is not recognized, the specific error is ValueError: time data '2010-05-11 17:07:33 EDT' does not match format '%Y-%m-%d %H:%M:%S %Z' A: Check out the pytz world timezone definitions library. This library allows accurate and cross platform timezone calculations using Python 2.3 or higher. It also solves the issue of ambiguous times at the end of daylight savings, which you can read more about in the Python Library Reference (datetime.tzinfo). It takes advantage of the tz database, which should include EDT, and allow you to perform the calculations you need to (and probably more reliably & accurately than your current implementation). A: In addition to pytz, check out python-dateutil. The relativedelta functionality is outstanding. Here's a sample of using them together: from datetime import datetime from dateutil.relativedelta import * import pytz if __name__ == '__main__': date_one = datetime.now(pytz.timezone('US/Eastern')) date_two = datetime.now(pytz.timezone('US/Mountain')) rdelta = relativedelta(date_one, date_two) print(rdelta) A: From docs for strptime Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).
How do I find difference between times in different timezones in Python?
I am trying to calculate difference(in seconds) between two date/times formatted as following: 2010-05-11 17:07:33 UTC 2010-05-11 17:07:33 EDT time1 = '2010-05-11 17:07:33 UTC' time2 = '2010-05-11 17:07:33 EDT' delta = time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M:%S %Z"))-\ time.mktime(time.strptime(time2, "%Y-%m-%d %H:%M:%S %Z")) The problem I got is EDT is not recognized, the specific error is ValueError: time data '2010-05-11 17:07:33 EDT' does not match format '%Y-%m-%d %H:%M:%S %Z'
[ "Check out the pytz world timezone definitions library.\n\nThis library allows accurate and cross platform timezone calculations using Python 2.3 or higher. It also solves the issue of ambiguous times at the end of daylight savings, which you can read more about in the Python Library Reference (datetime.tzinfo).\n\nIt takes advantage of the tz database, which should include EDT, and allow you to perform the calculations you need to (and probably more reliably & accurately than your current implementation).\n", "In addition to pytz, check out python-dateutil. The relativedelta functionality is outstanding.\nHere's a sample of using them together:\nfrom datetime import datetime\n\nfrom dateutil.relativedelta import *\nimport pytz\n\nif __name__ == '__main__':\n date_one = datetime.now(pytz.timezone('US/Eastern'))\n date_two = datetime.now(pytz.timezone('US/Mountain'))\n rdelta = relativedelta(date_one, date_two)\n print(rdelta)\n\n", "From docs for strptime\n\nSupport for the %Z directive is based\n on the values contained in tzname and\n whether daylight is true. Because of\n this, it is platform-specific except\n for recognizing UTC and GMT which are\n always known (and are considered to be\n non-daylight savings timezones).\n\n" ]
[ 8, 5, 0 ]
[]
[]
[ "datetime", "python", "timezone" ]
stackoverflow_0002828158_datetime_python_timezone.txt
Q: Sum records values in Django I defined couple models in my app: class Project(models.Model): title = models.CharField(max_length=150) url = models.URLField() manager = models.ForeignKey(User) class Cost(models.Model): project = models.ForeignKey(Project) cost = models.FloatField() date = models.DateField() I want to sum costs for each project and render values view.py: from mypm.costs.models import Project, Cost from django.shortcuts import render_to_response from django.db.models import Avg, Sum def index(request): # ... return render_to_response('index.html',... What is the best way of solving such aggregation in Django ORM? A: Alexander's solution will give you the right result, but with one query for each project. Use annotate to do the whole thing in a single query. from django.db.models import Sum annotated_projects = Project.objects.all().annotate(cost_sum=Sum('cost__cost')) for project in annotated_projects: print project.title, project.cost_sum A: Here's one way to do it. There may be a more efficient way to write the get_total_cost function... but this should work. Models: class Project(models.Model): title = models.CharField(max_length=150) url = models.URLField() manager = models.ForeignKey(User) def get_total_cost(self): tot = 0 for cost in Cost.objects.filter(project=self): tot += cost.cost return tot class Cost(models.Model): project = models.ForeignKey(Project) cost = models.FloatField() date = models.DateField() View: from mypm.costs.models import Project, Cost from django.shortcuts import render_to_response from django.db.models import Avg, Sum def index(request): return render_to_response('index.html',{'projects',Project.objects.all()},context_instance=RequestContext(request)) Template: {% for project in projects %} <p>{{project.title}}: {{project.get_total_cost}}</p> {% endfor %} This is pretty basic stuff. Take some time and go through the Django tutorials and documentation. A: Try using aggregate. from django.db.models import Sum for project in Projects.objects.all(): print project, project.cost_set.all().aggregate(sum_of_cost=Sum('cost'))['sum_of_cost'] or 0
Sum records values in Django
I defined couple models in my app: class Project(models.Model): title = models.CharField(max_length=150) url = models.URLField() manager = models.ForeignKey(User) class Cost(models.Model): project = models.ForeignKey(Project) cost = models.FloatField() date = models.DateField() I want to sum costs for each project and render values view.py: from mypm.costs.models import Project, Cost from django.shortcuts import render_to_response from django.db.models import Avg, Sum def index(request): # ... return render_to_response('index.html',... What is the best way of solving such aggregation in Django ORM?
[ "Alexander's solution will give you the right result, but with one query for each project. Use\nannotate to do the whole thing in a single query.\nfrom django.db.models import Sum\n\nannotated_projects = Project.objects.all().annotate(cost_sum=Sum('cost__cost'))\nfor project in annotated_projects:\n print project.title, project.cost_sum\n\n", "Here's one way to do it. There may be a more efficient way to write the get_total_cost function... but this should work.\nModels:\nclass Project(models.Model):\n title = models.CharField(max_length=150)\n url = models.URLField()\n manager = models.ForeignKey(User)\n\n def get_total_cost(self):\n tot = 0\n for cost in Cost.objects.filter(project=self):\n tot += cost.cost\n return tot\n\nclass Cost(models.Model):\n project = models.ForeignKey(Project)\n cost = models.FloatField()\n date = models.DateField()\n\nView:\nfrom mypm.costs.models import Project, Cost\nfrom django.shortcuts import render_to_response\nfrom django.db.models import Avg, Sum\n\ndef index(request):\n return render_to_response('index.html',{'projects',Project.objects.all()},context_instance=RequestContext(request))\n\nTemplate:\n{% for project in projects %}\n<p>{{project.title}}: {{project.get_total_cost}}</p>\n{% endfor %}\n\nThis is pretty basic stuff. \nTake some time and go through the Django tutorials and documentation.\n", "Try using aggregate.\nfrom django.db.models import Sum\n\nfor project in Projects.objects.all():\n print project, project.cost_set.all().aggregate(sum_of_cost=Sum('cost'))['sum_of_cost'] or 0\n\n" ]
[ 5, 3, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002828343_django_python.txt
Q: overriding callbacks avoiding attribute pollution I've a class that has some callbacks and its own interface, something like: class Service: def __init__(self): connect("service_resolved", self.service_resolved) def service_resolved(self, a,b c): ''' This function is called when it's triggered service resolved signal and has a lot of parameters''' the connect function is for example the gtkwidget.connect, but I want that this connection is something more general, so I've decided to use a "twisted like" approach: class MyService(Service): def my_on_service_resolved(self, little_param): ''' it's a decorated version of srvice_resolved ''' def service_resolved(self,a,b,c): super(MyService,self).service_resolved(a,b,c) little_param = "something that's obtained from a,b,c" self.my_on_service_resolved(little_param) So I can use MyService by overriding my_on_service_resolved. The problem is the "attributes" pollution. In the real implementation, Service has some attributes that can accidentally be overriden in MyService and those who subclass MyService. How can I avoid attribute pollution? What I've thought is a "wrapper" like approach but I don't know if it's a good solution: class WrapperService(): def __init__(self): self._service = service_resolved # how to override self._service.service_resolved callback? def my_on_service_resolved(self,param): ''' ''' A: Avoiding accidental clashes with derived classes is the reason the "double-leading-underscore" naming approach exists: if you name an attribute in class Service __foo, the Python compiler will internally "mangle" that name to _Service__foo, making accidental clashes unlikely. Alas, not impossible: a subclass might also be named Service (and live in another module) and also have its own __foo attribute... which would be named-mangled exactly the same way, resulting in a conflict again. Ameliorations include naming base classes BaseService and the like, exploiting the fact that a derived class is very unlikely to be named Basewhatever. But, in the end, there's no alternative to clearly documenting a convention such as this (at least if subclasses are going to be written by programmers with little Python experience). I don't think the "accidental clash" issue is enough to force you to forego subclassing entirely (in favor of using wrapping exclusively), which is basically the only way to avoid accidental name clashes for certain. The approach you call "twisted-like" (and is actually a case of the Template Method design pattern) is quite viable, and a mix of convention for naming, and documentation of your design choices, in real-life practice proves sufficient to avoid its "clash" risks.
overriding callbacks avoiding attribute pollution
I've a class that has some callbacks and its own interface, something like: class Service: def __init__(self): connect("service_resolved", self.service_resolved) def service_resolved(self, a,b c): ''' This function is called when it's triggered service resolved signal and has a lot of parameters''' the connect function is for example the gtkwidget.connect, but I want that this connection is something more general, so I've decided to use a "twisted like" approach: class MyService(Service): def my_on_service_resolved(self, little_param): ''' it's a decorated version of srvice_resolved ''' def service_resolved(self,a,b,c): super(MyService,self).service_resolved(a,b,c) little_param = "something that's obtained from a,b,c" self.my_on_service_resolved(little_param) So I can use MyService by overriding my_on_service_resolved. The problem is the "attributes" pollution. In the real implementation, Service has some attributes that can accidentally be overriden in MyService and those who subclass MyService. How can I avoid attribute pollution? What I've thought is a "wrapper" like approach but I don't know if it's a good solution: class WrapperService(): def __init__(self): self._service = service_resolved # how to override self._service.service_resolved callback? def my_on_service_resolved(self,param): ''' '''
[ "Avoiding accidental clashes with derived classes is the reason the \"double-leading-underscore\" naming approach exists: if you name an attribute in class Service __foo, the Python compiler will internally \"mangle\" that name to _Service__foo, making accidental clashes unlikely. Alas, not impossible: a subclass might also be named Service (and live in another module) and also have its own __foo attribute... which would be named-mangled exactly the same way, resulting in a conflict again. Ameliorations include naming base classes BaseService and the like, exploiting the fact that a derived class is very unlikely to be named Basewhatever. But, in the end, there's no alternative to clearly documenting a convention such as this (at least if subclasses are going to be written by programmers with little Python experience).\nI don't think the \"accidental clash\" issue is enough to force you to forego subclassing entirely (in favor of using wrapping exclusively), which is basically the only way to avoid accidental name clashes for certain. The approach you call \"twisted-like\" (and is actually a case of the Template Method design pattern) is quite viable, and a mix of convention for naming, and documentation of your design choices, in real-life practice proves sufficient to avoid its \"clash\" risks.\n" ]
[ 3 ]
[]
[]
[ "asynchronous", "python" ]
stackoverflow_0002828349_asynchronous_python.txt
Q: Python and hebrew encoding/decoding error I have sqlite database which I would like to insert values in Hebrew to I am keep getting the following error : UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128) my code is as following : runsql(u'INSERT into personal values(%(ID)d,%(name)s)' % {'ID':1,'name':fabricate_hebrew_name()}) def fabricate_hebrew_name(): hebrew_names = [u'ירדן',u'יפה',u'תמי',u'ענת',u'רבקה',u'טלי',u'גינה',u'דנה',u'ימית',u'אלונה',u'אילן',u'אדם',u'חווה'] return random.sample(names,1)[0].encode('utf-8') note: runsql executing the query on the sqlite database fabricate_hebrew_name() should return a string which could be used in my SQL query. any help is much appreciated. A: You are passing the fabricated names into the string formatting parameter for a Unicode string. Ideally, the strings passed this way should also be Unicode. But fabricate_hebrew_name isn't returning Unicode - it is returned UTF-8 encoded string, which isn't the same. So, get rid of the call the encode('utf-8') and see whether that helps. The next question is what type runsql is expecting. If it is expecting Unicode, no problem. If it is expecting an ASCII-encoded string, then you will have problems because the Hebrew is not ASCII. In the unlikely case it is expecting a UTF-8 encoded-string, then that is the time to convert it - after the substitution is done. In another answer, Ignacio Vazquez-Abrams warns against string interpolation in queries. The concept here is that instead of doing the string substitution, using the % operator, you should generally use a parameterised query, and pass the Hebrew strings as parameters to it. This may have some advantages in query optimisation and security against SQL injection. Example # -*- coding: utf-8 -*- import sqlite3 # create db in memory conn = sqlite3.connect(":memory:") cur = conn.cursor() cur.execute("CREATE TABLE personal (" "id INTEGER PRIMARY KEY," "name VARCHAR(42) NOT NULL)") # insert random name import random fabricate_hebrew_name = lambda: random.choice([ u'ירדן',u'יפה',u'תמי',u'ענת', u'רבקה',u'טלי',u'גינה',u'דנה',u'ימית', u'אלונה',u'אילן',u'אדם',u'חווה']) cur.execute("INSERT INTO personal VALUES(" "NULL, :name)", dict(name=fabricate_hebrew_name())) conn.commit() id, name = cur.execute("SELECT * FROM personal").fetchone() print id, name # -> 1 אלונה A: You should not encode manually, and you should not use string interpolation for queries.
Python and hebrew encoding/decoding error
I have sqlite database which I would like to insert values in Hebrew to I am keep getting the following error : UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128) my code is as following : runsql(u'INSERT into personal values(%(ID)d,%(name)s)' % {'ID':1,'name':fabricate_hebrew_name()}) def fabricate_hebrew_name(): hebrew_names = [u'ירדן',u'יפה',u'תמי',u'ענת',u'רבקה',u'טלי',u'גינה',u'דנה',u'ימית',u'אלונה',u'אילן',u'אדם',u'חווה'] return random.sample(names,1)[0].encode('utf-8') note: runsql executing the query on the sqlite database fabricate_hebrew_name() should return a string which could be used in my SQL query. any help is much appreciated.
[ "You are passing the fabricated names into the string formatting parameter for a Unicode string. Ideally, the strings passed this way should also be Unicode.\nBut fabricate_hebrew_name isn't returning Unicode - it is returned UTF-8 encoded string, which isn't the same.\nSo, get rid of the call the encode('utf-8') and see whether that helps.\nThe next question is what type runsql is expecting. If it is expecting Unicode, no problem. If it is expecting an ASCII-encoded string, then you will have problems because the Hebrew is not ASCII. In the unlikely case it is expecting a UTF-8 encoded-string, then that is the time to convert it - after the substitution is done.\nIn another answer, Ignacio Vazquez-Abrams warns against string interpolation in queries. The concept here is that instead of doing the string substitution, using the % operator, you should generally use a parameterised query, and pass the Hebrew strings as parameters to it. This may have some advantages in query optimisation and security against SQL injection.\nExample\n# -*- coding: utf-8 -*-\nimport sqlite3\n\n# create db in memory\nconn = sqlite3.connect(\":memory:\")\ncur = conn.cursor()\ncur.execute(\"CREATE TABLE personal (\"\n \"id INTEGER PRIMARY KEY,\"\n \"name VARCHAR(42) NOT NULL)\")\n\n# insert random name\nimport random\nfabricate_hebrew_name = lambda: random.choice([\n u'ירדן',u'יפה',u'תמי',u'ענת', u'רבקה',u'טלי',u'גינה',u'דנה',u'ימית',\n u'אלונה',u'אילן',u'אדם',u'חווה'])\n\ncur.execute(\"INSERT INTO personal VALUES(\"\n \"NULL, :name)\", dict(name=fabricate_hebrew_name()))\nconn.commit()\n\nid, name = cur.execute(\"SELECT * FROM personal\").fetchone()\nprint id, name\n# -> 1 אלונה\n\n", "You should not encode manually, and you should not use string interpolation for queries.\n" ]
[ 4, 2 ]
[]
[]
[ "encoding", "hebrew", "python", "sqlite", "unicode" ]
stackoverflow_0002828537_encoding_hebrew_python_sqlite_unicode.txt
Q: How can I load a sql "dump" file into sql alchemy I have a large sql dump file ... with multiple CREATE TABLE and INSERT INTO statements. Is there any way to load these all into a SQLAlchemy sqlite database at once. I plan to use the introspected ORM from sqlsoup after I've created the tables. However, when I use the engine.execute() method it complains: sqlite3.Warning: You can only execute one statement at a time. Is there a way to work around this issue. Perhaps splitting the file with a regexp or some kind of parser, but I don't know enough SQL to get all of the cases for the regexp. Any help would be greatly appreciated. Will EDIT: Since this seems important ... The dump file was created with a MySQL database and so it has quite a few commands/syntax that sqlite3 does not understand correctly. A: "or some kind of parser" I've found MySQL to be a great parser for MySQL dump files :) You said it yourself: "so it has quite a few commands/syntax that sqlite3 does not understand correctly." Clearly then, SQLite is not the tool for this task. As for your particular error: without context (i.e. a traceback) there's nothing I can say about it. Martelli or Skeet could probably reach across time and space and read your interpreter's mind, but me, not so much. A: The SQL recognized by MySQL and the SQL in SQLite are quite different. I suggest dumping the data of each table individually, then loading the data into equivalent tables in SQLite. Create the tables in SQLite manually, using a subset of the "CREATE TABLE" commands given in your raw-dump file.
How can I load a sql "dump" file into sql alchemy
I have a large sql dump file ... with multiple CREATE TABLE and INSERT INTO statements. Is there any way to load these all into a SQLAlchemy sqlite database at once. I plan to use the introspected ORM from sqlsoup after I've created the tables. However, when I use the engine.execute() method it complains: sqlite3.Warning: You can only execute one statement at a time. Is there a way to work around this issue. Perhaps splitting the file with a regexp or some kind of parser, but I don't know enough SQL to get all of the cases for the regexp. Any help would be greatly appreciated. Will EDIT: Since this seems important ... The dump file was created with a MySQL database and so it has quite a few commands/syntax that sqlite3 does not understand correctly.
[ "\"or some kind of parser\"\nI've found MySQL to be a great parser for MySQL dump files :)\nYou said it yourself: \"so it has quite a few commands/syntax that sqlite3 does not understand correctly.\" Clearly then, SQLite is not the tool for this task.\nAs for your particular error: without context (i.e. a traceback) there's nothing I can say about it. Martelli or Skeet could probably reach across time and space and read your interpreter's mind, but me, not so much.\n", "The SQL recognized by MySQL and the SQL in SQLite are quite different. I suggest dumping the data of each table individually, then loading the data into equivalent tables in SQLite.\nCreate the tables in SQLite manually, using a subset of the \"CREATE TABLE\" commands given in your raw-dump file.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0002824244_python_sql_sqlalchemy.txt
Q: Looking to reimplement build toolchain from bash/grep/sed/awk/(auto)make/configure to something more sane (e.g. boost.build, etc) I currently maintain a few boxes that house a loosely related cornucopia of coding projects, databases and repositories (ranging from a homebrew *nix distro to my class notes), maintained by myself and a few equally pasty-skinned nerdy friends (all of said cornucopia is stored in SVN). The vast majority of our code is in C/C++/assembly (a few utilities are in python/perl/php, we're not big java fans), compiled in gcc. Our build toolchain typically consists of a hodgepodge of make, bash, grep, sed and awk. Recent discovery of a Makefile nearly as long as the program it builds (as well as everyone's general anxiety with my cryptic sed and awking) has motivated me to seek a less painful build system. Currently, the strongest candidate I've come across is Boost Build/Bjam as a replacement for GNU make and python as a replacement for our build-related bash scripts. Are there any other C/C++/asm build systems out there worth looking into? I've browsed through a number of make alternatives, but I haven't found any that are developed by names I know aside from Boost's. (I should note that an ability to easily extract information from svn commandline tools such as svnversion is important, as well as enough flexibility to configure for builds of asm projects as easily as c/c++ projects) A: We've started using CMake here at work recently. I've been pretty happy with it so far. A: scons or cmake. Both "cross platform" - enable compiling on Windows and Linux. Cmake now very popular (for example boost uses it). It creates native build files for each platform - Makefiles (for Linux), VC++ projects (for Visual Studio) from custom files (CMakeList.txt). In can also create Eclipse projects, KDevelop projects etc. Since it creates native build files, you can continue using all features you're used for. For example, ccache/colorgcc/distcc for Makefiles or Visual Assist X for Visual Studio. We use it our project and are happy with it - automatic dependencies, easy syntax, robust builds. Scons is python bases system, which perform the builds by itself. It's IMHO less popular, and still slow for large project. But for msmall to medium project maybe good alternative. A: You could use python-based build system, too -- http://code.google.com/p/waf/
Looking to reimplement build toolchain from bash/grep/sed/awk/(auto)make/configure to something more sane (e.g. boost.build, etc)
I currently maintain a few boxes that house a loosely related cornucopia of coding projects, databases and repositories (ranging from a homebrew *nix distro to my class notes), maintained by myself and a few equally pasty-skinned nerdy friends (all of said cornucopia is stored in SVN). The vast majority of our code is in C/C++/assembly (a few utilities are in python/perl/php, we're not big java fans), compiled in gcc. Our build toolchain typically consists of a hodgepodge of make, bash, grep, sed and awk. Recent discovery of a Makefile nearly as long as the program it builds (as well as everyone's general anxiety with my cryptic sed and awking) has motivated me to seek a less painful build system. Currently, the strongest candidate I've come across is Boost Build/Bjam as a replacement for GNU make and python as a replacement for our build-related bash scripts. Are there any other C/C++/asm build systems out there worth looking into? I've browsed through a number of make alternatives, but I haven't found any that are developed by names I know aside from Boost's. (I should note that an ability to easily extract information from svn commandline tools such as svnversion is important, as well as enough flexibility to configure for builds of asm projects as easily as c/c++ projects)
[ "We've started using CMake here at work recently. I've been pretty happy with it so far.\n", "scons or cmake.\nBoth \"cross platform\" - enable compiling on Windows and Linux.\nCmake now very popular (for example boost uses it). It creates native build files for each platform - Makefiles (for Linux), VC++ projects (for Visual Studio) from custom files (CMakeList.txt). In can also create Eclipse projects, KDevelop projects etc. Since it creates native build files, you can continue using all features you're used for. For example, ccache/colorgcc/distcc for Makefiles or Visual Assist X for Visual Studio.\nWe use it our project and are happy with it - automatic dependencies, easy syntax, robust builds. \nScons is python bases system, which perform the builds by itself. It's IMHO less popular, and still slow for large project. But for msmall to medium project maybe good alternative. \n", "You could use python-based build system, too -- http://code.google.com/p/waf/\n" ]
[ 2, 2, 1 ]
[]
[]
[ "bash", "boost", "c++", "makefile", "python" ]
stackoverflow_0002819558_bash_boost_c++_makefile_python.txt
Q: Django syncdb not making tables for my app It used to work, and now it doesn't. python manage.py syncdb no longer makes tables for my app. From settings.py: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mysite.myapp', 'django.contrib.admin', ) What could I be doing wrong? The break appeared to coincide with editing this model in models.py, but that could be total coincidence. I commented out the lines I changed, and it still doesn't work. class MyUser(models.Model): user = models.ForeignKey(User, unique=True) takingReqSets = models.ManyToManyField(RequirementSet, blank=True) takingTerms = models.ManyToManyField(Term, blank=True) takingCourses = models.ManyToManyField(Course, through=TakingCourse, blank=True) school = models.ForeignKey(School) # minCreditsPerTerm = models.IntegerField(blank=True) # maxCreditsPerTerm = models.IntegerField(blank=True) # optimalCreditsPerTerm = models.IntegerField(blank=True) UPDATE: When I run python manage.py loadddata initial_data, it gives an error: DeserializationError: Invalid model identifier: myapp.SomeModel Loading this data had worked fine before. This error is thrown on the very first data object in the data file. SOLVED: Fixed by removing this line: from stringprep import bl A: I'd bet that the SomeModel model you mention above (not necessarily MyUser) has got a problem with it which means it can't be imported by loaddata. If not SomeModel, then a model in the same models.py that SomeModel is defined in. Have you tried ./manage.py validate ? Even if that says all models are fine, sometimes if there's an error in a models.py of an an app, the entire app becomes 'invisible' to manage.py. I can't say I know why this is the case, but seems to ring a bell.
Django syncdb not making tables for my app
It used to work, and now it doesn't. python manage.py syncdb no longer makes tables for my app. From settings.py: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mysite.myapp', 'django.contrib.admin', ) What could I be doing wrong? The break appeared to coincide with editing this model in models.py, but that could be total coincidence. I commented out the lines I changed, and it still doesn't work. class MyUser(models.Model): user = models.ForeignKey(User, unique=True) takingReqSets = models.ManyToManyField(RequirementSet, blank=True) takingTerms = models.ManyToManyField(Term, blank=True) takingCourses = models.ManyToManyField(Course, through=TakingCourse, blank=True) school = models.ForeignKey(School) # minCreditsPerTerm = models.IntegerField(blank=True) # maxCreditsPerTerm = models.IntegerField(blank=True) # optimalCreditsPerTerm = models.IntegerField(blank=True) UPDATE: When I run python manage.py loadddata initial_data, it gives an error: DeserializationError: Invalid model identifier: myapp.SomeModel Loading this data had worked fine before. This error is thrown on the very first data object in the data file. SOLVED: Fixed by removing this line: from stringprep import bl
[ "I'd bet that the SomeModel model you mention above (not necessarily MyUser) has got a problem with it which means it can't be imported by loaddata. If not SomeModel, then a model in the same models.py that SomeModel is defined in. \nHave you tried ./manage.py validate ? Even if that says all models are fine, sometimes if there's an error in a models.py of an an app, the entire app becomes 'invisible' to manage.py. I can't say I know why this is the case, but seems to ring a bell.\n" ]
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002829149_django_django_models_python.txt
Q: python convert 12 bit image encoded in a string to 8 bit png I have a string that is read from a usb apogee camera that is a 12-bit grayscale image with the 12-bits each occupying the lowest 12 bits of 16-bits words. I want to create a 8-bit png from this string by ignoring the lowest 4 bits. I can convert it to a 16-bit image where the highest 4 bits are always zero using PIL with import Image #imageStr is the image string #imageSize is the image size img=Image.fromstring("I", imageSize, imageStr, "raw", "I;16", 0,1) img.save("MyImage.png", "PNG") Anyway can I do something similar to create a 8-bit image without completely unpacking the string doing arithmetic and making a new string? Edit: Wumps comment about converting an image gave me an idea, and I did it by img = img.point(lambda i: i * 16, "L") #shifts by 4 bits and converts to 8-bit image. Thanks Wump A: Wump's comment about converting an image gave me an idea, and I did it by #shifts by 4 bits and converts to 8-bit image img = img.point(lambda i: i * 16, "L") Thanks Wump A: The only way I know how to do it would be: data = numpy.fromstring(imageStr, numpy.uint16) data >>= 4 # shift out four bits data = numpy.array(data, dtype=numpy.uint8) img = Image.fromarray(data.reshape(imageSize)) In principe, PIL can convert images this way: img = img.convert("L") But the problem is that it has no way to reduce the precision to 8 bits (AFAIK), so everything will be clipped to 255 :) Edit: removed intermediate string conversion, it's going directly from numpy to PIL now
python convert 12 bit image encoded in a string to 8 bit png
I have a string that is read from a usb apogee camera that is a 12-bit grayscale image with the 12-bits each occupying the lowest 12 bits of 16-bits words. I want to create a 8-bit png from this string by ignoring the lowest 4 bits. I can convert it to a 16-bit image where the highest 4 bits are always zero using PIL with import Image #imageStr is the image string #imageSize is the image size img=Image.fromstring("I", imageSize, imageStr, "raw", "I;16", 0,1) img.save("MyImage.png", "PNG") Anyway can I do something similar to create a 8-bit image without completely unpacking the string doing arithmetic and making a new string? Edit: Wumps comment about converting an image gave me an idea, and I did it by img = img.point(lambda i: i * 16, "L") #shifts by 4 bits and converts to 8-bit image. Thanks Wump
[ "Wump's comment about converting an image gave me an idea, and I did it by\n#shifts by 4 bits and converts to 8-bit image\nimg = img.point(lambda i: i * 16, \"L\") \n\nThanks Wump\n", "The only way I know how to do it would be:\ndata = numpy.fromstring(imageStr, numpy.uint16)\ndata >>= 4 # shift out four bits\ndata = numpy.array(data, dtype=numpy.uint8)\nimg = Image.fromarray(data.reshape(imageSize))\n\nIn principe, PIL can convert images this way:\nimg = img.convert(\"L\")\n\nBut the problem is that it has no way to reduce the precision to 8 bits (AFAIK), so everything will be clipped to 255 :)\nEdit: removed intermediate string conversion, it's going directly from numpy to PIL now\n" ]
[ 2, 1 ]
[]
[]
[ "bit", "image", "python" ]
stackoverflow_0002816144_bit_image_python.txt
Q: SOCKS in C/C++ or another language? How do i add SOCKS support to my application? and where can i get the libs? any help appreciated thanks A: You could try Boost.Asio library. It contains an example with SOCKS4 protocol implementation.
SOCKS in C/C++ or another language?
How do i add SOCKS support to my application? and where can i get the libs? any help appreciated thanks
[ "You could try Boost.Asio library. It contains an example with SOCKS4 protocol implementation.\n" ]
[ 6 ]
[ "VC++ has extensive support if you want to try on Windows. \nGoogle \"Windows sockets for beginners msdn\", great info for windows sockets...\nIf linux, try C sockets by beej... Just google beej's guide for sockets... \n" ]
[ -3 ]
[ "c", "c++", "perl", "python", "socks" ]
stackoverflow_0002829637_c_c++_perl_python_socks.txt
Q: What's the scope of a variable initialized in an if statement? I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly: if __name__ == '__main__': x = 1 print x In other languages I've worked in, this code would throw an exception, as the x variable is local to the if statement and should not exist outside of it. But this code executes, and prints 1. Can anyone explain this behavior? Are all variables created in a module global/available to the entire module? A: Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module. (Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.) A: Yes, they're in the same "local scope", and actually code like this is common in Python: if condition: x = 'something' else: x = 'something else' use(x) Note that x isn't declared or initialized before the condition, like it would be in C or Java, for example. In other words, Python does not have block-level scopes. Be careful, though, with examples such as if False: x = 3 print(x) which would clearly raise a NameError exception. A: Scope in python follows this order: Search the local scope Search the scope of any enclosing functions Search the global scope Search the built-ins (source) Notice that if and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an if block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown. A: As Eli said, Python doesn't require variable declaration. In C you would say: int x; if(something) x = 1; else x = 2; but in Python declaration is implicit, so when you assign to x it is automatically declared. It's because Python is dynamically typed - it wouldn't work in a statically typed language, because depending on the path used, a variable might be used without being declared. This would be caught at compile time in a statically typed language, but with a dynamically typed language it's allowed. The only reason that a statically typed language is limited to having to declare variables outside of if statements in because of this problem. Embrace the dynamic! A: Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost "block". It is as though you declared int x at the top of the function (or class, or module), except that in Python you don't have to declare variables. Note that the existence of the variable x is checked only at runtime -- that is, when you get to the print x statement. If __name__ didn't equal "__main__" then you would get an exception: NameError: name 'x' is not defined. A: Yes. It is also true for for scope. But not functions of course. In your example: if the condition in the if statement is false, x will not be defined though. A: you're executing this code from command line therefore if conditions is true and x is set. Compare: >>> if False: y = 42 >>> y Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> y NameError: name 'y' is not defined
What's the scope of a variable initialized in an if statement?
I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly: if __name__ == '__main__': x = 1 print x In other languages I've worked in, this code would throw an exception, as the x variable is local to the if statement and should not exist outside of it. But this code executes, and prints 1. Can anyone explain this behavior? Are all variables created in a module global/available to the entire module?
[ "Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.\n(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)\n", "Yes, they're in the same \"local scope\", and actually code like this is common in Python:\nif condition:\n x = 'something'\nelse:\n x = 'something else'\n\nuse(x)\n\nNote that x isn't declared or initialized before the condition, like it would be in C or Java, for example.\nIn other words, Python does not have block-level scopes. Be careful, though, with examples such as\nif False:\n x = 3\nprint(x)\n\nwhich would clearly raise a NameError exception.\n", "Scope in python follows this order:\n\nSearch the local scope\nSearch the scope of any enclosing functions\nSearch the global scope\nSearch the built-ins\n\n(source)\nNotice that if and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an if block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.\n", "As Eli said, Python doesn't require variable declaration. In C you would say:\nint x;\nif(something)\n x = 1;\nelse\n x = 2;\n\nbut in Python declaration is implicit, so when you assign to x it is automatically declared. It's because Python is dynamically typed - it wouldn't work in a statically typed language, because depending on the path used, a variable might be used without being declared. This would be caught at compile time in a statically typed language, but with a dynamically typed language it's allowed.\nThe only reason that a statically typed language is limited to having to declare variables outside of if statements in because of this problem. Embrace the dynamic!\n", "Unlike languages such as C, a Python variable is in scope for the whole of the function (or class, or module) where it appears, not just in the innermost \"block\". It is as though you declared int x at the top of the function (or class, or module), except that in Python you don't have to declare variables.\nNote that the existence of the variable x is checked only at runtime -- that is, when you get to the print x statement. If __name__ didn't equal \"__main__\" then you would get an exception: NameError: name 'x' is not defined.\n", "Yes. It is also true for for scope. But not functions of course.\nIn your example: if the condition in the if statement is false, x will not be defined though.\n", "you're executing this code from command line therefore if conditions is true and x is set. Compare:\n>>> if False:\n y = 42\n\n\n>>> y\nTraceback (most recent call last):\n File \"<pyshell#6>\", line 1, in <module>\n y\nNameError: name 'y' is not defined\n\n" ]
[ 465, 155, 48, 15, 15, 6, 3 ]
[]
[]
[ "if_statement", "local_variables", "python", "scope", "variables" ]
stackoverflow_0002829528_if_statement_local_variables_python_scope_variables.txt
Q: Organizing a random list of objects in Python So I have a list that I want to convert to a list that contains a list for each group of objects. ie ['objA.attr1', 'objC', 'objA.attr55', 'objB.attr4'] would return [['objA.attr1', 'objA.attr55'], ['objC'], ['objB.attr4']] currently this is what I use: givenList = ['a.attr1', 'b', 'a.attr55', 'c.attr4'] trgList = [] objNames = [] for val in givenList: obj = val.split('.')[0] if obj in objNames: id = objNames.index(obj) trgList[id].append(val) else: objNames.append(obj) trgList.append([val]) #print trgList It seems to run a decent speed when the original list has around 100,000 ids... but I am curious if there is a better way to do this. Order of the objects or attributes does not matter. Any ideas? A: This needs to be better defined: what do you do when there is no property? What order do you want the final list as? What about duplicates? A general algorithm would be to use a multi-map: a map that has multiple values per key. You will then scan through the original list, separate each element into an "object" and "property", and then add a key-value pair for the object and property. At the end of this cycle, you will have a mapping from objects to set of properties. You can then iterate over this to build your final list. You can use a third-party multimap or implement yourself by mapping into a sequence. You might want to create a dummy property for cases when the object does not have a property.
Organizing a random list of objects in Python
So I have a list that I want to convert to a list that contains a list for each group of objects. ie ['objA.attr1', 'objC', 'objA.attr55', 'objB.attr4'] would return [['objA.attr1', 'objA.attr55'], ['objC'], ['objB.attr4']] currently this is what I use: givenList = ['a.attr1', 'b', 'a.attr55', 'c.attr4'] trgList = [] objNames = [] for val in givenList: obj = val.split('.')[0] if obj in objNames: id = objNames.index(obj) trgList[id].append(val) else: objNames.append(obj) trgList.append([val]) #print trgList It seems to run a decent speed when the original list has around 100,000 ids... but I am curious if there is a better way to do this. Order of the objects or attributes does not matter. Any ideas?
[ "This needs to be better defined: what do you do when there is no property? What order do you want the final list as? What about duplicates?\nA general algorithm would be to use a multi-map: a map that has multiple values per key.\nYou will then scan through the original list, separate each element into an \"object\" and \"property\", and then add a key-value pair for the object and property. At the end of this cycle, you will have a mapping from objects to set of properties. You can then iterate over this to build your final list.\nYou can use a third-party multimap or implement yourself by mapping into a sequence. \nYou might want to create a dummy property for cases when the object does not have a property.\n" ]
[ 0 ]
[]
[]
[ "grouping", "python", "sorting" ]
stackoverflow_0002829758_grouping_python_sorting.txt
Q: Django: Determining if a user has voted or not I have a long list of links that I spit out using the below code, total votes, submitted by, the usual stuff but I am not 100% on how to determine if the currently logged in user has voted on a link or not. I know how to do this from within my view but do I need to alter my below view code or can I make use of the way templates work to determine it? I have read Django Vote Up/Down method but I don't quite understand what's going on ( and don't need any ofjavascriptery). Models (snippet): class Link(models.Model): category = models.ForeignKey(Category, blank=False, default=1) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) url = models.URLField(max_length=1024, unique=True, verify_exists=True) name = models.CharField(max_length=512) def __unicode__(self): return u'%s (%s)' % (self.name, self.url) class Vote(models.Model): link = models.ForeignKey(Link) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'%s vote for %s' % (self.user, self.link) Views (snippet): def hot(request): links = Link.objects.select_related().annotate(votes=Count('vote')).order_by('-created') for link in links: delta_in_hours = (int(datetime.now().strftime("%s")) - int(link.created.strftime("%s"))) / 3600 link.popularity = ((link.votes - 1) / (delta_in_hours + 2)**1.5) if request.user.is_authenticated(): try: link.voted = Vote.objects.get(link=link, user=request.user) except Vote.DoesNotExist: link.voted = None links = sorted(links, key=lambda x: x.popularity, reverse=True) links = paginate(request, links, 15) return direct_to_template( request, template = 'links/link_list.html', extra_context = { 'links': links, }) The above view actually accomplishes what I need but in what I believe to be a horribly inefficient way. This causes the dreaded n+1 queries, as it stands that's 33 queries for a page containing just 29 links while originally I got away with just 4 queries. I would really prefer to do this using Django's ORM or at least .extra(). Any advice? EDIT @Gabriel Hurley I am trying to recreate your answer and I'm have mixed results, let me show ya what I got. views.py links = Link.objects.select_related().extra( select={ 'votes': 'COUNT(links_vote.id)', 'voted': 'SELECT COUNT(links_vote.id) FROM links_vote WHERE links_vote.user_id = 1 AND links_vote.link_id = links_link.id', }, tables = ['links_vote'] ) models.py class Vote(models.Model): link = models.ForeignKey(Link) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('link', 'user') def __unicode__(self): return u'%s vote for %s' % (self.user, self.link) But it is returning an error: subquery uses ungrouped column "links_link.id" from outer query LINE 1: ...E links_vote.user_id = 1 AND links_vote.link_id = links_link... The query that is generated looks something (exactly) like this: SELECT (SELECT COUNT(links_vote.id) FROM links_vote WHERE links_vote.user_id = 1 AND links_vote.link_id = links_link.id) AS "voted", "links_link"."id", "links_link"."category_id", "links_link"."user_id", "links_link"."created", "links_link"."modified", "links_link"."url", "links_link"."name", "links_category"."id", "links_category"."name", "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "links_link" INNER JOIN "links_category" ON ("links_link"."category_id" = "links_category"."id") INNER JOIN "auth_user" ON ("links_link"."user_id" = "auth_user"."id") , "links_vote" I am using PostgreSQL which I know loves GROUP BY but I am not 100% on how to correct this. EDIT 2 (Major Progress) links = Link.objects.select_related().annotate(votes=Count('vote')).extra( select={ #'voted': 'SELECT COUNT() FROM links_vote WHERE links_vote.user_id = %s AND links_vote.link_id = links_link.id' % (request.user.id), #'voted': '' % (request.user.id), #'voted': 'SELECT CASE WHEN links_vote.user_id = %s THEN 1 ELSE 0 END' % (request.user.id), #'voted': 'SELECT COUNT() FROM links_vote WHERE links_vote.link_id = links_link.id AND links_vote.user_id = %s' % (request.user.id), }, where=['links_link.id = links_vote.link_id'], ).order_by('-created') *This only works after applying a patch for a bug from here (http://code.djangoproject.com/ticket/11916) I am so close to finding that last piece I need to determine if a user has voted... A: I've dealt with this before and solved it with extra more or less like so: # annotate whether you've already voted on this item table = Vote._meta.db_table select = 'SELECT COUNT(id) FROM %s' %table where1 = 'WHERE ' + table + '.user_id = %s' where2 = 'AND ' + table + '.item_id = appname_item.id' items = items.extra( select={'votes':" ".join((select, where1, where2,))}, select_params=(request.user.id,) ) Effectively this takes a QuerySet of items and annotates each one with either a 0 or some number of votes. In my system I use unique_together = ('link', 'user') on Vote to make sure each user can only vote once, so the annotated data is either 0 or 1 (effectively boolean). It works quite well and avoids the n+1 problem.
Django: Determining if a user has voted or not
I have a long list of links that I spit out using the below code, total votes, submitted by, the usual stuff but I am not 100% on how to determine if the currently logged in user has voted on a link or not. I know how to do this from within my view but do I need to alter my below view code or can I make use of the way templates work to determine it? I have read Django Vote Up/Down method but I don't quite understand what's going on ( and don't need any ofjavascriptery). Models (snippet): class Link(models.Model): category = models.ForeignKey(Category, blank=False, default=1) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) url = models.URLField(max_length=1024, unique=True, verify_exists=True) name = models.CharField(max_length=512) def __unicode__(self): return u'%s (%s)' % (self.name, self.url) class Vote(models.Model): link = models.ForeignKey(Link) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'%s vote for %s' % (self.user, self.link) Views (snippet): def hot(request): links = Link.objects.select_related().annotate(votes=Count('vote')).order_by('-created') for link in links: delta_in_hours = (int(datetime.now().strftime("%s")) - int(link.created.strftime("%s"))) / 3600 link.popularity = ((link.votes - 1) / (delta_in_hours + 2)**1.5) if request.user.is_authenticated(): try: link.voted = Vote.objects.get(link=link, user=request.user) except Vote.DoesNotExist: link.voted = None links = sorted(links, key=lambda x: x.popularity, reverse=True) links = paginate(request, links, 15) return direct_to_template( request, template = 'links/link_list.html', extra_context = { 'links': links, }) The above view actually accomplishes what I need but in what I believe to be a horribly inefficient way. This causes the dreaded n+1 queries, as it stands that's 33 queries for a page containing just 29 links while originally I got away with just 4 queries. I would really prefer to do this using Django's ORM or at least .extra(). Any advice? EDIT @Gabriel Hurley I am trying to recreate your answer and I'm have mixed results, let me show ya what I got. views.py links = Link.objects.select_related().extra( select={ 'votes': 'COUNT(links_vote.id)', 'voted': 'SELECT COUNT(links_vote.id) FROM links_vote WHERE links_vote.user_id = 1 AND links_vote.link_id = links_link.id', }, tables = ['links_vote'] ) models.py class Vote(models.Model): link = models.ForeignKey(Link) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('link', 'user') def __unicode__(self): return u'%s vote for %s' % (self.user, self.link) But it is returning an error: subquery uses ungrouped column "links_link.id" from outer query LINE 1: ...E links_vote.user_id = 1 AND links_vote.link_id = links_link... The query that is generated looks something (exactly) like this: SELECT (SELECT COUNT(links_vote.id) FROM links_vote WHERE links_vote.user_id = 1 AND links_vote.link_id = links_link.id) AS "voted", "links_link"."id", "links_link"."category_id", "links_link"."user_id", "links_link"."created", "links_link"."modified", "links_link"."url", "links_link"."name", "links_category"."id", "links_category"."name", "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "links_link" INNER JOIN "links_category" ON ("links_link"."category_id" = "links_category"."id") INNER JOIN "auth_user" ON ("links_link"."user_id" = "auth_user"."id") , "links_vote" I am using PostgreSQL which I know loves GROUP BY but I am not 100% on how to correct this. EDIT 2 (Major Progress) links = Link.objects.select_related().annotate(votes=Count('vote')).extra( select={ #'voted': 'SELECT COUNT() FROM links_vote WHERE links_vote.user_id = %s AND links_vote.link_id = links_link.id' % (request.user.id), #'voted': '' % (request.user.id), #'voted': 'SELECT CASE WHEN links_vote.user_id = %s THEN 1 ELSE 0 END' % (request.user.id), #'voted': 'SELECT COUNT() FROM links_vote WHERE links_vote.link_id = links_link.id AND links_vote.user_id = %s' % (request.user.id), }, where=['links_link.id = links_vote.link_id'], ).order_by('-created') *This only works after applying a patch for a bug from here (http://code.djangoproject.com/ticket/11916) I am so close to finding that last piece I need to determine if a user has voted...
[ "I've dealt with this before and solved it with extra more or less like so:\n# annotate whether you've already voted on this item\ntable = Vote._meta.db_table\nselect = 'SELECT COUNT(id) FROM %s' %table\nwhere1 = 'WHERE ' + table + '.user_id = %s'\nwhere2 = 'AND ' + table + '.item_id = appname_item.id'\nitems = items.extra(\n select={'votes':\" \".join((select, where1, where2,))},\n select_params=(request.user.id,)\n )\n\nEffectively this takes a QuerySet of items and annotates each one with either a 0 or some number of votes. In my system I use unique_together = ('link', 'user') on Vote to make sure each user can only vote once, so the annotated data is either 0 or 1 (effectively boolean). It works quite well and avoids the n+1 problem.\n" ]
[ 2 ]
[]
[]
[ "django", "orm", "python", "sql" ]
stackoverflow_0002829896_django_orm_python_sql.txt
Q: name 'OptionGroup' is not defined This error is done strictly by following examples found on the docs. And you can't find any clarification about it anywhere, be it that long long docs page, google or stackoverflow. Plus, reading optparse.py shows OptionGroup is there, so that adds to the confusion. Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) >>> from optparse import OptionParser >>> outputGroup = OptionGroup(parser, 'Output handling') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'OptionGroup' is not defined I bet it will take less than 1 minute for someone to spot my error. :) Yes, that means I knew the answer, but since this took me so long to discover I wanted to "document" it here. A: Perhaps this is another example of why it is better to import modules than functions from modules. OptionGroup is defined in the module optparse. The command from optparse import OptionParser puts OptionParser in the global namespace, but neglects OptionGroup entirely. To fix the code, import the optparse module, and access its parts like so: import optparse parser = optparse.OptionParser() outputGroup = optparse.OptionGroup(parser, 'Output handling')
name 'OptionGroup' is not defined
This error is done strictly by following examples found on the docs. And you can't find any clarification about it anywhere, be it that long long docs page, google or stackoverflow. Plus, reading optparse.py shows OptionGroup is there, so that adds to the confusion. Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) >>> from optparse import OptionParser >>> outputGroup = OptionGroup(parser, 'Output handling') Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'OptionGroup' is not defined I bet it will take less than 1 minute for someone to spot my error. :) Yes, that means I knew the answer, but since this took me so long to discover I wanted to "document" it here.
[ "Perhaps this is another example of why it is better to import modules than functions from modules.\nOptionGroup is defined in the module optparse.\nThe command\nfrom optparse import OptionParser\nputs OptionParser in the global namespace, but neglects OptionGroup entirely.\nTo fix the code, import the optparse module, and access its parts like so:\nimport optparse\nparser = optparse.OptionParser()\noutputGroup = optparse.OptionGroup(parser, 'Output handling')\n\n" ]
[ 6 ]
[]
[]
[ "nameerror", "optparse", "python" ]
stackoverflow_0002830069_nameerror_optparse_python.txt
Q: Distinguishing between broadcasted messages and direct messages How can I distinguish between a broadcasted message and a direct message for my ip? I'm doing this in python. A: Basically what you need to do is create a raw socket, receive a datagram, and examine the destination address in the header. If that address is a broadcast address for the network adapter the socket is bound to, then you're golden. I don't know how to do this in Python, so I suggest looking for examples of raw sockets and go from there. Bear in mind, you will need root access to use raw sockets, and you had better be real careful if you plan on sending using a raw socket. As you might imagine, this will not be a fun thing to do. I suggest trying to find a way to avoid doing this.
Distinguishing between broadcasted messages and direct messages
How can I distinguish between a broadcasted message and a direct message for my ip? I'm doing this in python.
[ "Basically what you need to do is create a raw socket, receive a datagram, and examine the destination address in the header. If that address is a broadcast address for the network adapter the socket is bound to, then you're golden.\nI don't know how to do this in Python, so I suggest looking for examples of raw sockets and go from there. Bear in mind, you will need root access to use raw sockets, and you had better be real careful if you plan on sending using a raw socket.\nAs you might imagine, this will not be a fun thing to do. I suggest trying to find a way to avoid doing this.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002830326_python.txt
Q: How should I grab pairs from a list in python? Say I have a list that looks like this: ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10'] Using Python, how would I grab pairs from it, where each item is included in a pair with both the item before and after it? ['item1', 'item2'] ['item2', 'item3'] ['item3', 'item4'] ['item4', 'item5'] ['item5', 'item6'] ['item6', 'item7'] ['item7', 'item8'] ['item8', 'item9'] ['item9', 'item10'] Seems like something i could hack together, but I'm wondering if someone has an elegant solution they've used before? A: A quick and simple way of doing it would be something like: a = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10'] print zip(a, a[1:]) Which will produce the following: [('item1', 'item2'), ('item2', 'item3'), ('item3', 'item4'), ('item4', 'item5'), ('item5', 'item6'), ('item6', 'item7'), ('item7', 'item8'), ('item8', 'item9'), ('item9', 'item10')] A: Check out the pairwise recipe in the itertools documentation. A: This should do the trick: [(foo[i], foo[i+1]) for i in xrange(len(foo) - 1)]
How should I grab pairs from a list in python?
Say I have a list that looks like this: ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10'] Using Python, how would I grab pairs from it, where each item is included in a pair with both the item before and after it? ['item1', 'item2'] ['item2', 'item3'] ['item3', 'item4'] ['item4', 'item5'] ['item5', 'item6'] ['item6', 'item7'] ['item7', 'item8'] ['item8', 'item9'] ['item9', 'item10'] Seems like something i could hack together, but I'm wondering if someone has an elegant solution they've used before?
[ "A quick and simple way of doing it would be something like:\na = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9', 'item10']\n\nprint zip(a, a[1:])\n\nWhich will produce the following:\n[('item1', 'item2'), ('item2', 'item3'), ('item3', 'item4'), ('item4', 'item5'), ('item5', 'item6'), ('item6', 'item7'), ('item7', 'item8'), ('item8', 'item9'), ('item9', 'item10')]\n\n", "Check out the pairwise recipe in the itertools documentation.\n", "This should do the trick:\n[(foo[i], foo[i+1]) for i in xrange(len(foo) - 1)]\n\n" ]
[ 11, 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002829887_list_python.txt
Q: Identifying a function call in a python script line in runtime I have a python script that I run with 'exec'. When a function is called by the script, I would like it to know the line number and offset in line for that call. Here is an example. If my script is: foo1(); foo2(); foo1() foo3() And if I have code that prints (line,offset) in every function, I should get (0,0), (0,8), (0,16), (1,0) In most cases this can be easily done by getting the stack frame, because it contains the line number and the function name. The only problem is when there are two functions with the same name in a certain line. Unfortunately this is a common case for me. Any ideas? Ok it seems that changing the original code is the simplest solution. How would you solve things like if foo1(7) or foo1(6): or foo2(foo1(), foo1()) There are some not very elegant solutions for this, for example, automatically turning the previous example to: def curpos(pos, func): record_curpos(pos) return func curpos(foo2,0)(curpos(foo1,5)(), curpos(foo1,13)()) Let me know if you have simpler ideas. A: Python doesn't provide a lot of information about character offsets in a line. If you are using exec to execute the Python, then you could re-write the code mechanically before executing it to tell you what you want to know. For example, you could change the original code: foo1(); foo2(); foo1() foo3() into annotated code: curpos(1,0); foo1(); curpos(1,8); foo2(); curpos(1,16); foo1() curpos(2,0); foo3() and then exec the annotated code. Where curpos(line,char) records or prints the line and character information of that point in the original code. This will be much simpler than mucking around with stack frames. A: You could of course look at the line in the string, and try to find the function name, though that will not be reliable if they alias a function, e.g.: bar = foo2 foo1(); foo2() Otherwise it gets really hard. The coverage module does this, and Ned explained the particular technique in a blog post -- basically it involves rewriting the bytecode to separate out expressions into different (fake) line numbers. You might actually be able to use the coverage module itself for this.
Identifying a function call in a python script line in runtime
I have a python script that I run with 'exec'. When a function is called by the script, I would like it to know the line number and offset in line for that call. Here is an example. If my script is: foo1(); foo2(); foo1() foo3() And if I have code that prints (line,offset) in every function, I should get (0,0), (0,8), (0,16), (1,0) In most cases this can be easily done by getting the stack frame, because it contains the line number and the function name. The only problem is when there are two functions with the same name in a certain line. Unfortunately this is a common case for me. Any ideas? Ok it seems that changing the original code is the simplest solution. How would you solve things like if foo1(7) or foo1(6): or foo2(foo1(), foo1()) There are some not very elegant solutions for this, for example, automatically turning the previous example to: def curpos(pos, func): record_curpos(pos) return func curpos(foo2,0)(curpos(foo1,5)(), curpos(foo1,13)()) Let me know if you have simpler ideas.
[ "Python doesn't provide a lot of information about character offsets in a line.\nIf you are using exec to execute the Python, then you could re-write the code mechanically before executing it to tell you what you want to know. For example, you could change the original code:\nfoo1(); foo2(); foo1()\nfoo3()\n\ninto annotated code:\ncurpos(1,0); foo1(); curpos(1,8); foo2(); curpos(1,16); foo1()\ncurpos(2,0); foo3()\n\nand then exec the annotated code.\nWhere curpos(line,char) records or prints the line and character information of that point in the original code. This will be much simpler than mucking around with stack frames.\n", "You could of course look at the line in the string, and try to find the function name, though that will not be reliable if they alias a function, e.g.:\nbar = foo2\nfoo1(); foo2()\n\nOtherwise it gets really hard. The coverage module does this, and Ned explained the particular technique in a blog post -- basically it involves rewriting the bytecode to separate out expressions into different (fake) line numbers.\nYou might actually be able to use the coverage module itself for this.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "stack_frame", "stack_trace" ]
stackoverflow_0002829818_python_stack_frame_stack_trace.txt
Q: Infinite loop when adding a row to a list in a class in python3 I have a script which contains two classes. (I'm obviously deleting a lot of stuff that I don't believe is relevant to the error I'm dealing with.) The eventual task is to create a decision tree, as I mentioned in this question. Unfortunately, I'm getting an infinite loop, and I'm having difficulty identifying why. I've identified the line of code that's going haywire, but I would have thought the iterator and the list I'm adding to would be different objects. Is there some side effect of list's .append functionality that I'm not aware of? Or am I making some other blindingly obvious mistake? class Dataset: individuals = [] #Becomes a list of dictionaries, in which each dictionary is a row from the CSV with the headers as keys def field_set(self): #Returns a list of the fields in individuals[] that can be used to split the data (i.e. have more than one value amongst the individuals def classified(self, predicted_value): #Returns True if all the individuals have the same value for predicted_value def fields_exhausted(self, predicted_value): #Returns True if all the individuals are identical except for predicted_value def lowest_entropy_value(self, predicted_value): #Returns the field that will reduce <a href="http://en.wikipedia.org/wiki/Entropy_%28information_theory%29">entropy</a> the most def __init__(self, individuals=[]): and class Node: ds = Dataset() #The data that is associated with this Node links = [] #List of Nodes, the offspring Nodes of this node level = 0 #Tree depth of this Node split_value = '' #Field used to split out this Node from the parent node node_value = '' #Value used to split out this Node from the parent Node def split_dataset(self, split_value): #Splits the dataset into a series of smaller datasets, each of which has a unique value for split_value. Then creates subnodes to store these datasets. fields = [] #List of options for split_value amongst the individuals datasets = {} #Dictionary of Datasets, each one with a value from fields[] as its key for field in self.ds.field_set()[split_value]: #Populates the keys of fields[] fields.append(field) datasets[field] = Dataset() for i in self.ds.individuals: #Adds individuals to the datasets.dataset that matches their result for split_value datasets[i[split_value]].individuals.append(i) #<---Causes an infinite loop on the second hit for field in fields: #Creates subnodes from each of the datasets.Dataset options self.add_subnode(datasets[field],split_value,field) def add_subnode(self, dataset, split_value='', node_value=''): def __init__(self, level, dataset=Dataset()): My initialisation code is currently: if __name__ == '__main__': filename = (sys.argv[1]) #Takes in a CSV file predicted_value = "# class" #Identifies the field from the CSV file that should be predicted base_dataset = parse_csv(filename) #Turns the CSV file into a list of lists parsed_dataset = individual_list(base_dataset) #Turns the list of lists into a list of dictionaries root = Node(0, Dataset(parsed_dataset)) #Creates a root node, passing it the full dataset root.split_dataset(root.ds.lowest_entropy_value(predicted_value)) #Performs the first split, creating multiple subnodes n = root.links[0] n.split_dataset(n.ds.lowest_entropy_value(predicted_value)) #Attempts to split the first subnode. A: I suspect that you are appending to the same list that you are iterating over causing it to increase in size before the iterator can reach the end of it. Try iterating over a copy of the list instead: for i in list(self.ds.individuals): datasets[i[split_value]].individuals.append(i) A: class Dataset: individuals = [] Suspicious. Unless you want to have a static member list shared by all instances of Dataset you shouldn't do that. If you are setting self.individuals= something in the __init__, then you don't need to set individuals here too. def __init__(self, individuals=[]): Still suspicious. Are you assigning the individuals argument to self.individuals? If so, you are assigning the same individuals list, created at function definition time, to every Dataset that is created with a default argument. Add an item to one Dataset's list and all the others created without an explicit individuals argument will get that item too. Similarly: class Node: def __init__(self, level, dataset=Dataset()): All Node​s created without an explicit dataset argument will receive the exact same default Dataset instance. This is the mutable default argument problem and the kind of destructive-iterations it would produce would seem very likely to be causing your infinite loop.
Infinite loop when adding a row to a list in a class in python3
I have a script which contains two classes. (I'm obviously deleting a lot of stuff that I don't believe is relevant to the error I'm dealing with.) The eventual task is to create a decision tree, as I mentioned in this question. Unfortunately, I'm getting an infinite loop, and I'm having difficulty identifying why. I've identified the line of code that's going haywire, but I would have thought the iterator and the list I'm adding to would be different objects. Is there some side effect of list's .append functionality that I'm not aware of? Or am I making some other blindingly obvious mistake? class Dataset: individuals = [] #Becomes a list of dictionaries, in which each dictionary is a row from the CSV with the headers as keys def field_set(self): #Returns a list of the fields in individuals[] that can be used to split the data (i.e. have more than one value amongst the individuals def classified(self, predicted_value): #Returns True if all the individuals have the same value for predicted_value def fields_exhausted(self, predicted_value): #Returns True if all the individuals are identical except for predicted_value def lowest_entropy_value(self, predicted_value): #Returns the field that will reduce <a href="http://en.wikipedia.org/wiki/Entropy_%28information_theory%29">entropy</a> the most def __init__(self, individuals=[]): and class Node: ds = Dataset() #The data that is associated with this Node links = [] #List of Nodes, the offspring Nodes of this node level = 0 #Tree depth of this Node split_value = '' #Field used to split out this Node from the parent node node_value = '' #Value used to split out this Node from the parent Node def split_dataset(self, split_value): #Splits the dataset into a series of smaller datasets, each of which has a unique value for split_value. Then creates subnodes to store these datasets. fields = [] #List of options for split_value amongst the individuals datasets = {} #Dictionary of Datasets, each one with a value from fields[] as its key for field in self.ds.field_set()[split_value]: #Populates the keys of fields[] fields.append(field) datasets[field] = Dataset() for i in self.ds.individuals: #Adds individuals to the datasets.dataset that matches their result for split_value datasets[i[split_value]].individuals.append(i) #<---Causes an infinite loop on the second hit for field in fields: #Creates subnodes from each of the datasets.Dataset options self.add_subnode(datasets[field],split_value,field) def add_subnode(self, dataset, split_value='', node_value=''): def __init__(self, level, dataset=Dataset()): My initialisation code is currently: if __name__ == '__main__': filename = (sys.argv[1]) #Takes in a CSV file predicted_value = "# class" #Identifies the field from the CSV file that should be predicted base_dataset = parse_csv(filename) #Turns the CSV file into a list of lists parsed_dataset = individual_list(base_dataset) #Turns the list of lists into a list of dictionaries root = Node(0, Dataset(parsed_dataset)) #Creates a root node, passing it the full dataset root.split_dataset(root.ds.lowest_entropy_value(predicted_value)) #Performs the first split, creating multiple subnodes n = root.links[0] n.split_dataset(n.ds.lowest_entropy_value(predicted_value)) #Attempts to split the first subnode.
[ "I suspect that you are appending to the same list that you are iterating over causing it to increase in size before the iterator can reach the end of it. Try iterating over a copy of the list instead:\nfor i in list(self.ds.individuals):\n datasets[i[split_value]].individuals.append(i) \n\n", "class Dataset:\n individuals = []\n\nSuspicious. Unless you want to have a static member list shared by all instances of Dataset you shouldn't do that. If you are setting self.individuals= something in the __init__, then you don't need to set individuals here too.\n def __init__(self, individuals=[]):\n\nStill suspicious. Are you assigning the individuals argument to self.individuals? If so, you are assigning the same individuals list, created at function definition time, to every Dataset that is created with a default argument. Add an item to one Dataset's list and all the others created without an explicit individuals argument will get that item too.\nSimilarly:\nclass Node:\n def __init__(self, level, dataset=Dataset()):\n\nAll Node​s created without an explicit dataset argument will receive the exact same default Dataset instance.\nThis is the mutable default argument problem and the kind of destructive-iterations it would produce would seem very likely to be causing your infinite loop.\n" ]
[ 4, 4 ]
[]
[]
[ "infinite_loop", "python", "python_3.x" ]
stackoverflow_0002830953_infinite_loop_python_python_3.x.txt
Q: Tool (or combination of tools) for reproducible environments in Python I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team. I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java. A: virtualenv to create a contained virtual environment (prevent different versions of Python or Python packages from stomping on each other). There is increasing buzz from people moving to this tool. The author is the same as the older working-env.py mentioned by Aaron. pip to install packages inside a virtualenv. The traditional is easy_install as answered by S. Lott, but pip works better with virtualenv. easy_install still has features not found in pip though. scons as a build tool, although you won't need this if you stay purely Python. Fabric paste, or paver for deployment. buildbot for continuous integration. Bazaar, mercurial, or git for version control. Nose as an extension for unit testing. PyFit for FIT testing. A: I also work with both java and python. For python development the maven equivalent is setuptools (http://peak.telecommunity.com/DevCenter/setuptools). For web application development I use this in combination with paster (http://pythonpaste.org/) for the deployment process A: Other than easy_install? For our Linux servers, we use easy_install and yum. For our Windows development laptops, we use easy_install and a few MSI's for some projects. Most of the Python libraries we use are source-only, so we can use the same distribution on all boxes. If we could have a network shared device, we'd put them all there. Sadly, our infrastructure is kind of scattered, so we have to either move .TAR files around or redo the installs to rebuild the environments. In a few cases (e.g., PIL), we have to recompile and check the version numbers. A: You will want easy_setup to get the eggs (roughly what Maven calls an artifact). For setting up your environment, have a look at working-env.py Python is not compiled but you can put all files for a project in an egg. This is done with setuptools For CI, check this answer. A: We would be remiss not to also mention Paver, which was created by Kevin Dangoor of TurboGears fame. The project is still in alpha, but it appears very promising. A snippet from the project page: Paver is a Python-based build/distribution/deployment scripting tool along the lines of Make or Rake. What makes Paver unique is its integration with commonly used Python libraries. Common tasks that were easy before remain easy. More importantly, dealing with your applications specific needs and requirements is now much easier. A: I do exactly this with a combination of setuptools and Hudson. I know Hudson is a java app, but it can run Python stuff just fine. A: You might want to check our Devenv. It allows you to standardize the build environments for development, QA and UAT. It's free as in "free beer". HTH
Tool (or combination of tools) for reproducible environments in Python
I used to be a java developer and we used tools like ant or maven to manage our development/testing/UAT environments in a standardized way. This allowed us to handle library dependencies, setting OS variables, compiling, deploying, running unit tests, and all the required tasks. Also, the scripts generated guaranteed that all the environments were almost equally configured, and all the task were performed in the same way by all the members of the team. I'm starting to work in Python now and I'd like your advice in which tools should I use to accomplish the same as described for java.
[ "\nvirtualenv to create a contained virtual environment (prevent different versions of Python or Python packages from stomping on each other). There is increasing buzz from people moving to this tool. The author is the same as the older working-env.py mentioned by Aaron.\npip to install packages inside a virtualenv. The traditional is easy_install as answered by S. Lott, but pip works better with virtualenv. easy_install still has features not found in pip though.\nscons as a build tool, although you won't need this if you stay purely Python.\nFabric paste, or paver for deployment.\nbuildbot for continuous integration.\nBazaar, mercurial, or git for version control.\nNose as an extension for unit testing.\nPyFit for FIT testing.\n\n", "I also work with both java and python.\nFor python development the maven equivalent is setuptools (http://peak.telecommunity.com/DevCenter/setuptools). For web application development I use this in combination with paster (http://pythonpaste.org/) for the deployment process\n", "Other than easy_install?\nFor our Linux servers, we use easy_install and yum.\nFor our Windows development laptops, we use easy_install and a few MSI's for some projects.\nMost of the Python libraries we use are source-only, so we can use the same distribution on all boxes. If we could have a network shared device, we'd put them all there. Sadly, our infrastructure is kind of scattered, so we have to either move .TAR files around or redo the installs to rebuild the environments.\nIn a few cases (e.g., PIL), we have to recompile and check the version numbers.\n", "You will want easy_setup to get the eggs (roughly what Maven calls an artifact).\nFor setting up your environment, have a look at working-env.py\nPython is not compiled but you can put all files for a project in an egg. This is done with setuptools\nFor CI, check this answer.\n", "We would be remiss not to also mention Paver, which was created by Kevin Dangoor of TurboGears fame. The project is still in alpha, but it appears very promising. A snippet from the project page:\n\nPaver is a Python-based build/distribution/deployment scripting tool along the lines of Make or Rake. What makes Paver unique is its integration with commonly used Python libraries. Common tasks that were easy before remain easy. More importantly, dealing with your applications specific needs and requirements is now much easier.\n\n", "I do exactly this with a combination of setuptools and Hudson. I know Hudson is a java app, but it can run Python stuff just fine.\n", "You might want to check our Devenv. It allows you to standardize the build environments for development, QA and UAT. It's free as in \"free beer\".\nHTH\n" ]
[ 18, 3, 2, 2, 2, 0, 0 ]
[]
[]
[ "automated_deploy", "continuous_integration", "development_environment", "installation", "python" ]
stackoverflow_0000545730_automated_deploy_continuous_integration_development_environment_installation_python.txt
Q: Excel CSV into Nested Dictionary; List Comprehensions I have a Excel CSV files with employee records in them. Something like this: mail,first_name,surname,employee_id,manager_id,telephone_number blah@blah.com,john,smith,503422,503423,+65(2)3423-2433 foo@blah.com,george,brown,503097,503098,+65(2)3423-9782 .... I'm using DictReader to put this into a nested dictionary: import csv gd_extract = csv.DictReader(open('filename 20100331 original.csv'), dialect='excel') employees = dict([(row['employee_id'], row) for row in gp_extract]) Is the above the proper way to do it - it does work, but is it the Right Way? Something more efficient? Also, the funny thing is, in IDLE, if I try to print out "employees" at the shell, it seems to cause IDLE to crash (there's approximately 1051 rows). 2. Remove employee_id from inner dict The second issue issue, I'm putting it into a dictionary indexed by employee_id, with the value as a nested dictionary of all the values - however, employee_id is also a key:value inside the nested dictionary, which is a bit redundant? Is there any way to exclude it from the inner dictionary? 3. Manipulate data in comprehension Thirdly, we need do some manipulations to the imported data - for example, all the phone numbers are in the wrong format, so we need to do some regex there. Also, we need to convert manager_id to an actual manager's name, and their email address. Most managers are in the same file, while others are in an external_contractors CSV, which is similar but not quite the same format - I can import that to a separate dict though. Are these two items things that can be done within the single list comprehension, or should I use a for loop? Or does multiple comprehensions work? (sample code would be really awesome here). Or is there a smarter way in Python do it? Cheers, Victor A: Your first part has one simple issue (which might not even be an issue). You don't handle key collisions at all (unless you intend to simply overwrite). >>> dict([('a', 'b'), ('a', 'c')]) {'a': 'c'} If you're guaranteed that employee_id is unique, there isn't an issue though. 2) Sure you can exclude it, but no real harm done. Actually, especially in python, if employee_id is a string or int (or some other primitive), the inner dict's reference and the key actually reference the same thing. They both point to the same spot in memory. The only duplication is in the reference (which isn't that big). If you're worried about memory consumption, you probably don't have to. 3) Don't try to do too much in one list comprehension. Just use a for loop after the first list comprehension. To sum it all up, it sounds like you're really worried about the performance of iterating over the loop twice. Don't worry about performance initially. Performance problems come from algorithm problems, not specific language constructs like for loops vs list comprehensions. If you're familiar with Big O notation, the list comprehension and for loop after (if you decide to do that) both have a Big O of O(n). Add them together and you get O(2n), but as we know from Big O notation, we can simplify that to O(n). I've over simplified a lot here, but the point is, you really don't need to worry. If there are performance concerns, raise them after you written the code and prove it to yourself with a code profiler. response to comments As for your #2 reply, python really doesn't have a lot of mechanisms for making one liners cute and extra snazzy. It's meant to force you into simply writing the code out vs sticking it all in one line. That being said, it's still possible to do quite a bit of work in one line. My suggestion is to not worry about how much code you can stick in one line. Python looks a lot more beautiful (IMO) when its written out, not jammed in one line. As for your #1 reply, you could try something like this: employees = {} for row in gd_extract: if row['employee_id'] in employees: ... handle duplicates in employees dictionary ... else: employees[row['employee_id']] = row As for your #3 reply, not sure what you're looking for and what about the telephone numbers you'd like to fix, but... this may give you a start: import re retelephone = re.compile(r'[-\(\)\s]') # remove dashes, open/close parens, and spaces for empid, row in employees.iteritems(): retelephone.sub('',row['telephone'])
Excel CSV into Nested Dictionary; List Comprehensions
I have a Excel CSV files with employee records in them. Something like this: mail,first_name,surname,employee_id,manager_id,telephone_number blah@blah.com,john,smith,503422,503423,+65(2)3423-2433 foo@blah.com,george,brown,503097,503098,+65(2)3423-9782 .... I'm using DictReader to put this into a nested dictionary: import csv gd_extract = csv.DictReader(open('filename 20100331 original.csv'), dialect='excel') employees = dict([(row['employee_id'], row) for row in gp_extract]) Is the above the proper way to do it - it does work, but is it the Right Way? Something more efficient? Also, the funny thing is, in IDLE, if I try to print out "employees" at the shell, it seems to cause IDLE to crash (there's approximately 1051 rows). 2. Remove employee_id from inner dict The second issue issue, I'm putting it into a dictionary indexed by employee_id, with the value as a nested dictionary of all the values - however, employee_id is also a key:value inside the nested dictionary, which is a bit redundant? Is there any way to exclude it from the inner dictionary? 3. Manipulate data in comprehension Thirdly, we need do some manipulations to the imported data - for example, all the phone numbers are in the wrong format, so we need to do some regex there. Also, we need to convert manager_id to an actual manager's name, and their email address. Most managers are in the same file, while others are in an external_contractors CSV, which is similar but not quite the same format - I can import that to a separate dict though. Are these two items things that can be done within the single list comprehension, or should I use a for loop? Or does multiple comprehensions work? (sample code would be really awesome here). Or is there a smarter way in Python do it? Cheers, Victor
[ "Your first part has one simple issue (which might not even be an issue). You don't handle key collisions at all (unless you intend to simply overwrite).\n>>> dict([('a', 'b'), ('a', 'c')])\n{'a': 'c'}\n\nIf you're guaranteed that employee_id is unique, there isn't an issue though.\n2) Sure you can exclude it, but no real harm done. Actually, especially in python, if employee_id is a string or int (or some other primitive), the inner dict's reference and the key actually reference the same thing. They both point to the same spot in memory. The only duplication is in the reference (which isn't that big). If you're worried about memory consumption, you probably don't have to.\n3) Don't try to do too much in one list comprehension. Just use a for loop after the first list comprehension.\nTo sum it all up, it sounds like you're really worried about the performance of iterating over the loop twice. Don't worry about performance initially. Performance problems come from algorithm problems, not specific language constructs like for loops vs list comprehensions.\nIf you're familiar with Big O notation, the list comprehension and for loop after (if you decide to do that) both have a Big O of O(n). Add them together and you get O(2n), but as we know from Big O notation, we can simplify that to O(n). I've over simplified a lot here, but the point is, you really don't need to worry.\nIf there are performance concerns, raise them after you written the code and prove it to yourself with a code profiler.\nresponse to comments\nAs for your #2 reply, python really doesn't have a lot of mechanisms for making one liners cute and extra snazzy. It's meant to force you into simply writing the code out vs sticking it all in one line. That being said, it's still possible to do quite a bit of work in one line. My suggestion is to not worry about how much code you can stick in one line. Python looks a lot more beautiful (IMO) when its written out, not jammed in one line.\nAs for your #1 reply, you could try something like this:\nemployees = {}\nfor row in gd_extract:\n if row['employee_id'] in employees:\n ... handle duplicates in employees dictionary ...\n else:\n employees[row['employee_id']] = row\n\nAs for your #3 reply, not sure what you're looking for and what about the telephone numbers you'd like to fix, but... this may give you a start:\nimport re\nretelephone = re.compile(r'[-\\(\\)\\s]') # remove dashes, open/close parens, and spaces\nfor empid, row in employees.iteritems():\n retelephone.sub('',row['telephone'])\n\n" ]
[ 4 ]
[]
[]
[ "csv", "list_comprehension", "python" ]
stackoverflow_0002831315_csv_list_comprehension_python.txt
Q: Sending and receiving async over multiprocessing.Pipe() in Python I'm having some issues getting the Pipe.send to work in this code. What I would ultimately like to do is send and receive messages to and from the foreign process while its running in a fork. This is eventually going to be integrated into a pexpect loop for talking to interpreter processes. from multiprocessing import Process, Pipe from pexpect import spawn class CockProc(Process): def start(self): self.process = spawn('coqtop', ['-emacs-U']) def run(self, conn): while True: if not conn.poll(): cmd = conn.recv() self.process.send(cmd) self.process.expect('\<\/prompt\>') result = self.process.before + self.process.after + " " conn.send(result) q, p = Pipe() proc = CockProc() proc.start() proc.run(p) res = q.recv() command = raw_input(res + " ") q.send(command) res = q.recv() parent_conn.send('OHHAI') p.join() ` A: This works, but might need some more work. Not sure how many of these i can create and loop over. from multiprocessing import Process, Pipe from pexpect import spawn class CockProc(Process): def start(self): self.process = spawn('coqtop', ['-emacs-U']) def run(self, conn): if conn.poll(): cmd = conn.recv() self.process.send(cmd + "\n") print "sent comm" self.process.expect('\<\/prompt\>') result = self.process.before + self.process.after + " " conn.send(result) here, there = Pipe(duplex=True) proc = CockProc() proc.start() proc.run(there) while True: if here.poll(): res = here.recv() command = raw_input(res + " ") here.send(command) proc.run(there)
Sending and receiving async over multiprocessing.Pipe() in Python
I'm having some issues getting the Pipe.send to work in this code. What I would ultimately like to do is send and receive messages to and from the foreign process while its running in a fork. This is eventually going to be integrated into a pexpect loop for talking to interpreter processes. from multiprocessing import Process, Pipe from pexpect import spawn class CockProc(Process): def start(self): self.process = spawn('coqtop', ['-emacs-U']) def run(self, conn): while True: if not conn.poll(): cmd = conn.recv() self.process.send(cmd) self.process.expect('\<\/prompt\>') result = self.process.before + self.process.after + " " conn.send(result) q, p = Pipe() proc = CockProc() proc.start() proc.run(p) res = q.recv() command = raw_input(res + " ") q.send(command) res = q.recv() parent_conn.send('OHHAI') p.join() `
[ "This works, but might need some more work. Not sure how many of these i can create and loop over.\nfrom multiprocessing import Process, Pipe\nfrom pexpect import spawn\n\n\nclass CockProc(Process):\n\n def start(self):\n self.process = spawn('coqtop', ['-emacs-U'])\n\n def run(self, conn):\n if conn.poll():\n cmd = conn.recv()\n self.process.send(cmd + \"\\n\")\n print \"sent comm\"\n self.process.expect('\\<\\/prompt\\>')\n result = self.process.before + self.process.after + \" \"\n conn.send(result)\n\nhere, there = Pipe(duplex=True)\n\nproc = CockProc()\nproc.start()\nproc.run(there)\n\nwhile True:\n if here.poll():\n res = here.recv()\n command = raw_input(res + \" \")\n here.send(command)\n proc.run(there)\n\n" ]
[ 1 ]
[]
[]
[ "asynchronous", "multiprocessing", "python" ]
stackoverflow_0002831299_asynchronous_multiprocessing_python.txt
Q: How to generate a tree without recursive using python or other language? class tree: def __init__(self, name='a', childs=[]): self.name = name self.childs = childs output: <ul> <li> Introduction <ul> <li>Sub Intro</li> </ul> </li> <li>Module 1</li> </ul> A: To generate nested lists without recursion you'd simply keep track of your nesting level, incrementing it as you traverse into deeper levels of nesting and decrementing it as you traverse back upwards. The natural approach, for handling things like closing tags, would be to maintain a simple stack (Python list) and push the closing tags onto it as you insert their corresponding opening tags into the output stream. You'd then pop these off as you traverse out of any level of nesting. You don't say anything about your input format ... so let's pretend that it looks something like: = Introduction == Sub Intro = Module 1 Then something like: def pref_txt_to_ul(txt): nesting = 0 closing_tags = list() for x in txt: if len(x.split()) < 2: continue prefix, content = x.split(None,1) nd = len(prefix) ## new depth assert prefix == "=" * nd ## First "word" is all = characters if nd > nesting: print "\n", " " * nesting * 4, "<ul>" * (nd - nesting), ## Push new opening tags into output closing_tags.append('</ul>' * (nd - nesting)) ## push closing tags for later elif nd < nesting: for x in range(nesting - nd): if closing_tags: print " " * nesting * 4, closing_tags.pop(), ## Pop closing tags nesting = nd print "\n", " " * nesting * 4, "<li>%s</li>" % content, # push out this item (at new depth) ## After all text is done: while closing_tags: print closing_tags.pop(), # Pop off remaining cloing tags ... should do the trick (albeit, rather crudely). Note that I'm not actually enforcing a rule that one should only increase the nesting level in increments of one. Degenerate input that go from = to ====== in one step would generate extraneous tags and push extraneous tags into the closing stack. Note: I'm only answering the explicit question about how to handle nesting without recursion. One might infer from your example (using HTML unordered list tags) that your real goal is to generate valid HTML. In that case there are a wealth of Python tools that are far better suited to that task then any crude text munging I'm doing in this example. A Yahoo or Google search on: Python "generate HTML" will return many thousands of pages about ways to do this and the many available tools for this. (I remember that I used HTMLgen years ago, and I see that it's still available as a Debian package, but it seems to have fallen off of PyPI ... the Python Package Index. There are undoubtedly much more recently updated packages out there. Most people seem to use templating engines such as Genshi or Mako, for example).
How to generate a tree without recursive using python or other language?
class tree: def __init__(self, name='a', childs=[]): self.name = name self.childs = childs output: <ul> <li> Introduction <ul> <li>Sub Intro</li> </ul> </li> <li>Module 1</li> </ul>
[ "To generate nested lists without recursion you'd simply keep track of your nesting level, incrementing it as you traverse into deeper levels of nesting and decrementing it as you traverse back upwards.\nThe natural approach, for handling things like closing tags, would be to maintain a simple stack (Python list) and push the closing tags onto it as you insert their corresponding opening tags into the output stream. You'd then pop these off as you traverse out of any level of nesting.\nYou don't say anything about your input format ... so let's pretend that it looks something like:\n= Introduction\n== Sub Intro\n= Module 1\n\nThen something like:\n def pref_txt_to_ul(txt):\n nesting = 0\n closing_tags = list()\n for x in txt:\n if len(x.split()) < 2:\n continue\n prefix, content = x.split(None,1)\n nd = len(prefix) ## new depth\n assert prefix == \"=\" * nd ## First \"word\" is all = characters\n\n if nd > nesting:\n print \"\\n\", \" \" * nesting * 4, \"<ul>\" * (nd - nesting), ## Push new opening tags into output\n closing_tags.append('</ul>' * (nd - nesting)) ## push closing tags for later\n elif nd < nesting:\n for x in range(nesting - nd):\n if closing_tags:\n print \" \" * nesting * 4, closing_tags.pop(), ## Pop closing tags\n nesting = nd\n print \"\\n\", \" \" * nesting * 4, \"<li>%s</li>\" % content, # push out this item (at new depth)\n ## After all text is done:\n while closing_tags:\n print closing_tags.pop(), # Pop off remaining cloing tags\n\n... should do the trick (albeit, rather crudely).\nNote that I'm not actually enforcing a rule that one should only increase the nesting level in increments of one. Degenerate input that go from = to ====== in one step would generate extraneous tags and push extraneous tags into the closing stack.\nNote: I'm only answering the explicit question about how to handle nesting without recursion. One might infer from your example (using HTML unordered list tags) that your real goal is to generate valid HTML. In that case there are a wealth of Python tools that are far better suited to that task then any crude text munging I'm doing in this example. A Yahoo or Google search on: Python \"generate HTML\" will return many thousands of pages about ways to do this and the many available tools for this.\n(I remember that I used HTMLgen years ago, and I see that it's still available as a Debian package, but it seems to have fallen off of PyPI ... the Python Package Index. There are undoubtedly much more recently updated packages out there. Most people seem to use templating engines such as Genshi or Mako, for example).\n" ]
[ 2 ]
[ "Maybe something like this:\nNEW=object()\nEND=object()\n\nclass tree:\n def __init__(self, name='a', childs=[]):\n self.name = name\n self.childs = childs\n\n def __str__(self):\n indent=0\n result=[]\n for i in self.childs:\n if i is NEW:\n result.append('%s<ul>\\n'%(' '*indent))\n indent+=1\n elif i is END: \n indent-=1\n result.append('%s</ul>\\n'%(' '*indent))\n else:\n result.append('%s<li>%s</li>\\n'%(' '*indent, i))\n return ''.join(result)\n\n\n\nprint tree('test', [NEW, 'Introduction', NEW, 'Sub Intro', END, 'Module 1', END])\n\n" ]
[ -1 ]
[ "python", "tree" ]
stackoverflow_0002831478_python_tree.txt
Q: Wav analysis in python I'm looking for a python library that will help me analyze the audio in wav files. At the very least I'm hoping to find some kind of interface that understands .wav format so that I don't have to :P at best I need a module with methods for reading wave form parameters like pitch, volume levels, etc A: How about the wave module?
Wav analysis in python
I'm looking for a python library that will help me analyze the audio in wav files. At the very least I'm hoping to find some kind of interface that understands .wav format so that I don't have to :P at best I need a module with methods for reading wave form parameters like pitch, volume levels, etc
[ "How about the wave module?\n" ]
[ 2 ]
[]
[]
[ "python", "wav" ]
stackoverflow_0002831699_python_wav.txt
Q: Pyparsing CSV string with random quotes I have a string like the following: <118>date=2010-05-09,time=16:41:27,device_id=FE-2KA3F09000049,log_id=0400147717,log_part=00,type=statistics,subtype=n/a,pri=information,session_id=o49CedRc021772,from="prvs=4745cd07e1=example@example.org",mailer="mta",client_name="example.org,[194.177.17.24]",resolved=OK,to="example@example.org",direction="in",message_length=6832079,virus="",disposition="Accept",classifier="Not,Spam",subject="=?windows-1255?B?Rlc6IEZ3OiDg5fDp5fog+fno5fog7Pf46eHp7S3u4+Tp7SE=?=" I tried using CSV module and it didn't fit, cause i haven't found a way to ignore what's quoted. Pyparsing looked like a better answer but i haven't found a way to declare all the grammars. Currently, i am using my old Perl script to parse it, but i want this written in Python. if you need my Perl snippet i will be glad to provide it. Any help is appreciated. A: It might be better to leverage an existing parser than to use ad-hoc regexs. parse_http_list(s) Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Neither commas nor quotes count if they are escaped. Only double-quotes count, not single-quotes. parse_keqv_list(l) Parse list of key=value strings where keys are not duplicated. Example: >>> pprint.pprint(urllib2.parse_keqv_list(urllib2.parse_http_list(s))) {'<118>date': '2010-05-09', 'classifier': 'Not,Spam', 'client_name': 'example.org,[194.177.17.24]', 'device_id': 'FE-2KA3F09000049', 'direction': 'in', 'disposition': 'Accept', 'from': 'prvs=4745cd07e1=example@example.org', 'log_id': '0400147717', 'log_part': '00', 'mailer': 'mta', 'message_length': '6832079', 'pri': 'information', 'resolved': 'OK', 'session_id': 'o49CedRc021772', 'subject':'=?windows-1255?B?Rlc6IEZ3OiDg5fDp5fog+fno5fog7Pf46eHp7S3u4+Tp7SE=?=', 'subtype': 'n/a', 'time': '16:41:27', 'to': 'example@example.org', 'type': 'statistics', 'virus': ''} A: I'm not sure what you're really looking for, but import re data = "date=2010-05-09,time=16:41:27,device_id=FE-2KA3F09000049,log_id=0400147717,log_part=00,type=statistics,subtype=n/a,pri=information,session_id=o49CedRc021772,from=\"prvs=4745cd07e1=example@example.org\",mailer=\"mta\",client_name=\"example.org,[194.177.17.24]\",resolved=OK,to=\"example@example.org\",direction=\"in\",message_length=6832079,virus=\"\",disposition=\"Accept\",classifier=\"Not,Spam\",subject=\"=?windows-1255?B?Rlc6IEZ3OiDg5fDp5fog+fno5fog7Pf46eHp7S3u4+Tp7SE=?=\"" pattern = r"""(\w+)=((?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*'|[^\\,"'])+)""" print(re.findall(pattern, data)) gives you [('date', '2010-05-09'), ('time', '16:41:27'), ('device_id', 'FE-2KA3F09000049'), ('log_id', '0400147717'), ('log_part', '00'), ('type', 'statistics'), ('subtype', 'n/a'), ('pri', 'information'), ('session_id', 'o49CedRc021772'), ('from', '"prvs=4745cd07e1=example@example.org"'), ('mailer', '"mta"'), ('client_name', '"example.org,[194.177.17.24]"'), ('resolved', 'OK'), ('to', '"example@example.org"'), ('direction', '"in"'), ('message_length', '6832079'), ('virus', '""'), ('disposition', '"Accept"'), ('classifier', '"Not,Spam"'), ('subject', '"=?windows-1255?B?Rlc6IEZ3OiDg5fDp5fog+fno5fog7Pf46eHp7S3u4+Tp7SE=?="') ] You might want to clean up the quoted strings afterwards (using mystring.strip("'\"")). EDIT: This regex now also correctly handles escaped quotes inside quoted strings (a="She said \"Hi!\""). Explanation of the regex: (\w+)=((?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*'|[^\\,"'])+) (\w+): Match the identifier and capture it into backreference no. 1 =: Match a = (: Capture the following into backreference no. 2: (?:: One of the following: "(?:\\.|[^\\"])*": A double quote, followed by either zero or more of the following: an escaped character or a non-quote/non-backslash character, followed by another double quote |: or '(?:\\.|[^\\'])*': See above, just for single quotes. |: or [^\\,"']: one character that is neither a backslash, a comma, nor a quote. )+: repeat at least once, as many times as possible. ): end of capturing group no. 2.
Pyparsing CSV string with random quotes
I have a string like the following: <118>date=2010-05-09,time=16:41:27,device_id=FE-2KA3F09000049,log_id=0400147717,log_part=00,type=statistics,subtype=n/a,pri=information,session_id=o49CedRc021772,from="prvs=4745cd07e1=example@example.org",mailer="mta",client_name="example.org,[194.177.17.24]",resolved=OK,to="example@example.org",direction="in",message_length=6832079,virus="",disposition="Accept",classifier="Not,Spam",subject="=?windows-1255?B?Rlc6IEZ3OiDg5fDp5fog+fno5fog7Pf46eHp7S3u4+Tp7SE=?=" I tried using CSV module and it didn't fit, cause i haven't found a way to ignore what's quoted. Pyparsing looked like a better answer but i haven't found a way to declare all the grammars. Currently, i am using my old Perl script to parse it, but i want this written in Python. if you need my Perl snippet i will be glad to provide it. Any help is appreciated.
[ "It might be better to leverage an existing parser than to use ad-hoc regexs.\nparse_http_list(s)\n Parse lists as described by RFC 2068 Section 2.\n\n In particular, parse comma-separated lists where the elements of\n the list may include quoted-strings. A quoted-string could\n contain a comma. A non-quoted string could have quotes in the\n middle. Neither commas nor quotes count if they are escaped.\n Only double-quotes count, not single-quotes.\n\nparse_keqv_list(l)\n Parse list of key=value strings where keys are not duplicated.\n\nExample:\n>>> pprint.pprint(urllib2.parse_keqv_list(urllib2.parse_http_list(s)))\n{'<118>date': '2010-05-09',\n 'classifier': 'Not,Spam',\n 'client_name': 'example.org,[194.177.17.24]',\n 'device_id': 'FE-2KA3F09000049',\n 'direction': 'in',\n 'disposition': 'Accept',\n 'from': 'prvs=4745cd07e1=example@example.org',\n 'log_id': '0400147717',\n 'log_part': '00',\n 'mailer': 'mta',\n 'message_length': '6832079',\n 'pri': 'information',\n 'resolved': 'OK',\n 'session_id': 'o49CedRc021772',\n 'subject':'=?windows-1255?B?Rlc6IEZ3OiDg5fDp5fog+fno5fog7Pf46eHp7S3u4+Tp7SE=?=',\n 'subtype': 'n/a',\n 'time': '16:41:27',\n 'to': 'example@example.org',\n 'type': 'statistics',\n 'virus': ''}\n\n", "I'm not sure what you're really looking for, but\nimport re\ndata = \"date=2010-05-09,time=16:41:27,device_id=FE-2KA3F09000049,log_id=0400147717,log_part=00,type=statistics,subtype=n/a,pri=information,session_id=o49CedRc021772,from=\\\"prvs=4745cd07e1=example@example.org\\\",mailer=\\\"mta\\\",client_name=\\\"example.org,[194.177.17.24]\\\",resolved=OK,to=\\\"example@example.org\\\",direction=\\\"in\\\",message_length=6832079,virus=\\\"\\\",disposition=\\\"Accept\\\",classifier=\\\"Not,Spam\\\",subject=\\\"=?windows-1255?B?Rlc6IEZ3OiDg5fDp5fog+fno5fog7Pf46eHp7S3u4+Tp7SE=?=\\\"\"\npattern = r\"\"\"(\\w+)=((?:\"(?:\\\\.|[^\\\\\"])*\"|'(?:\\\\.|[^\\\\'])*'|[^\\\\,\"'])+)\"\"\"\nprint(re.findall(pattern, data))\n\ngives you\n[('date', '2010-05-09'), ('time', '16:41:27'), ('device_id', 'FE-2KA3F09000049'),\n ('log_id', '0400147717'), ('log_part', '00'), ('type', 'statistics'),\n ('subtype', 'n/a'), ('pri', 'information'), ('session_id', 'o49CedRc021772'),\n ('from', '\"prvs=4745cd07e1=example@example.org\"'), ('mailer', '\"mta\"'),\n ('client_name', '\"example.org,[194.177.17.24]\"'), ('resolved', 'OK'),\n ('to', '\"example@example.org\"'), ('direction', '\"in\"'),\n ('message_length', '6832079'), ('virus', '\"\"'), ('disposition', '\"Accept\"'),\n ('classifier', '\"Not,Spam\"'), \n ('subject', '\"=?windows-1255?B?Rlc6IEZ3OiDg5fDp5fog+fno5fog7Pf46eHp7S3u4+Tp7SE=?=\"')\n]\n\nYou might want to clean up the quoted strings afterwards (using mystring.strip(\"'\\\"\")).\nEDIT: This regex now also correctly handles escaped quotes inside quoted strings (a=\"She said \\\"Hi!\\\"\"). \nExplanation of the regex:\n(\\w+)=((?:\"(?:\\\\.|[^\\\\\"])*\"|'(?:\\\\.|[^\\\\'])*'|[^\\\\,\"'])+)\n\n(\\w+): Match the identifier and capture it into backreference no. 1\n=: Match a =\n(: Capture the following into backreference no. 2:\n(?:: One of the following:\n\"(?:\\\\.|[^\\\\\"])*\": A double quote, followed by either zero or more of the following: an escaped character or a non-quote/non-backslash character, followed by another double quote\n|: or\n'(?:\\\\.|[^\\\\'])*': See above, just for single quotes.\n|: or\n[^\\\\,\"']: one character that is neither a backslash, a comma, nor a quote.\n)+: repeat at least once, as many times as possible.\n): end of capturing group no. 2.\n" ]
[ 6, 5 ]
[]
[]
[ "csv", "logging", "pyparsing", "python" ]
stackoverflow_0002797644_csv_logging_pyparsing_python.txt
Q: pythonic way to associate list elements with their indices I have a list of values and I want to put them in a dictionary that would map each value to it's index. I can do it this way: >>> t = (5,6,7) >>> d = dict(zip(t, range(len(t)))) >>> d {5: 0, 6: 1, 7: 2} this is not bad, but I'm looking for something more elegant. I've come across the following, but it does the opposite of what I need: >>> d = dict(enumerate(t)) >>> d {0: 5, 1: 6, 2: 7} Please share your solutions, Thank you EDIT: Python 2.6.4 For lists containing 1000 elements the dict(zip) version is the fastest, the generator and the list comprehension versions are virtually identical and they are ~1.5 times slower and the functional map(reversed) is considerably slower. $ python -mtimeit -s"t = range(int(1e3))" "d = dict(zip(t, range(len(t))))" 1000 loops, best of 3: 277 usec per loop $ python -mtimeit -s"t = range(int(1e3))" "d = dict([(y,x) for x,y in enumerate(t)])" 1000 loops, best of 3: 426 usec per loop $ python -mtimeit -s"t = range(int(1e3))" "d = dict((y,x) for x,y in enumerate(t))" 1000 loops, best of 3: 437 usec per loop $ python -mtimeit -s"t = range(int(1e3))" "d = dict(map(reversed, enumerate(t)))" 100 loops, best of 3: 3.66 msec per loop I tried running the same tests for longer and for shorter lists (1e2, 1e4, 1e5) and the time per loop scales linearly with the length of the list. Could somebody time py 2.7+ version? A: You can use a list comprehension (or a generator, depending on your python version) to perform a simple in-place swap for your second example. Using a list comprehension: d = dict([(y,x) for x,y in enumerate(t)]) Using a generator expression (Python 2.4 and up): d = dict((y,x) for x,y in enumerate(t)) A: In Python2.7+ you can write it like this >>> t = (5,6,7) >>> d = {x:i for i,x in enumerate(t)} >>> print d {5: 0, 6: 1, 7: 2} A: >>> dict((x,i) for i,x in enumerate(t)) {5: 0, 6: 1, 7: 2} >>> A: Are all your elements unique (i.e. your list would never be 5,6,7,7)? The dict solution will only work if all your elements are unique. By storing the index, you're essentially duplicating information, since you could simply query the current index of the item in the list. Duplicating information is usually not the best idea, because it allows the possibility for one set of data to get out of sync with the other. If the list is being modified, there's also nothing preventing you from accidentally assigning the same index to more than one item. Why are you trying to store the index value, when you could simply get the index from the list? A: As everybody has already written, in Python 2.6 I would consider the following as the most pythonic: >>> dict((x, i) for i, x in enumerate(t)) {5: 0, 6: 1, 7: 2} Still, in a moment of functional frenzy I would write: >>> dict(map(reversed, enumerate(t))) {5: 0, 6: 1, 7: 2} A: I like the dict(zip(t, range(len(t)))) best.
pythonic way to associate list elements with their indices
I have a list of values and I want to put them in a dictionary that would map each value to it's index. I can do it this way: >>> t = (5,6,7) >>> d = dict(zip(t, range(len(t)))) >>> d {5: 0, 6: 1, 7: 2} this is not bad, but I'm looking for something more elegant. I've come across the following, but it does the opposite of what I need: >>> d = dict(enumerate(t)) >>> d {0: 5, 1: 6, 2: 7} Please share your solutions, Thank you EDIT: Python 2.6.4 For lists containing 1000 elements the dict(zip) version is the fastest, the generator and the list comprehension versions are virtually identical and they are ~1.5 times slower and the functional map(reversed) is considerably slower. $ python -mtimeit -s"t = range(int(1e3))" "d = dict(zip(t, range(len(t))))" 1000 loops, best of 3: 277 usec per loop $ python -mtimeit -s"t = range(int(1e3))" "d = dict([(y,x) for x,y in enumerate(t)])" 1000 loops, best of 3: 426 usec per loop $ python -mtimeit -s"t = range(int(1e3))" "d = dict((y,x) for x,y in enumerate(t))" 1000 loops, best of 3: 437 usec per loop $ python -mtimeit -s"t = range(int(1e3))" "d = dict(map(reversed, enumerate(t)))" 100 loops, best of 3: 3.66 msec per loop I tried running the same tests for longer and for shorter lists (1e2, 1e4, 1e5) and the time per loop scales linearly with the length of the list. Could somebody time py 2.7+ version?
[ "You can use a list comprehension (or a generator, depending on your python version) to perform a simple in-place swap for your second example.\n\nUsing a list comprehension:\nd = dict([(y,x) for x,y in enumerate(t)])\n\n\nUsing a generator expression (Python 2.4 and up):\nd = dict((y,x) for x,y in enumerate(t))\n\n", "In Python2.7+ you can write it like this\n>>> t = (5,6,7)\n>>> d = {x:i for i,x in enumerate(t)}\n>>> print d\n{5: 0, 6: 1, 7: 2}\n\n", ">>> dict((x,i) for i,x in enumerate(t))\n{5: 0, 6: 1, 7: 2}\n>>>\n\n", "Are all your elements unique (i.e. your list would never be 5,6,7,7)? The dict solution will only work if all your elements are unique.\nBy storing the index, you're essentially duplicating information, since you could simply query the current index of the item in the list. Duplicating information is usually not the best idea, because it allows the possibility for one set of data to get out of sync with the other.\nIf the list is being modified, there's also nothing preventing you from accidentally assigning the same index to more than one item.\nWhy are you trying to store the index value, when you could simply get the index from the list?\n", "As everybody has already written, in Python 2.6 I would consider the following as the most pythonic:\n>>> dict((x, i) for i, x in enumerate(t))\n{5: 0, 6: 1, 7: 2}\n\nStill, in a moment of functional frenzy I would write:\n>>> dict(map(reversed, enumerate(t)))\n{5: 0, 6: 1, 7: 2}\n\n", "I like the dict(zip(t, range(len(t)))) best.\n" ]
[ 14, 14, 4, 2, 2, 0 ]
[]
[]
[ "dictionary", "enumerate", "list", "python" ]
stackoverflow_0002831672_dictionary_enumerate_list_python.txt
Q: Creating a new workbook in Excel from Python breaks I am trying to use the stock standard win32com approach to drive Excel 2007 from Python. However, when I try to create a new workbook, things go pear-shaped: Python 2.6.4 (r264:75706, Nov 3 2009, 13:23:17) [MSC v.1500 32 bit (Intel)] on win32 ... >>> import win32com.client >>> excel = win32com.client.Dispatch("Excel.Application") >>> wb = excel.Workbooks.Add() Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> wb = excel.Workbooks.Add() File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 467, in __getattr__ if self._olerepr_.mapFuncs.has_key(attr): return self._make_method_(attr) File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 295, in _make_method_ methodCodeList = self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[name], methodName,0) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 297, in MakeFuncMethod return self.MakeDispatchFuncMethod(entry, name, bMakeClass) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 318, in MakeDispatchFuncMethod s = linePrefix + 'def ' + name + '(self' + BuildCallList(fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg) + '):' File "C:\Python26\lib\site-packages\win32com\client\build.py", line 604, in BuildCallList argName = MakePublicAttributeName(argName) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 542, in MakePublicAttributeName return filter( lambda char: char in valid_identifier_chars, className) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 542, in <lambda> return filter( lambda char: char in valid_identifier_chars, className) UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 52: ordinal not in range(128) >>> What is going wrong here? Have I done something silly, or is Python/win32com/Excel somehow broken? A: you might want to look at the excellent xl*t packages at http://www.python-excel.org/ Creating workbooks/sheets is as easy as: import xlwt from datetime import datetime wb = xlwt.Workbook() ws = wb.add_sheet('A Test Sheet') ws.write(0, 0, 'Test', style0) ws.write(1, 0, datetime.now(), style1) ws.write(2, 0, 1) ws.write(2, 1, 1) ws.write(2, 2, xlwt.Formula("A3+B3")) wb.save('example.xls') And you don't have to bother with the win32com api..... Good luck !! Ben A: I'm on 2.6.3, so I can't check this directly, but it appears that you've got a non-ASCII character in the className somehow, and valid_identifier_chars is a byte string, so this breaks it. A couple thoughts on things to check: Are you using a localized version of Excel? Do you have the latest version of win32com (the error message doesn't line up exactly with my version's line numbers)? Do you have an earlier version of python (e.g. 2.5) that you can test this on, to see if it's a problem introduced in 2.6.4? If you do have the latest version of win32com, a hacky thing to try would be to edit build.py, and change valid_identifier_chars to a Unicode string.
Creating a new workbook in Excel from Python breaks
I am trying to use the stock standard win32com approach to drive Excel 2007 from Python. However, when I try to create a new workbook, things go pear-shaped: Python 2.6.4 (r264:75706, Nov 3 2009, 13:23:17) [MSC v.1500 32 bit (Intel)] on win32 ... >>> import win32com.client >>> excel = win32com.client.Dispatch("Excel.Application") >>> wb = excel.Workbooks.Add() Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> wb = excel.Workbooks.Add() File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 467, in __getattr__ if self._olerepr_.mapFuncs.has_key(attr): return self._make_method_(attr) File "C:\Python26\lib\site-packages\win32com\client\dynamic.py", line 295, in _make_method_ methodCodeList = self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[name], methodName,0) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 297, in MakeFuncMethod return self.MakeDispatchFuncMethod(entry, name, bMakeClass) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 318, in MakeDispatchFuncMethod s = linePrefix + 'def ' + name + '(self' + BuildCallList(fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg) + '):' File "C:\Python26\lib\site-packages\win32com\client\build.py", line 604, in BuildCallList argName = MakePublicAttributeName(argName) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 542, in MakePublicAttributeName return filter( lambda char: char in valid_identifier_chars, className) File "C:\Python26\lib\site-packages\win32com\client\build.py", line 542, in <lambda> return filter( lambda char: char in valid_identifier_chars, className) UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 52: ordinal not in range(128) >>> What is going wrong here? Have I done something silly, or is Python/win32com/Excel somehow broken?
[ "you might want to look at the excellent xl*t packages at http://www.python-excel.org/\nCreating workbooks/sheets is as easy as:\nimport xlwt\nfrom datetime import datetime\n\nwb = xlwt.Workbook()\nws = wb.add_sheet('A Test Sheet')\n\nws.write(0, 0, 'Test', style0)\nws.write(1, 0, datetime.now(), style1)\nws.write(2, 0, 1)\nws.write(2, 1, 1)\nws.write(2, 2, xlwt.Formula(\"A3+B3\"))\n\nwb.save('example.xls')\n\nAnd you don't have to bother with the win32com api.....\nGood luck !! \nBen\n", "I'm on 2.6.3, so I can't check this directly, but it appears that you've got a non-ASCII character in the className somehow, and valid_identifier_chars is a byte string, so this breaks it.\nA couple thoughts on things to check:\n\nAre you using a localized version of Excel? \nDo you have the latest version of win32com (the error message doesn't line up exactly with my version's line numbers)?\nDo you have an earlier version of python (e.g. 2.5) that you can test this on, to see if it's a problem introduced in 2.6.4?\n\nIf you do have the latest version of win32com, a hacky thing to try would be to edit build.py, and change valid_identifier_chars to a Unicode string.\n" ]
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002831491_python.txt
Q: how to increase Speed of a component made from Javascript or JQuery? I want to make my component faster, I am using Javascript and JQuery to build that. I am using JSON object to communicate with component and back-end is python. Is there any suggestion to make component faster? A: Setup some analysis to see what takes time to process. Then decide if you want to try to optimize the javascript and client code, the communication up/down with the server or the actual speed of the python execution. When you have decided what you want to make faster, you can post samples of that to this site and people will probably be willing to help you. A: On the client side, you can benchmark your script(s) using getTime() var start = (new Date).getTime(); /* Run your script. */ var diff = (new Date).getTime() - start; alert(diff) And see what is taking long in a script exactly. But its hard do tell what could be optimized if you don't post any code. A: If speed is the issue, and you by profiling discover that js is the culprit, then I would look into replacing the jQuery with vanilla javascript, or a more optimized library. As jQuery tries to do 'everything' and trains its users into wrapping everything in $(), its bound to introduce unnecessary method calls (I've seen that a single call to $() can result in upto 100+ method calls).
how to increase Speed of a component made from Javascript or JQuery?
I want to make my component faster, I am using Javascript and JQuery to build that. I am using JSON object to communicate with component and back-end is python. Is there any suggestion to make component faster?
[ "Setup some analysis to see what takes time to process. Then decide if you want to try to optimize the javascript and client code, the communication up/down with the server or the actual speed of the python execution. When you have decided what you want to make faster, you can post samples of that to this site and people will probably be willing to help you.\n", "On the client side, you can benchmark your script(s) using getTime() \nvar start = (new Date).getTime();\n /* Run your script. */\nvar diff = (new Date).getTime() - start;\nalert(diff)\n\nAnd see what is taking long in a script exactly.\nBut its hard do tell what could be optimized if you don't post any code.\n", "If speed is the issue, and you by profiling discover that js is the culprit, then I would look into replacing the jQuery with vanilla javascript, or a more optimized library.\nAs jQuery tries to do 'everything' and trains its users into wrapping everything in $(), its bound to introduce unnecessary method calls (I've seen that a single call to $() can result in upto 100+ method calls).\n" ]
[ 1, 0, 0 ]
[]
[]
[ "google_apps", "javascript", "jquery", "python" ]
stackoverflow_0002832064_google_apps_javascript_jquery_python.txt
Q: Google App Engine Python: get image upload size server-side I am building a Google App Engine App that lets users upload images; I have everything working fine, but I am struggling to find a way to ensure that the user does not upload an image too large (because I am resizing the images, so this crashes my python script). When a user uploads a large image, I get this error RequestTooLargeError: The request to API call images.Transform() was too large. I know that there is a size limitation on what GAE allows for it's image API, I am just trying to find a way to deal with this server side; something along the lines of if (image is too large): inform user else: proceed I haven't had any luck finding the right python code to do this; can anyone help me out? A: from google.appengine.runtime import apiproxy_errors ... try: #the code you are getting the error at except apiproxy_errors.RequestTooLargeError, message: print message # or something else A: I am not sure I understand your problem completely but maybe a try would work? try: images.Transform() except Transform.RequestTooLargeError: inform else: proceed
Google App Engine Python: get image upload size server-side
I am building a Google App Engine App that lets users upload images; I have everything working fine, but I am struggling to find a way to ensure that the user does not upload an image too large (because I am resizing the images, so this crashes my python script). When a user uploads a large image, I get this error RequestTooLargeError: The request to API call images.Transform() was too large. I know that there is a size limitation on what GAE allows for it's image API, I am just trying to find a way to deal with this server side; something along the lines of if (image is too large): inform user else: proceed I haven't had any luck finding the right python code to do this; can anyone help me out?
[ "from google.appengine.runtime import apiproxy_errors\n\n...\n\ntry:\n #the code you are getting the error at\nexcept apiproxy_errors.RequestTooLargeError, message:\n print message # or something else\n\n", "I am not sure I understand your problem completely but maybe a try would work?\ntry: \n images.Transform()\nexcept Transform.RequestTooLargeError:\n inform\nelse:\n proceed\n\n" ]
[ 5, 1 ]
[]
[]
[ "google_app_engine", "image", "python" ]
stackoverflow_0002831713_google_app_engine_image_python.txt
Q: python: send a list/dict over network I'm looking for an easy way of packing/unpacking data structures for sending over the network: on client just before sending: a = ((1,2),(11,22,),(111,222)) message = pack(a) and then on server: a = unpack(message) Is there a library that could do pack/unpack magic? Thanks in advance A: Looks like JSON might fit the bill. It's simple, and it's in the Python standard library. It might not be too happy about the tuples, though: >>> import json >>> a = ((1,2),(11,22,),(111,222)) >>> print a ((1, 2), (11, 22), (111, 222)) >>> message = json.dumps(a) >>> message '[[1, 2], [11, 22], [111, 222]]' >>> b = json.loads(message) >>> b [[1, 2], [11, 22], [111, 222]] Whether or not that's a problem is for you to decide. A: See pickle - Python object serialization: The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”. A: ast.literal_eval() preserves tuples: >>> a = ((1,2),(11,22,),(111,222)) >>> s = repr(a) >>> import ast >>> ast.literal_eval(s) ((1, 2), (11, 22), (111, 222))
python: send a list/dict over network
I'm looking for an easy way of packing/unpacking data structures for sending over the network: on client just before sending: a = ((1,2),(11,22,),(111,222)) message = pack(a) and then on server: a = unpack(message) Is there a library that could do pack/unpack magic? Thanks in advance
[ "Looks like JSON might fit the bill. It's simple, and it's in the Python standard library.\nIt might not be too happy about the tuples, though:\n>>> import json\n>>> a = ((1,2),(11,22,),(111,222))\n>>> print a\n((1, 2), (11, 22), (111, 222))\n>>> message = json.dumps(a)\n>>> message\n'[[1, 2], [11, 22], [111, 222]]'\n>>> b = json.loads(message)\n>>> b\n[[1, 2], [11, 22], [111, 222]]\n\nWhether or not that's a problem is for you to decide. \n", "See pickle - Python object serialization:\n\nThe pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”.\n\n", "ast.literal_eval() preserves tuples:\n>>> a = ((1,2),(11,22,),(111,222))\n>>> s = repr(a)\n>>> import ast\n>>> ast.literal_eval(s)\n((1, 2), (11, 22), (111, 222))\n\n" ]
[ 12, 2, 1 ]
[]
[]
[ "python", "serialization" ]
stackoverflow_0002562359_python_serialization.txt
Q: how to import the blog.py(i import the 'blog' folder) my dir location,i am in a.py: my_Project |----blog |-----__init__.py |-----a.py |-----blog.py when i 'from blog import something' in a.py , it show error: from blog import BaseRequestHandler ImportError: cannot import name BaseRequestHandler i think it import the blog folder,not the blog.py so how to import the blog.py updated when i use 'blog.blog', it show this: from blog.blog import BaseRequestHandler ImportError: No module named blog updated2 my sys.path is : ['D:\\zjm_code', 'D:\\Python25\\lib\\site-packages\\setuptools-0.6c11-py2.5.egg', 'D:\\Python25\\lib\\site-packages\\whoosh-0.3.18-py2.5.egg', 'C:\\WINDOWS\\system32\\python25.zip', 'D:\\Python25\\DLLs', 'D:\\Python25\\lib', 'D:\\Python25\\lib\\plat-win', 'D:\\Python25\\lib\\lib-tk', 'D:\\Python25', 'D:\\Python25\\lib\\site-packages', 'D:\\Python25\\lib\\site-packages\\PIL'] zjm_code |-----a.py |-----b.py a.py is : c="ccc" b.py is : from a import c print c and when i execute b.py ,i show this: > "D:\Python25\pythonw.exe" "D:\zjm_code\b.py" Traceback (most recent call last): File "D:\zjm_code\b.py", line 2, in <module> from a import c ImportError: cannot import name c A: When you are in a.py, import blog should import the local blog.py and nothing else. Quoting the docs: modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script So my guess is that somehow, the name BaseRequestHandler is not defined in the file blog.py. A: what happens when you: import blog Try outputting your sys.path, in order to make sure that you have the right dir to call the module from.
how to import the blog.py(i import the 'blog' folder)
my dir location,i am in a.py: my_Project |----blog |-----__init__.py |-----a.py |-----blog.py when i 'from blog import something' in a.py , it show error: from blog import BaseRequestHandler ImportError: cannot import name BaseRequestHandler i think it import the blog folder,not the blog.py so how to import the blog.py updated when i use 'blog.blog', it show this: from blog.blog import BaseRequestHandler ImportError: No module named blog updated2 my sys.path is : ['D:\\zjm_code', 'D:\\Python25\\lib\\site-packages\\setuptools-0.6c11-py2.5.egg', 'D:\\Python25\\lib\\site-packages\\whoosh-0.3.18-py2.5.egg', 'C:\\WINDOWS\\system32\\python25.zip', 'D:\\Python25\\DLLs', 'D:\\Python25\\lib', 'D:\\Python25\\lib\\plat-win', 'D:\\Python25\\lib\\lib-tk', 'D:\\Python25', 'D:\\Python25\\lib\\site-packages', 'D:\\Python25\\lib\\site-packages\\PIL'] zjm_code |-----a.py |-----b.py a.py is : c="ccc" b.py is : from a import c print c and when i execute b.py ,i show this: > "D:\Python25\pythonw.exe" "D:\zjm_code\b.py" Traceback (most recent call last): File "D:\zjm_code\b.py", line 2, in <module> from a import c ImportError: cannot import name c
[ "When you are in a.py, import blog should import the local blog.py and nothing else. Quoting the docs:\n\nmodules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script\n\nSo my guess is that somehow, the name BaseRequestHandler is not defined in the file blog.py.\n", "what happens when you:\nimport blog\n\nTry outputting your sys.path, in order to make sure that you have the right dir to call the module from.\n" ]
[ 1, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002832646_import_python.txt
Q: how to import a.py not a folder zjm_code |-----a.py |-----a |----- __init__.py |-----b.py in a.py is : c='ccc' in b.py is : import a print dir(a) when i execute b.py ,it show (it import 'a' folder): ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] and when i delete a folder, it show ,(it import a.py): ['__builtins__', '__doc__', '__file__', '__name__', 'c'] so my question is : how to import a.py via not delete a folder thanks updated i use imp.load_source, so in b.py is : import imp,os path = os.path.join(os.path.dirname(__file__), os.path.join('aaa.py')) ok=imp.load_source('*',path) print ok.c it is ok now ,and print 'ccc' and how to show 'ccc' via "print c" not via "print ok.c" ??? thanks updated2 it is ok now : imp.load_source('anyname',path) from anyname import * print c it show 'ccc' updated3 it is also ok: import imp,os imp.load_source('anyname','aaa.py') from anyname import * print c A: Use imp.load_module - there you can specify the file directory, overriding the behaviour of import. A: Rename the folder to a different name. A folder with the same name takes precedence.
how to import a.py not a folder
zjm_code |-----a.py |-----a |----- __init__.py |-----b.py in a.py is : c='ccc' in b.py is : import a print dir(a) when i execute b.py ,it show (it import 'a' folder): ['__builtins__', '__doc__', '__file__', '__name__', '__path__'] and when i delete a folder, it show ,(it import a.py): ['__builtins__', '__doc__', '__file__', '__name__', 'c'] so my question is : how to import a.py via not delete a folder thanks updated i use imp.load_source, so in b.py is : import imp,os path = os.path.join(os.path.dirname(__file__), os.path.join('aaa.py')) ok=imp.load_source('*',path) print ok.c it is ok now ,and print 'ccc' and how to show 'ccc' via "print c" not via "print ok.c" ??? thanks updated2 it is ok now : imp.load_source('anyname',path) from anyname import * print c it show 'ccc' updated3 it is also ok: import imp,os imp.load_source('anyname','aaa.py') from anyname import * print c
[ "Use imp.load_module - there you can specify the file directory, overriding the behaviour of import.\n", "Rename the folder to a different name. A folder with the same name takes precedence.\n" ]
[ 2, 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0002832865_import_python.txt
Q: Possible to access gdata api when using Java App Engine? I have a dilemma where I want to create an application that manipulates google contacts information. The problem comes down to the fact that Python only supports version 1.0 of the api whilst Java supports 3.0. I also want it to be web-based so I'm having a look at google app engine, but it seems that only the python version of app engine supports the import of gdata apis whilst java does not. So its either web based and version 1.0 of the api or non-web based and version 3.0 of the api. I actually need version 3.0 to get access to the extra fields provided by google contacts. So my question is, is there a way to get access to the gdata api under Google App Engine using Java? If not is there an ETA on when version 3.0 of the gdata api will be released for python? Cheers. A: I'm having a look into the google data api protocol which seems to solve the problem. A: Google Data API Java Client : link1 Getting Started with the Google Data Java Client Library link2 I guess this is what you were looking for. A: I use GDATA apis for my JAVA appengine webapp. So GDATA can be used with JAVA runtime. From http://code.google.com/appengine/kb/java.html Yes, the Google Data Java client library can be used in App Engine, but you need to set a configuration option to avoid a runtime permissions error. Add the following to your appengine-web.xml file: <system-properties> <property name="com.google.gdata.DisableCookieHandler" value="true"/> </system-properties> If the following is not included, you may see the following exception: java.security.AccessControlException: access denied (java.net.NetPermission getCookieHandler)
Possible to access gdata api when using Java App Engine?
I have a dilemma where I want to create an application that manipulates google contacts information. The problem comes down to the fact that Python only supports version 1.0 of the api whilst Java supports 3.0. I also want it to be web-based so I'm having a look at google app engine, but it seems that only the python version of app engine supports the import of gdata apis whilst java does not. So its either web based and version 1.0 of the api or non-web based and version 3.0 of the api. I actually need version 3.0 to get access to the extra fields provided by google contacts. So my question is, is there a way to get access to the gdata api under Google App Engine using Java? If not is there an ETA on when version 3.0 of the gdata api will be released for python? Cheers.
[ "I'm having a look into the google data api protocol which seems to solve the problem.\n", "Google Data API Java Client : link1\nGetting Started with the Google Data Java Client Library link2 \nI guess this is what you were looking for.\n", "I use GDATA apis for my JAVA appengine webapp. So GDATA can be used with JAVA runtime.\nFrom http://code.google.com/appengine/kb/java.html\n\nYes, the Google Data Java client library can be used in App Engine, but you need to set a configuration option to avoid a runtime permissions error. Add the following to your appengine-web.xml file:\n\n<system-properties>\n <property name=\"com.google.gdata.DisableCookieHandler\" value=\"true\"/>\n</system-properties>\n\n\nIf the following is not included, you\n may see the following exception:\n java.security.AccessControlException:\n access denied (java.net.NetPermission\n getCookieHandler)\n\n" ]
[ 0, 0, 0 ]
[]
[]
[ "gdata_api", "google_app_engine", "java", "python" ]
stackoverflow_0001148165_gdata_api_google_app_engine_java_python.txt