content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python (1..n) syntax? I see in the code on this Sage wiki page the following code: @interact def _(order=(1..12)): Is this (1..n) syntax unique to Sage or is it something in Python? Also, what does it do? A: It's Sage-specific. You can use preparse to see how it is desugared to: sage: preparse("(1..12)") '(ellipsis_iter(Integer(1),Ellipsis,Integer(12)))' See here for documentation of ellipsis_iter, here for information on the preparser. A: There was a Python PEP to add this notation to Python, but it was rejected. Robert Bradshaw decided to implement it anyways, but for the Sage preparser. He implemented the following: (a..b) -- like xrange, so an iterator [a..b] -- list, including endpoints [a,b,..,c] -- arithmetic progression A: This is not Python syntax. I would guess that it creates a range from 1 to 12. A: (1..n) syntax does not exist in Python.
Python (1..n) syntax?
I see in the code on this Sage wiki page the following code: @interact def _(order=(1..12)): Is this (1..n) syntax unique to Sage or is it something in Python? Also, what does it do?
[ "It's Sage-specific. You can use preparse to see how it is desugared to:\nsage: preparse(\"(1..12)\")\n'(ellipsis_iter(Integer(1),Ellipsis,Integer(12)))'\n\nSee here for documentation of ellipsis_iter, here for information on the preparser. \n", "There was a Python PEP to add this notation to Python, but it was r...
[ 13, 10, 1, 0 ]
[]
[]
[ "python", "sage" ]
stackoverflow_0003511699_python_sage.txt
Q: How to bind self events in Tkinter Text widget after it will binded by Text widget? I want to bind self events after Text widget class bindings, in order to change the text of the widget when my binding function is called. My binding, for example self.text.bind("<Key>", self.callback), is called before the content in Text widget changes. A: What is happening in your case is that your binding to print the value happens before the class binding, and it's the class binding that actually takes user input and puts it in the widget. There are several ways to solve this problem. You could bind to <KeyRelease> instead of <KeyPress>, or you could use the built-in entry validation features to have your code called on every key press. With that solution you'll be given all the data you need -- the value before the change, the value after the change, the key that was pressed, etc. Another choice is to change the order in which events are processed. Since your question specifically asked how to change the order, that is what I will address. Even though a binding appears to be associated with a widget when you do something like entry.bind(...), you're actually assigning a binding to a "bind tag" (or "bindtag"). By default each widget has a bindtag that is the same as the name of the widget. Other bindtags include the class of a widget (for example, "Entry"), the path of the root window (eg: ".") and the special tag "all". Widgets are assigned a set of bindtags which are processed in order when an event is received. The default order goes from most- to least-specific: widget, class, toplevel, all. There are a couple ways to manipulate the bindtags to get the result you desire. One choice is to rearrange the order of the bindtags. By moving the bindtag that represents the widget to be after the bindtag representing the class, the class will handle the event before passing it on to the specific widget. Another choice is to add an additional bindtag that is after the class binding, and then put your bindings on this tag rather than on the tag that represents the widget. Why choose one over the other? By rearranging the order you will affect all bindings on that widget. If you have many bindings and some depend on the order (so that the can, for example, disallow certain keystrokes), changing the order may cause those bindings to stop working. By introducing a new bindtag, you can choose which bindings happen before class bindings and which happen after. In the following code I create three entry widgets. The first uses the default set of bindtags (explicitly set in the example, though they are identical to the default). The second changes the order, and the third introduces an additional bindtag. Run the code then press a key while the focus is in each window. Notice that in the first entry widget the binding always seems to be one character behind. Again, this is because the widget binding happens before the class binding puts the character into the widget. In the second and third examples, the binding happens after the class binding so the function sees the change in the widgets. import Tkinter def OnKeyPress(event): value = event.widget.get() string="value of %s is '%s'" % (event.widget._name, value) status.configure(text=string) root = Tkinter.Tk() entry1 = Tkinter.Entry(root, name="entry1") entry2 = Tkinter.Entry(root, name="entry2") entry3 = Tkinter.Entry(root, name="entry3") # Three different bindtags. The first is just the default but I'm # including it for illustrative purposes. The second reverses the # order of the first two tags. The third introduces a new tag after # the class tag. entry1.bindtags(('.entry1', 'Entry', '.', 'all')) entry2.bindtags(('Entry', '.entry2', '.', 'all')) entry3.bindtags(('.entry3','Entry','post-class-bindings', '.', 'all')) btlabel1 = Tkinter.Label(text="bindtags: %s" % " ".join(entry1.bindtags())) btlabel2 = Tkinter.Label(text="bindtags: %s" % " ".join(entry2.bindtags())) btlabel3 = Tkinter.Label(text="bindtags: %s" % " ".join(entry3.bindtags())) status = Tkinter.Label(anchor="w") entry1.grid(row=0,column=0) btlabel1.grid(row=0,column=1, padx=10, sticky="w") entry2.grid(row=1,column=0) btlabel2.grid(row=1,column=1, padx=10, sticky="w") entry3.grid(row=2,column=0) btlabel3.grid(row=2,column=1, padx=10) status.grid(row=3, columnspan=2, sticky="w") # normally you bind to the widget; in the third case we're binding # to the new bindtag we've created entry1.bind("<KeyPress>", OnKeyPress) entry2.bind("<KeyPress>", OnKeyPress) entry3.bind_class("post-class-bindings", "<KeyPress>", OnKeyPress) root.mainloop()
How to bind self events in Tkinter Text widget after it will binded by Text widget?
I want to bind self events after Text widget class bindings, in order to change the text of the widget when my binding function is called. My binding, for example self.text.bind("<Key>", self.callback), is called before the content in Text widget changes.
[ "What is happening in your case is that your binding to print the value happens before the class binding, and it's the class binding that actually takes user input and puts it in the widget. There are several ways to solve this problem. You could bind to <KeyRelease> instead of <KeyPress>, or you could use the buil...
[ 35 ]
[]
[]
[ "binding", "events", "python", "text", "tkinter" ]
stackoverflow_0003501849_binding_events_python_text_tkinter.txt
Q: Enable gzip compression in a Grok - Zope - PasteScript environment I am trying to make my server send gzipped data. I have a grok application that runs over Paste (Paste-1.7.2-py2.4.egg) I have been trying to google how to make all that environment to serve data in gzip... But without success... I think the answer comes in http://pythonpaste.org/modules/gzipper.html but if I do this: [app:myAppsName] use = egg:grokserver filter-with = translogger filter-with = fileupload filter-with = gzip [filter:fileupload] use = egg:grokserver#fileupload [filter:gzip] use = egg:Paste#gzip [server:main] use = egg:Paste#http host = 0.0.0.0 port = 8080 it doesn't seem to do anything... Thank you in advance! A: Well... I am going to reply to myself... It turns out that modifying the .ini files in the way I detailed in my question was, indeed, activating the gzip compression. I thought that it wasn't doing anything because I believed what the Google Chrome's Developer Tools audits were saying... Said audits were still telling me to activate the gzip compression to improve the site's performance, but it turned out (by seeing the network traffic) that is was activated (and the audits were wrong)
Enable gzip compression in a Grok - Zope - PasteScript environment
I am trying to make my server send gzipped data. I have a grok application that runs over Paste (Paste-1.7.2-py2.4.egg) I have been trying to google how to make all that environment to serve data in gzip... But without success... I think the answer comes in http://pythonpaste.org/modules/gzipper.html but if I do this: [app:myAppsName] use = egg:grokserver filter-with = translogger filter-with = fileupload filter-with = gzip [filter:fileupload] use = egg:grokserver#fileupload [filter:gzip] use = egg:Paste#gzip [server:main] use = egg:Paste#http host = 0.0.0.0 port = 8080 it doesn't seem to do anything... Thank you in advance!
[ "Well... I am going to reply to myself... \nIt turns out that modifying the .ini files in the way I detailed in my question was, indeed, activating the gzip compression.\nI thought that it wasn't doing anything because I believed what the Google Chrome's Developer Tools audits were saying... Said audits were still ...
[ 1 ]
[]
[]
[ "grok", "gzip", "http", "paster", "python" ]
stackoverflow_0003391950_grok_gzip_http_paster_python.txt
Q: How to work with a new Python installation while having an old one installed? After a fresh installation of my Windows dev machine, I installed Python 2.7. Quickly I learnt that this was a mistake as many of the packages I use only work on Python 2.6. So I installed 2.6 also and now I have both installations. How can I make everything work with Python 2.6 instead of Python 2.7? Every time I install a package it installs into Python 2.7. Every time I run a .py file it runs using the 2.7 interpreter. Is there a way to completely uninstall Python 2.7? A: Most python installations come with an uninstaller that shows up in Add/Remove programs on Windows. It is certainly possible to have several versions installed. On my windows machine, I have Python 2.5, 2.6, 2.7 and 3.1. The "default" python is the one which occurs first in your system path. Also (depending on which installer you used), you may have to change the handler for .py files in the registry. If you want to run a particular version, then start python.exe from the appropriate directory (C:\Python26\python.exe). Managing packages should be pretty easy too. EXE packages are generally tied to the python version. PIL, for example has installers like PIL-1.1.7.win32-py2.5.exe for Python 2.5 and PIL-1.1.7.win32-py2.6.exe for Python 2.6. Other packages can be dropped into the right site-packages folder.
How to work with a new Python installation while having an old one installed?
After a fresh installation of my Windows dev machine, I installed Python 2.7. Quickly I learnt that this was a mistake as many of the packages I use only work on Python 2.6. So I installed 2.6 also and now I have both installations. How can I make everything work with Python 2.6 instead of Python 2.7? Every time I install a package it installs into Python 2.7. Every time I run a .py file it runs using the 2.7 interpreter. Is there a way to completely uninstall Python 2.7?
[ "Most python installations come with an uninstaller that shows up in Add/Remove programs on Windows.\nIt is certainly possible to have several versions installed. On my windows machine, I have Python 2.5, 2.6, 2.7 and 3.1. The \"default\" python is the one which occurs first in your system path. Also (depending on ...
[ 2 ]
[]
[]
[ "python", "uninstallation", "version", "windows" ]
stackoverflow_0003514444_python_uninstallation_version_windows.txt
Q: webpy: How to serve JSON Is it possible to use webpy to serve JSON? I built my website and I need to serve some information in JSON to interact with the Javascript on some pages. I try to look for answers in the documentation, but I'm not able to find anything. Thanks, Giovanni A: I wouldn't think you'd have to do any thing overly "special" for web.py to serve JSON. import web import json class index: def GET(self): pyDict = {'one':1,'two':2} web.header('Content-Type', 'application/json') return json.dumps(pyDict)
webpy: How to serve JSON
Is it possible to use webpy to serve JSON? I built my website and I need to serve some information in JSON to interact with the Javascript on some pages. I try to look for answers in the documentation, but I'm not able to find anything. Thanks, Giovanni
[ "I wouldn't think you'd have to do any thing overly \"special\" for web.py to serve JSON.\nimport web\nimport json\n\nclass index:\n def GET(self):\n pyDict = {'one':1,'two':2}\n web.header('Content-Type', 'application/json')\n return json.dumps(pyDict)\n\n" ]
[ 62 ]
[ "It is certainly possible to serve JSON from webpy, But if you and choosing a framework, I would look at starlight and my fork twilight (for documentation).\nIt has a JSON wrapper for fixing the http headers for your json response. \nit uses either the json or simplejson libraries for json handling the conversions ...
[ -6 ]
[ "python", "web.py" ]
stackoverflow_0003513446_python_web.py.txt
Q: how to force matplotlib to update a plot I am trying to construct a little GUI that has a plot which updates every time a new data sample is read. I would prefer not to run it with a timer, since the data will be arriving at differing intervals. Instead, I'm trying to make an implementation using signals, where the data collection function will emit a signal when data is read, and then the painting function will emit a signal when the painting is completed. The problem, as it appears right now, is that the canvas is not updating as soon as I call canvas.draw(). When this program runs, data_collect() and paint() alternate sending signals, but the figure is not updated until after I stop the process. How can I force matplotlib to update the figure whenever paint() is called? What follows is a relatively simple piece of example code which is not optimal, but hopefully will convey the flavor of what I'm trying to do... N_length = 150; count = [0]; def sinval(delay): k = 0; x = []; # set up data vector with sinusoidal data in it. while k < N_length: x.append(math.sin(2*math.pi*k/N_length)); k += 1; def next(): time.sleep(delay); outstring = "%0.3e" % (x[count[0]]); if (count[0] == (N_length-1)): count[0] = 0; else: count[0] += 1; return outstring; return next; class DesignerMainWindow(QtGui.QMainWindow, Ui_mplMainWindow): def __init__(self, parent = None): super(DesignerMainWindow, self).__init__(parent) self.setupUi(self) QtCore.QObject.connect(self.mplStartButton, QtCore.SIGNAL("clicked()"), self.start_graph); QtCore.QObject.connect(self.mplStopButton, QtCore.SIGNAL("clicked()"), self.stop_graph); QtCore.QObject.connect(self.mplQuitButton, QtCore.SIGNAL("clicked()"), QtGui.qApp, QtCore.SLOT("quit()")); QtCore.QObject.connect(self, QtCore.SIGNAL("data_collect()"), self.data_collect); QtCore.QObject.connect(self, QtCore.SIGNAL("paint()"), self.paint); def start_graph(self): # generates first "empty" plots self.user = []; self.l_user, = self.mpl.canvas.ax.plot([], self.user, label='sine wave'); # set up the axes. self.mpl.canvas.ax.set_xlim(0, 300); self.mpl.canvas.ax.set_ylim(-1.1, 1.1); self.mpl.canvas.draw(); # start the data collection process. self.delay = 0.05; self.next = sinval(self.delay); self.emit(QtCore.SIGNAL('data_collect()')); def data_collect(self): outstring = self.next(); self.user.append(float(outstring.split()[0])); self.l_user.set_data(range(len(self.user)), self.user); self.emit(QtCore.SIGNAL('paint()')); def paint(self): self.mpl.canvas.draw(); self.emit(QtCore.SIGNAL('data_collect()')); A: I'd guess that calling QCoreApplication::processEvents after paint() will help. More elegant would be to have a separate QThread for the reading. Take a look at this thread.
how to force matplotlib to update a plot
I am trying to construct a little GUI that has a plot which updates every time a new data sample is read. I would prefer not to run it with a timer, since the data will be arriving at differing intervals. Instead, I'm trying to make an implementation using signals, where the data collection function will emit a signal when data is read, and then the painting function will emit a signal when the painting is completed. The problem, as it appears right now, is that the canvas is not updating as soon as I call canvas.draw(). When this program runs, data_collect() and paint() alternate sending signals, but the figure is not updated until after I stop the process. How can I force matplotlib to update the figure whenever paint() is called? What follows is a relatively simple piece of example code which is not optimal, but hopefully will convey the flavor of what I'm trying to do... N_length = 150; count = [0]; def sinval(delay): k = 0; x = []; # set up data vector with sinusoidal data in it. while k < N_length: x.append(math.sin(2*math.pi*k/N_length)); k += 1; def next(): time.sleep(delay); outstring = "%0.3e" % (x[count[0]]); if (count[0] == (N_length-1)): count[0] = 0; else: count[0] += 1; return outstring; return next; class DesignerMainWindow(QtGui.QMainWindow, Ui_mplMainWindow): def __init__(self, parent = None): super(DesignerMainWindow, self).__init__(parent) self.setupUi(self) QtCore.QObject.connect(self.mplStartButton, QtCore.SIGNAL("clicked()"), self.start_graph); QtCore.QObject.connect(self.mplStopButton, QtCore.SIGNAL("clicked()"), self.stop_graph); QtCore.QObject.connect(self.mplQuitButton, QtCore.SIGNAL("clicked()"), QtGui.qApp, QtCore.SLOT("quit()")); QtCore.QObject.connect(self, QtCore.SIGNAL("data_collect()"), self.data_collect); QtCore.QObject.connect(self, QtCore.SIGNAL("paint()"), self.paint); def start_graph(self): # generates first "empty" plots self.user = []; self.l_user, = self.mpl.canvas.ax.plot([], self.user, label='sine wave'); # set up the axes. self.mpl.canvas.ax.set_xlim(0, 300); self.mpl.canvas.ax.set_ylim(-1.1, 1.1); self.mpl.canvas.draw(); # start the data collection process. self.delay = 0.05; self.next = sinval(self.delay); self.emit(QtCore.SIGNAL('data_collect()')); def data_collect(self): outstring = self.next(); self.user.append(float(outstring.split()[0])); self.l_user.set_data(range(len(self.user)), self.user); self.emit(QtCore.SIGNAL('paint()')); def paint(self): self.mpl.canvas.draw(); self.emit(QtCore.SIGNAL('data_collect()'));
[ "I'd guess that calling QCoreApplication::processEvents after paint() will help. More elegant would be to have a separate QThread for the reading. Take a look at this thread.\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "pyqt4", "python", "qt4", "signals_slots" ]
stackoverflow_0003514074_matplotlib_pyqt4_python_qt4_signals_slots.txt
Q: How do I parse only foreign characters from the text in an HTML file with regular expressions I'm trying to parse HTML and automatically change the font of any foreign characters, and I'm having some issues. There are a few different hackish ways I'm trying to accomplish this, but none work really well, and I'm wondering if anyone has any ideas. Is there any easy way with python to match all the foreign characters (specifically, Japanese Kanji/Hirigana/Katakana) with regular expressions? What I've been using is the complement of a set of non-foreign characters ([^A-Za-z0-9 <>'"=]), but this isn't working well, and I'm worried it will match things enclosed in <...>, which I don't want to do. A: I wouldn't use just regular expressions for this. Down that path lies an angry Tony the Pony. I'd use an HTML parser in conjuction with regular expressions, though. That way you can distinguish the markup from the non-markup. A: Use BeautifulSoup to get the content that you need, then use a variation on this code to match your characters. import re kataLetters = range(0x30A0, 0x30FF) hiraLetters = range(0x3040, 0x309F) kataPunctuation = range(0x31F0,0x31FF) myLetters = kataLetters+kataPunctuation+hiraLetters myLetters = u''.join([unichr(aLetter) for aLetter in myLetters]) myRe = re.compile('['+myLetters+']+', re.UNICODE) Use the code charts here to get the ranges for your characters.
How do I parse only foreign characters from the text in an HTML file with regular expressions
I'm trying to parse HTML and automatically change the font of any foreign characters, and I'm having some issues. There are a few different hackish ways I'm trying to accomplish this, but none work really well, and I'm wondering if anyone has any ideas. Is there any easy way with python to match all the foreign characters (specifically, Japanese Kanji/Hirigana/Katakana) with regular expressions? What I've been using is the complement of a set of non-foreign characters ([^A-Za-z0-9 <>'"=]), but this isn't working well, and I'm worried it will match things enclosed in <...>, which I don't want to do.
[ "I wouldn't use just regular expressions for this. Down that path lies an angry Tony the Pony.\nI'd use an HTML parser in conjuction with regular expressions, though. That way you can distinguish the markup from the non-markup.\n", "Use BeautifulSoup to get the content that you need, then use a variation on thi...
[ 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003514415_python_regex.txt
Q: How to use C extensions in python to get around GIL I want to run a cpu intensive program in Python across multiple cores and am trying to figure out how to write C extensions to do this. Are there any code samples or tutorials on this? A: You can already break a Python program into multiple processes. The OS will already allocate your processes across all the cores. Do this. python part1.py | python part2.py | python part3.py | ... etc. The OS will assure that part uses as many resources as possible. You can trivially pass information along this pipeline by using cPickle on sys.stdin and sys.stdout. Without too much work, this can often lead to dramatic speedups. Yes -- to the haterz -- it's possible to construct an algorithm so tortured that it may not be sped up much. However, this often yields huge benefits for minimal work. And. The restructuring for this purpose will exactly match the restructuring required to maximize thread concurrency. So. Start with shared-nothing process parallelism until you can prove that sharing more data would help, then move to the more complex shared-everything thread parallelism. A: Take a look at multiprocessing. It's an often overlooked fact that not globally sharing data, and not cramming loads of threads into a single process is what operating systems prefer. If you still insist that your CPU intensive behaviour requires threading, take a look at the documentation for working with the GIL in C. It's quite informative. A: This is a good use of C extension. The keyword you should search for is Py_BEGIN_ALLOW_THREADS. http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock P.S. I mean if you processing is already in C, like imaging processing, then release the lock in C extension is good. If your processing code is mainly in Python, other people's suggestion to multiprocessing is better. It is usually not justify to rewrite the code in C for background processing.
How to use C extensions in python to get around GIL
I want to run a cpu intensive program in Python across multiple cores and am trying to figure out how to write C extensions to do this. Are there any code samples or tutorials on this?
[ "You can already break a Python program into multiple processes. The OS will already allocate your processes across all the cores.\nDo this.\npython part1.py | python part2.py | python part3.py | ... etc.\n\nThe OS will assure that part uses as many resources as possible. You can trivially pass information along ...
[ 9, 7, 1 ]
[ "Have you considered using one of the python mpi libraries like mpi4py? Although MPI is normally used to distribute work across a cluster, it works quite well on a single multicore machine. The downside is that you'll have to refactor your code to use MPI's communication calls (which may be easy).\n", "multiproce...
[ -1, -2 ]
[ "python", "python_c_extension" ]
stackoverflow_0003514495_python_python_c_extension.txt
Q: What is wrong with this Python game code? import random secret = random.randint (1,99) guess = 0 tries = 0 print ("AHOY! I'm the Dread Pirate Roberts, and I have a secret!") print ("It is a number from 1 to 99. I'll give you 6 tries. ") while guess != secret and tries < 6: guess = input ("What's yer guess? ") if guess < secret: print ("Too low, ye scurvy dog") elif guess > secret: print ("Too high, landrubber!") tries = tries + 1 if guess == secret: print ("Avast! Ye got it! Found my secret, ye did!") else: print ("No more guesses! Better luck next time, matey!") print ("The secret number was", secret) I keep getting this error: if guess < secret: TypeError: unorderable types: str() < int() A: guess = input ("What's yer guess? ") Calling input gives you back a string, not an int. When you then compare guess using <, you need an int in order to compare a numerical value. Try doing something along the lines of: try: guess = int(input("What's yer guess? ")) except ValueError: # Handle bad input A: Because Python is strongly typed, you can't compare string and an int. What you get back from input() is a str not an int. So, you need to convert the str to an int before comparison is possible. guess = int(input("What's yer guess")) You should also handle the possible exception thrown when the input is not convertable to an int. So, the code becomes: try: guess = int(input("What's yer guess")) except ValueError: print ('Arrrrr... I said a number ye lily-livered dog') In addition, input() is unsafe, at least in Python 2.x. This is because input() accepts any valid Python statement. You should use raw_input() instead if you're using Python 2.x. If you're using Python 3, just disregard this bit. try: guess = int(raw_input("What's yer guess")) except ValueError: print 'Arrrrr... I said a number ye lily-livered dog' A: You spelled "landlubber" wrong. A landrubber is a person who caresses the ground. A landlubber is a person who doesn't know their way around a ship. And you need to parse your input to an int before you can compare it to an int.
What is wrong with this Python game code?
import random secret = random.randint (1,99) guess = 0 tries = 0 print ("AHOY! I'm the Dread Pirate Roberts, and I have a secret!") print ("It is a number from 1 to 99. I'll give you 6 tries. ") while guess != secret and tries < 6: guess = input ("What's yer guess? ") if guess < secret: print ("Too low, ye scurvy dog") elif guess > secret: print ("Too high, landrubber!") tries = tries + 1 if guess == secret: print ("Avast! Ye got it! Found my secret, ye did!") else: print ("No more guesses! Better luck next time, matey!") print ("The secret number was", secret) I keep getting this error: if guess < secret: TypeError: unorderable types: str() < int()
[ "guess = input (\"What's yer guess? \")\n\nCalling input gives you back a string, not an int. When you then compare guess using <, you need an int in order to compare a numerical value. Try doing something along the lines of:\ntry:\n guess = int(input(\"What's yer guess? \"))\nexcept ValueError:\n # Handle ...
[ 12, 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003514154_python.txt
Q: created sorted table in gtk What's the easieest way to create a sorted table view in gtk? I'm not sure if that's the right term, but you know the one: (source: sun.com) Is there a built-in widget for this? If not, how would I go about making those columns that look slightly different, click to change sorting, etc. Note I don't need multi-column sorting at the moment. A: Sorted List Stores UPDATE: After looking at your edit (disregarding commens): There is no built-in widget, but ListView = TreeView + ListStore Clicking to change sorting is harder, but probably not by much Remember that most anything is handled by their tutorial, at PyGTK.org (HTML) and in PDF Format. They also have a PyGTK Refrence, if that suits you better.
created sorted table in gtk
What's the easieest way to create a sorted table view in gtk? I'm not sure if that's the right term, but you know the one: (source: sun.com) Is there a built-in widget for this? If not, how would I go about making those columns that look slightly different, click to change sorting, etc. Note I don't need multi-column sorting at the moment.
[ "Sorted List Stores\nUPDATE:\nAfter looking at your edit (disregarding commens):\n\nThere is no built-in widget, but ListView = TreeView + ListStore\nClicking to change sorting is harder, but probably not by much\n\nRemember that most anything is handled by their tutorial, at PyGTK.org (HTML)\nand in PDF Format. Th...
[ 2 ]
[]
[]
[ "gtk", "pygtk", "python", "uitableview", "user_interface" ]
stackoverflow_0003513480_gtk_pygtk_python_uitableview_user_interface.txt
Q: Prevent normal users to execute I need a better way to prevent normal users from executing my python script. I'm doing something like that: if __name__ == '__main__': if os.getenv('USER') == 'root': addUser = addUser() else: print 'Only root can run that!' It's working, but it's pretty ugly! My script is about user management in a Debian system. A: Python code can be viewed and edited to circumvent any protection you put in, your best bet is to restrict executable access by user in debian so only root can execute/view/edit. See chmod A: It's more normal to restrict access to the resources an executable needs to work than to enforce permissions at the level of the executable. For example, the mount(8) command can normally be run by any user, but the device files needed to actually mount real volumes are restricted to certain users or groups, and the mount command checks to see if the operation would be possible before even attempting to make the syscalls to perform the device operations. This works as well with regular files. For instance, many linux package managers require a database of installed programs. Before installing anything, the package manager will check the permissions on the database file to see if the calling user could write to it, and also checks the destination directories to see if the user could modify those. even if the package manager does not perform these checks, they can't make those changes when they try, the kernel simply prevents the program from performing an action the owning user is not permitted to make.
Prevent normal users to execute
I need a better way to prevent normal users from executing my python script. I'm doing something like that: if __name__ == '__main__': if os.getenv('USER') == 'root': addUser = addUser() else: print 'Only root can run that!' It's working, but it's pretty ugly! My script is about user management in a Debian system.
[ "Python code can be viewed and edited to circumvent any protection you put in, your best bet is to restrict executable access by user in debian so only root can execute/view/edit.\nSee chmod\n", "It's more normal to restrict access to the resources an executable needs to work than to enforce permissions at the le...
[ 12, 5 ]
[]
[]
[ "debian", "python", "root" ]
stackoverflow_0003515062_debian_python_root.txt
Q: Refactoring Index/Search View I've written an index and search view all in one if a GET request is detected it returns just the search results otherwise it returns all records. I've written this view below but I feel like I'm repeating myself a bit too much. Any ideas as to how I can slim this code down a bit would be much appreciated. def index(request): if 'q' in request.GET: company_list = Company.objects.filter( Q(company__icontains = request.GET['q']) | Q(county__icontains = request.GET['q']) | Q(city__icontains = request.GET['q']) | Q(product_description__icontains = request.GET['q']) ) query = request.GET['q'] else: company_list = Company.objects.all() paginator = Paginator(company_list, 10) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: companies = paginator.page(page) except (EmptyPage, InvalidPage): companies = paginator.page(paginator.num_pages) if 'q' in request.GET: return render_response(request, 'database/index.html', {"companies": companies, "query": query}) else: return render_response(request, 'database/index.html', {"companies": companies}) A: Perhaps not the best way but for me this makes it a little bit more readable and minimizes repetition. def index(request): def get_companies(company_list): paginator = Paginator(company_list, 10)     try:         page = int(request.GET.get('page', '1'))     except ValueError:         page = 1     try:         companies = paginator.page(page)     except (EmptyPage, InvalidPage):         companies = paginator.page(paginator.num_pages) return companies     if 'q' in request.GET:         companies = get_companies( Company.objects.filter(             Q(company__icontains = request.GET['q']) |             Q(county__icontains = request.GET['q']) |             Q(city__icontains = request.GET['q']) |             Q(product_description__icontains = request.GET['q'])         ))         query = request.GET['q'] context = {"companies": companies, "query": query}     else: companies = get_companies(Company.objects.all()) context = {"companies": companies} return render_response(request, 'database/index.html',context) A: I ended up abstracting the pagination to a separate function, that looks like this. def pagination(request, objects, pages): paginator = Paginator(objects, pages) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: results = paginator.page(page) except (EmptyPage, InvalidPage): results = paginator.page(paginator.num_pages) return results And I was able to refactor the index/search function down to this. def index(request): if 'q' in request.GET: company_list = Company.objects.filter( Q(company__icontains = request.GET['q']) | Q(county__icontains = request.GET['q']) | Q(city__icontains = request.GET['q']) | Q(product_description__icontains = request.GET['q']) ) query = request.GET['q'] companies = pagination(request, company_list, 10) return render_response(request, 'database/index.html', {"companies": companies, "query": query}) else: company_list = Company.objects.all() companies = pagination(request, company_list, 10) return render_response(request, 'database/index.html', {"companies": companies}) I still don't like that I am repeating the pagination line but it seems a bit better.
Refactoring Index/Search View
I've written an index and search view all in one if a GET request is detected it returns just the search results otherwise it returns all records. I've written this view below but I feel like I'm repeating myself a bit too much. Any ideas as to how I can slim this code down a bit would be much appreciated. def index(request): if 'q' in request.GET: company_list = Company.objects.filter( Q(company__icontains = request.GET['q']) | Q(county__icontains = request.GET['q']) | Q(city__icontains = request.GET['q']) | Q(product_description__icontains = request.GET['q']) ) query = request.GET['q'] else: company_list = Company.objects.all() paginator = Paginator(company_list, 10) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: companies = paginator.page(page) except (EmptyPage, InvalidPage): companies = paginator.page(paginator.num_pages) if 'q' in request.GET: return render_response(request, 'database/index.html', {"companies": companies, "query": query}) else: return render_response(request, 'database/index.html', {"companies": companies})
[ "Perhaps not the best way but for me this makes it a little bit more readable and minimizes repetition.\ndef index(request):\n def get_companies(company_list):\n paginator = Paginator(company_list, 10)\n\n    try:\n        page = int(request.GET.get('page', '1'))\n    except ValueError:\n     ...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003506393_django_python.txt
Q: Detecting timeout erros in Python's urllib2 urlopen I'm still relatively new to Python, so if this is an obvious question, I apologize. My question is in regard to the urllib2 library, and it's urlopen function. Currently I'm using this to load a large amount of pages from another server (they are all on the same remote host) but the script is killed every now and then by a timeout error (I assume this is from the large requests). Is there a way to keep the script running after a timeout? I'd like to be able to fetch all of the pages, so I want a script that will keep trying until it gets a page, and then moves on. On a side note, would keeping the connection open to the server help? A: Next time the error occurs, take note of the error message. The last line will tell you the type of exception. For example, it might be a urllib2.HTTPError. Once you know the type of exception raised, you can catch it in a try...except block. For example: import urllib2 import time for url in urls: while True: try: sock=urllib2.urlopen(url) except (urllib2.HTTPError, urllib2.URLError) as err: # You may want to count how many times you reach here and # do something smarter if you fail too many times. # If a site is down, pestering it every 10 seconds may not # be very fruitful or polite. time.sleep(10) else: # Success contents=sock.read() # process contents break # break out of the while loop A: The missing manual of urllib2 might help you
Detecting timeout erros in Python's urllib2 urlopen
I'm still relatively new to Python, so if this is an obvious question, I apologize. My question is in regard to the urllib2 library, and it's urlopen function. Currently I'm using this to load a large amount of pages from another server (they are all on the same remote host) but the script is killed every now and then by a timeout error (I assume this is from the large requests). Is there a way to keep the script running after a timeout? I'd like to be able to fetch all of the pages, so I want a script that will keep trying until it gets a page, and then moves on. On a side note, would keeping the connection open to the server help?
[ "Next time the error occurs, take note of the error message. The last line will tell you the type of exception. For example, it might be a urllib2.HTTPError. Once you know the type of exception raised, you can catch it in a try...except block. For example:\nimport urllib2\nimport time\n\nfor url in urls:\n while...
[ 2, 1 ]
[]
[]
[ "python", "urllib2", "urlopen" ]
stackoverflow_0003515087_python_urllib2_urlopen.txt
Q: Can an API tell Pylint not to complain in the client code? I have some code in a reusable class that modifies some types. Here's a simplified version. class Foo: def __init__(self): self.count = 0 def increment(self): self.count += 1 # Add another method outside of the class definition. # Pylint doesn't care about this, and rates this file 10/10. Foo.__dict__["current_count"] = lambda self: self.count In the real code, "current_count" is a variable, not a fixed string, which is why I didn't write: Foo.current_count = lambda self: self.count # Cannot do in my scenario. Now, when my clients come to use the new function, Pylint jumps up and down in horror. import server_api def main(): foo_count = server_api.Foo() foo_count.increment() print foo_count.current_count() # Pylint complains here: # E1101: 8:main: Instance of 'Foo' has no 'current_count' member # I don't want to have to tell pylint to disable that message in every client. main() Every class that uses this new function gets chastised, and I am forced to disable the message in every reference. I would RATHER put some code in the API to tell Pylint to chill when there are unknown references on this class. Alas, the pylint documentation is... ummm... not of a quality conducive to my understanding, and I have been unable to find any suggestions there. So boiling it down: Can I tell pylint in my API code to turn off the E1101 rule in relation to this class, whenever a client refers to it? Is there another solution? A: Here is my solution inspired by the example in ActiveState cookbook recipe, provided in Yoni H's answer. To the Foo class, I added this useless __getattr__ method. def __getattr__(self, name): # This is only called when the normal mechanism fails, so in practice should never be called. # It is only provided to satisfy pylint that it is okay not to raise E1101 errors in the client code. raise AttributeError("%r instance has no attribute %r" % (self, name)) This should be nigh indistinguishable from the previous version. It should not be called in the normal course of events, but it is enough to persuade pylint to remain quiet about this error. p.s. You are allowed to grumble that this code isn't very pretty. I share that opinion. But I think its benefits for the client outweigh its code smell. A: Following one your comments, since you're going for an Enumerated type, why not have a look at this SO question, or this ActiveState cookbook recipe? Out of personal preference, I'd choose adding the enumerated types into the class, just like one of the answers in SO question (copied shamelessly for context): class Animal: def __init__(self, name): self.name = name def __str__(self): return self.name def __repr__(self): return "<Animal: %s>" % self Animal.DOG = Animal("dog") Animal.CAT = Animal("cat") A: Pragmatically speaking, why the assumption that pylint (or any lint) should be silent? Given a bias between false positives and false negatives, lints should prefer the former. It seems to me that because Pylint expresses its results as a score that people assume it should be maximized, but there is no prize for "winning". On the other hand, the construct it is complaining about is certainly ugly. I understand that the server_api is simplified for our convenience, but do you really need to muck about with the module namespace? From your client code it appears that the current_count method name is hard coded, why not in the server?
Can an API tell Pylint not to complain in the client code?
I have some code in a reusable class that modifies some types. Here's a simplified version. class Foo: def __init__(self): self.count = 0 def increment(self): self.count += 1 # Add another method outside of the class definition. # Pylint doesn't care about this, and rates this file 10/10. Foo.__dict__["current_count"] = lambda self: self.count In the real code, "current_count" is a variable, not a fixed string, which is why I didn't write: Foo.current_count = lambda self: self.count # Cannot do in my scenario. Now, when my clients come to use the new function, Pylint jumps up and down in horror. import server_api def main(): foo_count = server_api.Foo() foo_count.increment() print foo_count.current_count() # Pylint complains here: # E1101: 8:main: Instance of 'Foo' has no 'current_count' member # I don't want to have to tell pylint to disable that message in every client. main() Every class that uses this new function gets chastised, and I am forced to disable the message in every reference. I would RATHER put some code in the API to tell Pylint to chill when there are unknown references on this class. Alas, the pylint documentation is... ummm... not of a quality conducive to my understanding, and I have been unable to find any suggestions there. So boiling it down: Can I tell pylint in my API code to turn off the E1101 rule in relation to this class, whenever a client refers to it? Is there another solution?
[ "Here is my solution inspired by the example in ActiveState cookbook recipe, provided in Yoni H's answer.\nTo the Foo class, I added this useless __getattr__ method.\ndef __getattr__(self, name):\n # This is only called when the normal mechanism fails, so in practice should never be called.\n # It is only pr...
[ 6, 2, 0 ]
[]
[]
[ "pylint", "python" ]
stackoverflow_0003509599_pylint_python.txt
Q: Google App Engine and Amazon S3 File Uploads I know this has been asked before but there is really not a clear answer. My problem is I built a file upload script for GAE and only found out after, that you can only store files up to aprox. 1MB in the data store. I can stop you right here if you can tell me that if I enable billing the 1MB limit is history but I doubt it. I need to be able to upload up to 20mb per file so I thought maybe I can use Amazon's S3. Any ideas on how to accomplish this? I was told to use a combination of GAE + Ec2 and S3 but I have no idea how this would work. Thanks, Max A: From the Amazon S3 documentation: The user opens a web browser and accesses your web page. Your web page contains an HTTP form that contains all the information necessary for the user to upload content to Amazon S3. The user uploads content directly to Amazon S3. GAE prepares and serves the web page, a speedy operation. You user uploads to S3, a lengthy operation, but that is between your user's browser and Amazon; GAE is not involved. Part of the S3 protocol is a success_action_redirect, that lets you tell S3 where to aim the browser in the event of a successful upload. That redirect can be to GAE. A: Google App Engine and EC2 are competitors. They do the same thing, although GAE provides an environment for your app to run in with strict language restrictions, while EC2 provides you a virtual machine ( think VMWare ) on which to host your application. S3 on the other hand is a raw storage api. You can use a SOAP or REST api to access it. If you want to stick with GAE, you can simply use the Amazon S3 Python Library to make REST calls from Python to S3. You will, of course, have to pay for usage on S3. Its amazing how granular their billing is. When getting started I was literally charged 4 cents one month. A: For future reference, Google added support for large file upload (up to 50 MB): The new feature was released as part of the Blobstore API and is discussed here. A: Thomas L Holaday's answer is the correct answer, I suppose. Anyway, just in case, here's a link to Amazon Web Services SDK for App Engine (Java), which you can use e.g. to upload files from App Engine to Amazon S3. (Edit: Oh, just noticed -- excepting S3) http://apetresc.wordpress.com/2010/06/22/introducing-the-gae-aws-sdk-for-java/ Written by Adrian Petrescu. From his web site: [It is] a version of the Amazon Web Services SDK for Java that will run from inside of Google App Engine. This wouldn’t work if you simply included the JAR that AWS provides directly into GAE’s WAR, because GAE’s security model doesn’t allow the Apache Commons HTTP Client to create the sockets and low-level networking primitives it requires to establish an HTTP connection; instead, Google requires you to make all connections through its URLFetch utility A: Some Google App Engine + S3 links: Previous related post... 10mb limit. This link demonstrates small file uploads. I haven't found an example of large uploads yet... This link shows a different approach, (with a fix for a known issue)
Google App Engine and Amazon S3 File Uploads
I know this has been asked before but there is really not a clear answer. My problem is I built a file upload script for GAE and only found out after, that you can only store files up to aprox. 1MB in the data store. I can stop you right here if you can tell me that if I enable billing the 1MB limit is history but I doubt it. I need to be able to upload up to 20mb per file so I thought maybe I can use Amazon's S3. Any ideas on how to accomplish this? I was told to use a combination of GAE + Ec2 and S3 but I have no idea how this would work. Thanks, Max
[ "From the Amazon S3 documentation:\n\nThe user opens a web browser and accesses your web page.\nYour web page contains an HTTP form that contains all the information necessary for the user to upload content to Amazon S3.\nThe user uploads content directly to Amazon S3.\n\nGAE prepares and serves the web page, a spe...
[ 13, 3, 2, 1, 0 ]
[]
[]
[ "amazon_ec2", "amazon_s3", "google_app_engine", "python" ]
stackoverflow_0000972895_amazon_ec2_amazon_s3_google_app_engine_python.txt
Q: Python print statements being buffered with > output redirection I'm doing print statements in python. I'm executing my script like so: python script.py > out.log nohup & The print statements are not all showing up in out.log but the program is finishing ok. That line of code is in an .sh file I execute by doing ./script.sh Update: The log does get all the data but not until a certain # of lines are printed. It would appear to be buffering the output. A: When stdout is sent to a tty it will be line buffered and will be flushed every line, but when redirected to a file or pipe it'll be fully buffered and will only be flushed periodically when you overrun the buffer. You'll have to add sys.stdout.flush() calls after each line if you want the output to be immediately visible, or disable buffering entirely. See Disable output buffering for ways to do the latter: Use the -u command line switch Wrap sys.stdout in an object that flushes after every write Set PYTHONUNBUFFERED env var sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) A: Did you try: Running it without the redirection and making sure everything is printed as expected Running it not through a shell script, but simply from a command line ? These steps may help you "home in" on the problem.
Python print statements being buffered with > output redirection
I'm doing print statements in python. I'm executing my script like so: python script.py > out.log nohup & The print statements are not all showing up in out.log but the program is finishing ok. That line of code is in an .sh file I execute by doing ./script.sh Update: The log does get all the data but not until a certain # of lines are printed. It would appear to be buffering the output.
[ "When stdout is sent to a tty it will be line buffered and will be flushed every line, but when redirected to a file or pipe it'll be fully buffered and will only be flushed periodically when you overrun the buffer.\nYou'll have to add sys.stdout.flush() calls after each line if you want the output to be immediatel...
[ 27, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0003515757_linux_python.txt
Q: PIL save as 24 bit true color bitmap I have a png file generated by Gnuplot that I need to put into an excel document using XLWT. XLWT can't import PNG's into the document, only BMP's, so I needed to convert the PNG first. I used PIL for this. Here's the relevant code: im = Image.open('%s' % os.path.join(os.getcwd(), s + '.png')) im.save('%s.bmp' % s) However XLWT gives me this error: Exception: bitmap isn't a 24bit true color bitmap. Here's what the XLWT code looks like: self.chart.insert_bitmap(path, 2, 2) I know both images work fine, they're both openable by windows. I've also tried adding a 2 second pause after creating the BMP (to make up for write time), but it still fails. How do I go about making a 24 bit true color bitmap using PIL? A: Nevermind! Just figured it out myself. Change im = Image.open('%s' % os.path.join(os.getcwd(), s + '.png')) To im = Image.open('%s' % os.path.join(os.getcwd(), s + '.png')).convert("RGB")
PIL save as 24 bit true color bitmap
I have a png file generated by Gnuplot that I need to put into an excel document using XLWT. XLWT can't import PNG's into the document, only BMP's, so I needed to convert the PNG first. I used PIL for this. Here's the relevant code: im = Image.open('%s' % os.path.join(os.getcwd(), s + '.png')) im.save('%s.bmp' % s) However XLWT gives me this error: Exception: bitmap isn't a 24bit true color bitmap. Here's what the XLWT code looks like: self.chart.insert_bitmap(path, 2, 2) I know both images work fine, they're both openable by windows. I've also tried adding a 2 second pause after creating the BMP (to make up for write time), but it still fails. How do I go about making a 24 bit true color bitmap using PIL?
[ "Nevermind! Just figured it out myself.\nChange\nim = Image.open('%s' % os.path.join(os.getcwd(), s + '.png'))\n\nTo\nim = Image.open('%s' % os.path.join(os.getcwd(), s + '.png')).convert(\"RGB\")\n\n" ]
[ 7 ]
[]
[]
[ "gnuplot", "python", "python_imaging_library", "xlwt" ]
stackoverflow_0003516144_gnuplot_python_python_imaging_library_xlwt.txt
Q: OpenID auth: which method to get a unique identifier to use as key? Using OpenID auth, which is the proper User instance method to get a unique identifier useful for creating and identifying a user on Datastore as key_name? Available methods : nickname() For OpenID users, the nickname is the OpenID identifier. federated_identity() Returns the user's OpenID identifier. federated_provider() Returns the URL of the user's OpenID provider. On user logins i would like to retrieve it by: User.get_by_key_name(key_used_to_create_the_user) A: You will probably want to generate your own user ID for within your system so that users can change their OpenID providers (or even have more than one OpenID associated with their account, which many sites support). But if you did want to use the OpenID as a unique key for some reason, I think federated_identity() is the one you want (just from reading the docs, I have never used this library). You want their full OpenID URL, which is guaranteed to be unique -- this includes both the provider portion of the URL and the "username" portion (which maybe be a "subfolder" or subdomain, etc). Sorry I've forgotten the technical terms... been a while since I used OpenID.
OpenID auth: which method to get a unique identifier to use as key?
Using OpenID auth, which is the proper User instance method to get a unique identifier useful for creating and identifying a user on Datastore as key_name? Available methods : nickname() For OpenID users, the nickname is the OpenID identifier. federated_identity() Returns the user's OpenID identifier. federated_provider() Returns the URL of the user's OpenID provider. On user logins i would like to retrieve it by: User.get_by_key_name(key_used_to_create_the_user)
[ "You will probably want to generate your own user ID for within your system so that users can change their OpenID providers (or even have more than one OpenID associated with their account, which many sites support). But if you did want to use the OpenID as a unique key for some reason, I think federated_identity(...
[ 2 ]
[]
[]
[ "google_app_engine", "openid", "python" ]
stackoverflow_0003516241_google_app_engine_openid_python.txt
Q: How to reassign a string after removing parts of it by index I have a string s = 'texttexttextblahblah",".' and I want to cut of some of the rightmost characters by indexing and assign it to s so that s will be equal to texttexttextblahblah". I've looked around and found how to print by indexing, but not how to reassign that actual variable to be trimmed. A: Just reassign what you printed to the variable. >>> s = 'texttexttextblahblah",".' >>> s = s[:-3] >>> s 'texttexttextblahblah"' >>> Unless you know exactly how many text and blah's you'll have, use .find() as Brent suggested (or .index(x), which is like find, except complains when it doesn't find x). If you want that trailing ", just add one to the value it kicks out. (or just find the value you actually want to split at, ,) s = s[:s.find('"') + 1] A: If you need something that works like a string, but is mutable you can use a bytearray: >>> s = bytearray('texttexttextblahblah",".') >>> s[20:] = '' >>> print s texttexttextblahblah bytearray has all the usual string methods. A: Strings are immutable so you can't really change the string in-place. You'll need to slice out the part you want and then reassign it back over the original variable. Is something like this what you wanted? (note I left out storing the index in a variable because I'm not sure how you're using this): >>> s = 'texttexttextblahblah",".' >>> s.index('"') 20 >>> s = s[:20] >>> s 'texttexttextblahblah' A: I myself prefer to do it without indexing: (My favorite partition was commented as winner in speed and clearness in comments so I updated the original code) s = 'texttexttextblahblah",".' s,_,_ = s.partition(',') print s Result texttexttextblahblah"
How to reassign a string after removing parts of it by index
I have a string s = 'texttexttextblahblah",".' and I want to cut of some of the rightmost characters by indexing and assign it to s so that s will be equal to texttexttextblahblah". I've looked around and found how to print by indexing, but not how to reassign that actual variable to be trimmed.
[ "Just reassign what you printed to the variable.\n>>> s = 'texttexttextblahblah\",\".'\n>>> s = s[:-3]\n>>> s\n'texttexttextblahblah\"'\n>>>\n\nUnless you know exactly how many text and blah's you'll have, use .find() as Brent suggested (or .index(x), which is like find, except complains when it doesn't find x).\nI...
[ 16, 8, 5, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003516571_python_string.txt
Q: Can I execute sudo make install twice from different locations? I am on Mac, Snow Lepard. In preparation to install PIL I need to install libjpeg. So, from my home directory I did: tar zxvf jpegsrc.v6b.tar.gz cd jpeg-6b cp /usr/share/libtool/config/config.sub . cp /usr/share/libtool/config/config.guess . ./configure --enable-shared --enable-static make sudo make install But actually I read later it would have been better to this from src directory to keep all source together neatly. Can I just do the above over from /usr/local/src or will that mess up my system? A: The question doesn't really have much to do with Python...;-). Anyway, yes, repeating the same steps in a different directory should "overwrite" the installation you just performed.
Can I execute sudo make install twice from different locations?
I am on Mac, Snow Lepard. In preparation to install PIL I need to install libjpeg. So, from my home directory I did: tar zxvf jpegsrc.v6b.tar.gz cd jpeg-6b cp /usr/share/libtool/config/config.sub . cp /usr/share/libtool/config/config.guess . ./configure --enable-shared --enable-static make sudo make install But actually I read later it would have been better to this from src directory to keep all source together neatly. Can I just do the above over from /usr/local/src or will that mess up my system?
[ "The question doesn't really have much to do with Python...;-). Anyway, yes, repeating the same steps in a different directory should \"overwrite\" the installation you just performed.\n" ]
[ 2 ]
[]
[]
[ "libjpeg", "macos", "python", "python_imaging_library" ]
stackoverflow_0003516680_libjpeg_macos_python_python_imaging_library.txt
Q: Once I have identified the beginning and end parts of a section of an html document using lxml, how do I get everything between them I am working with some html files. I am trying to figure out a way to consistently get to some text that exists in the documents. I know that the section I want begins with some bolded words and I know that the section ends with other bolded words. bolded_item=atree.cssselect('b') myKeys=[item for item in bolded_items if item.text if 'KEY' in item.text] so myKeys is a list whose members are elements from atree, specifically elements that have bolded text and have the word 'KEY' in the text. I want now to identify all of the parts of the tree between any 2 elements in myKeys I want to be able to manipulate them in various ways. I was playing around with getparent, getchildren getnext and all of the other methods that looked likely after running a dir(myKeys[0]) but I am not making progress. Any suggestions would be appreciated A: I'd suggest using SAX for this task. Basic docs are available at http://lxml.de/sax.html#producing-sax-events-from-an-elementtree-or-element Your handler should consume events w/out any action till it receives needed bolded item, and then it writes events into new buffer/tree/whatever till it receives terminating bolded item. A: In the spirit of SO I have figured out what I think is the best answer and am going to post it myself. import lxml from lxml import html testFile=open(r'c:\temp\testlxml.htm').read() aTree=html.fromstring(testFile) bolds=aTree.cssselect('b') theTitles=[item.text for item in bolds if item.text if 'KEY' in item.text] theBoldKeys=[item for item in bolds if item.text if 'KEY' in item.text] theFullList=[] for e in aTree.iter(): theFullList.append(e) for numb,item in enumerate(theFullList): if item==theBoldItems[0]: first=numb if item==theBoldItems[1]: second=numb theText=[] for item in theFullList[first:second]: if item.text: theText.append(item.text) if item.tail: theText.append(item.tail) aString=' '.join(theText) A little bit of explanation. My goal is to apply some logic to the bolded parts of the documents as those bolded sections that have the word KEY in them define different sections of the document. TheTitles is a list of the bolded elements that have the word 'KEY' included. Based on my particular needs I might want all of the text between any two items from theTitles, I can create tests and the necessary logic to select items from theTitles. theBoldItems is a list of the actual elements, for any i theTitles[i]==theBoldItems[i].text next I get theFullList which is all of the htm elements in the tree. Because LXML builds the tree in order I know that I want to capture all of the elements theBoldItems[i] and theBoldItems[i+1]. And the nice thing is that the way Python is built the test is that easy. I can now get the text for all of those things and while I still need to clean it up some I have successfully ripped out all of the text between any two items I might want.
Once I have identified the beginning and end parts of a section of an html document using lxml, how do I get everything between them
I am working with some html files. I am trying to figure out a way to consistently get to some text that exists in the documents. I know that the section I want begins with some bolded words and I know that the section ends with other bolded words. bolded_item=atree.cssselect('b') myKeys=[item for item in bolded_items if item.text if 'KEY' in item.text] so myKeys is a list whose members are elements from atree, specifically elements that have bolded text and have the word 'KEY' in the text. I want now to identify all of the parts of the tree between any 2 elements in myKeys I want to be able to manipulate them in various ways. I was playing around with getparent, getchildren getnext and all of the other methods that looked likely after running a dir(myKeys[0]) but I am not making progress. Any suggestions would be appreciated
[ "I'd suggest using SAX for this task.\nBasic docs are available at http://lxml.de/sax.html#producing-sax-events-from-an-elementtree-or-element\nYour handler should consume events w/out any action till it receives needed bolded item, and then it writes events into new buffer/tree/whatever till it receives terminatin...
[ 1, 0 ]
[]
[]
[ "html", "lxml", "parsing", "python" ]
stackoverflow_0003499242_html_lxml_parsing_python.txt
Q: Python Auto Fill with Mechanize Could someone help me or share some code to auto fill a login with mechanize (http://wwwsearch.sourceforge.net/mechanize/)? I want to make a python script to log me into my favorite sites when I run it. Thanks! A: This will help you to login to one site and download a page for example: import mechanize br=mechanize.Browser() br.open('http://www.yourfavoritesite.com') br.select_form(nr=0) #check yoursite forms to match the correct number br['Username']='Username' #use the proper input type=text name br['Password']='Password' #use the proper input type=password name br.submit() br.retrieve('https://www.yourfavoritesite.com/pagetoretrieve.html','yourfavoritepage.html') This script presumes that your login form is the first of the page and the input names are Username and Password. You could also select your form by name with: br.select_form(name="thisthing") Please, adapt this script to your favorite site login page. As well pointed by AlexMartelli, this script should be generalized to handle different sites with some config parameters. A: Each of your favorite sites probably has different forms (form number, and names of user and password fields) and one hopes you use different usernames and passwords on each (using the same user and password on many sites means that if one of the sites is cracked, your identity is now compromised "everywhere" -- quite a mess!). So, you can either hardcode all of these parameters, as in @systempuntoout's answer, or write a little configuration text file (for example in the format supported by ConfigParser) with all this info for each site, so that you can load the configuration when your script starts, and write a "log_me_in" function, just once, that takes the sitename as the parameter and looks up and uses the parameters that depend on it. If you have a lot of "favorite sites", so that loading all their info perceptibly slows your startup time, then you may even want to consider persisting that info more smartly (e.g. in a sqlite table) so it can be looked up rapidly for just one or a few sites given their names as the "key" to use.
Python Auto Fill with Mechanize
Could someone help me or share some code to auto fill a login with mechanize (http://wwwsearch.sourceforge.net/mechanize/)? I want to make a python script to log me into my favorite sites when I run it. Thanks!
[ "This will help you to login to one site and download a page for example:\nimport mechanize\nbr=mechanize.Browser()\nbr.open('http://www.yourfavoritesite.com')\nbr.select_form(nr=0) #check yoursite forms to match the correct number\nbr['Username']='Username' #use the proper input type=text name\nbr['Password']='Pas...
[ 3, 1 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0003516655_mechanize_python.txt
Q: Python, using two variables in getattr? I'm trying to do the following: import sys; sys.path.append('/var/www/python/includes') import functionname x = 'testarg' fn = "functionname" func = getattr(fn, fn) func (x) but am getting an error: "TypeError: getattr(): attribute name must be string" I have tried this before calling getattr but it still doesn't work: str(fn) I don't understand why this is happening, any advice is appreciated A: It sounds like you might be wanting locals() instead of getattr()... x = 'testarg' fn = "functionname" func = locals()[fn] func (x) You should be using getattr when you have an object and you want to get an attribute of that object, not a variable from the local namespace. A: The first argument of getattr is the object that has the attribute you are interested in. In this case you are trying to get an attribute of the function, I assume. So the first argument should be the function. Not a string containing the function name, but the function itself. If you want to use a string for that, you will need to use something like locals()[fn] to find the actual function object with that name. Second, you're passing the function name to getattr twice. The function doesn't have itself as an attribute. Did you mean the second argument to be x? I don't really get what you're trying to do here, I guess.
Python, using two variables in getattr?
I'm trying to do the following: import sys; sys.path.append('/var/www/python/includes') import functionname x = 'testarg' fn = "functionname" func = getattr(fn, fn) func (x) but am getting an error: "TypeError: getattr(): attribute name must be string" I have tried this before calling getattr but it still doesn't work: str(fn) I don't understand why this is happening, any advice is appreciated
[ "It sounds like you might be wanting locals() instead of getattr()... \nx = 'testarg'\nfn = \"functionname\"\nfunc = locals()[fn]\nfunc (x)\n\nYou should be using getattr when you have an object and you want to get an attribute of that object, not a variable from the local namespace.\n", "The first argument of ge...
[ 5, 0 ]
[]
[]
[ "function", "getattr", "python" ]
stackoverflow_0003516778_function_getattr_python.txt
Q: Extending python with C module So I have a C program to interface with an i2c device. I need to interface to that device from python. I'm just wondering if it's worth porting the program into a python module or if the amount of effort involved in porting won't outweigh just executing the program using subprocess. I know I'm sure it's different for every application, but I'd like to know if it's even worth my time to learn the python C extensions and port this program. Update: I have full access to the source of both the C as well as the python. But there is already substantial work done on the python side and I'd like to keep changes to that as minimal is possible, if that matters. And I'd also like to minimize the changes that have to be made to the C. It's doable, but I didn't write it and it involves a lot of by addressing that I'd rather not have to redo. A: There are many ways you can proceed -- the Python C API, which seems to be the one you're considering, but also SWIG, Cython, ctypes... as long as your existing C code can be made into a library (with functions callable "from the outside"), you have a wealth of options. Personally, I'd recommend Cython -- it's looking more and more as a broad subset of Python, extended just enough to allow effective compilation into machine code and direct calling of functions from C libraries. A: One of the first Python programs I wrote was a script that called functions from a C library, which sounds close to what you're doing. I used ctypes, and I was impressed as to how easy it was: I could access each library function from python by writing just a few lines of python (no C at all!). I'd tried the Python C API before, and it required a lot more boilerplate. I havent tried SWIG or Cython. A: Don't use the Python C API, there are much easier alternatives, most notably cython. cython is a Python-like language, which compiles into C code for the Python c library. Basically it's C with Python syntax and features (e.g. nice for loops, exceptions, etc.). cython is clearly the most recommendable way to write C extensions for python. You might also want to take a look at ctypes, a module to dynamically load C libraries and call functions from them. If your i2c-code is available as shared library, you can get away with no native binding at all, which eases development and distribution. A: I've had good luck using ctypes. Whatever you choose, though, you may not gain any time this time but the next time around your effort will be much faster than doing the whole thing in C. A: I would recommend ctypes using a shared library. It would be a good idea however to don't rely on complex types like structs in your C API. Using a pseudo-OOP approach is the simplest to map over to Python. E.g. foo_t* foo_new(void); int foo_bar(foo_t*, int); int foo_baz(foo_t*, int); void foo_free(foo_t*); Here, you could use ctypes native stuff. E.g. c_void_p for your object handle and c_int. c style strings are also supported with create_string_buffer (or something like that).
Extending python with C module
So I have a C program to interface with an i2c device. I need to interface to that device from python. I'm just wondering if it's worth porting the program into a python module or if the amount of effort involved in porting won't outweigh just executing the program using subprocess. I know I'm sure it's different for every application, but I'd like to know if it's even worth my time to learn the python C extensions and port this program. Update: I have full access to the source of both the C as well as the python. But there is already substantial work done on the python side and I'd like to keep changes to that as minimal is possible, if that matters. And I'd also like to minimize the changes that have to be made to the C. It's doable, but I didn't write it and it involves a lot of by addressing that I'd rather not have to redo.
[ "There are many ways you can proceed -- the Python C API, which seems to be the one you're considering, but also SWIG, Cython, ctypes... as long as your existing C code can be made into a library (with functions callable \"from the outside\"), you have a wealth of options. Personally, I'd recommend Cython -- it's ...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "c", "i2c", "python", "python_module" ]
stackoverflow_0003517011_c_i2c_python_python_module.txt
Q: Modify CRUD Form in web2py before sending to view I cannot seem to find a way to modify a form that has been created via: from gluon.tools import Crud crud = Crud(globals(), db) form = crud.create(db.table_name) Since I am using foreign keys in my table, the auto-generated form only allows an integer (which represents the foreign primary key), but what I want to be able to do is enter whatever data type the foreign data field requires (rather than just the identifier). Is there an easy way to tell the create() function to use the foreign table's data type rather than the primary table's data type (which is the auto-incrementing primary key)? A: You can use database validators to it. It will show a select box with the values from foreign table: (from http://web2py.com/book/default/chapter/07?search=requires#Database-Validators): IS_IN_DB Consider the following tables and requirement: db.define_table('person', Field('name', unique=True)) db.define_table('dog', Field('name'), Field('owner', db.person) db.dog.owner.requires = IS_IN_DB(db, 'person.id', '%(name)s', zero=T('choose one')) It is enforced at the level of dog INSERT/UPDATE/DELETE forms. It requires that a dog.owner be a valid id in the field person.id in the database db. Because of this validator, the dog.owner field is represented as a dropbox. The third argument of the validator is a string that describes the elements in the dropbox. In the example you want to see the person %(name)s instead of the person %(id)s. %(...)s is replaced by the value of the field in brackets for each record. The zero option works very much like for the IS_IN_SET validator. If you want the field validated, but you do not want a dropbox, you must put the validator in a list. db.dog.owner.requires = [IS_IN_DB(db, 'person.id', '%(name)s')] The first argument of the validator can be a database connection or a DAL Set, as in IS_NOT_IN_DB. Occasionally you want the drop-box (so you do not want to use the list syntax above) yet you want to use additional validators. For this purpose the IS_IN_DB validator takes an extra argument _and that can point to a list of other validators applied if the validated value passes the IS_IN_DB validation. For example to validate all dog owners in db that are not in a subset: subset=db(db.person.id>100) db.dog.owner.requires = IS_IN_DB(db, 'person.id', '%(name)s', _and=IS_NOT_IN_DB(subset,'person.id')) IS_IN_DB and Tagging The IS_IN_DB validator has an optional attribute multiple=False. If set to True multiple values can be stored in one field. This field should be of type list:reference as discussed in Chapter 6. An explicit example of tagging is discussed there. multiple references are handled automatically in create and update forms, but they are transparent to the DAL. We strongly suggest using the jQuery multiselect plugin to render multiple fields.
Modify CRUD Form in web2py before sending to view
I cannot seem to find a way to modify a form that has been created via: from gluon.tools import Crud crud = Crud(globals(), db) form = crud.create(db.table_name) Since I am using foreign keys in my table, the auto-generated form only allows an integer (which represents the foreign primary key), but what I want to be able to do is enter whatever data type the foreign data field requires (rather than just the identifier). Is there an easy way to tell the create() function to use the foreign table's data type rather than the primary table's data type (which is the auto-incrementing primary key)?
[ "You can use database validators to it.\nIt will show a select box with the values from foreign table:\n(from http://web2py.com/book/default/chapter/07?search=requires#Database-Validators):\nIS_IN_DB\nConsider the following tables and requirement:\ndb.define_table('person', Field('name', unique=True))\ndb.define_t...
[ 3 ]
[]
[]
[ "auto_generate", "crud", "foreign_keys", "python", "web2py" ]
stackoverflow_0003517072_auto_generate_crud_foreign_keys_python_web2py.txt
Q: Web2py ticket invalid links I started playing around with web2py the other day for a new project. I really like the structure and the whole concept which feels like a breath of fresh air after spending a few years with PHP frameworks. The only thing (currently) that is bothering me is the ticketing system. Each time I make a misstake a page with a link to a ticket is presented. I guess I could live with that if the link worked. It currently points to an admin page with http as protocol instead of https. I've done a bit of reading and the forced https for admin seems to be a security measure, but this makes debugging a pain. Whats the standard solution here? Alter the error page, allow http for admin och use logs for debugging? Best regards Fredrik A: I was in the same boat as you, I did not like the default mechanism. Luckily, customized exception handling with web2py is very straightforward. Take a look at routes.py in the root of your web2py directory. I've added the following to mine: routes_onerror = [('application_name/*','/application_name/error/index')] This routes any exceptions to my error handler controller (application_name/controllers/error.py) in which I defined my def index as: def index(): if request.vars.code == '400': return(dict(app=request.application, ticket=None, traceback="A 400 error was raised, this is controller/method path not found", code=None, layer=None, wasEmailed=False)) elif request.vars.code == '404': return(dict(app=request.application, ticket=None, traceback="A 404 error was raised, this is bad.", code=None, layer=None, wasEmailed=False)) else: fH = file('applications/%s/errors/%s' % (request.application,request.vars.ticket.split("/")[1])) e = cPickle.load(fH) fH.close() __sendEmail(request.application,e['layer'],e['traceback'],e['code']) return(dict(app=request.application, ticket=request.vars.ticket, traceback=e['traceback'], code=e['code'], layer=e['layer'], wasEmailed=True)) As you can see for non-400 and 404 errors, I'm emailing the traceback to myself and then invoking the corresponding views/error/index.html. In production, this view gives a generic "I'm sorry an error has occurred, developers have been emailed". On my development server, it displays the formatted traceback. A: Normally, I just use http://127.0.0.1/ (if you are local or over ssh) or edit/navigate using https://... So, you will logon the admin app the first time, but always will the show the tickets after.
Web2py ticket invalid links
I started playing around with web2py the other day for a new project. I really like the structure and the whole concept which feels like a breath of fresh air after spending a few years with PHP frameworks. The only thing (currently) that is bothering me is the ticketing system. Each time I make a misstake a page with a link to a ticket is presented. I guess I could live with that if the link worked. It currently points to an admin page with http as protocol instead of https. I've done a bit of reading and the forced https for admin seems to be a security measure, but this makes debugging a pain. Whats the standard solution here? Alter the error page, allow http for admin och use logs for debugging? Best regards Fredrik
[ "I was in the same boat as you, I did not like the default mechanism. Luckily, customized exception handling with web2py is very straightforward. Take a look at routes.py in the root of your web2py directory. I've added the following to mine:\nroutes_onerror = [('application_name/*','/application_name/error/inde...
[ 4, 0 ]
[]
[]
[ "admin", "https", "python", "web2py" ]
stackoverflow_0003505582_admin_https_python_web2py.txt
Q: Ctypes Offset Into A Buffer I have a string buffer: b = create_string_buffer(numb) where numb is a number of bytes. In my wrapper I need to splice up this buffer. When calling a function that expects a POINTER(c_char) I can do: myfunction(self, byref(b, offset)) but in a Structure: class mystruct(Structure): _fields_ = [("buf", POINTER(c_char))] I am unable to do this, getting an argument type exception. So my question is: how can I assign .buf to be an offset into b. Direct assignment works so .buf = b, however this is unsuitable. (Python does not hold up to well against ~32,000 such buffers being created every second, hence my desire to use a single spliced buffer.) A: ctypes.cast >>> import ctypes >>> b = ctypes.create_string_buffer(500) >>> b[:6] = 'foobar' >>> ctypes.cast(ctypes.byref(b, 4), ctypes.POINTER(ctypes.c_char)) <ctypes.LP_c_char object at 0x100756e60> >>> _.contents c_char('a')
Ctypes Offset Into A Buffer
I have a string buffer: b = create_string_buffer(numb) where numb is a number of bytes. In my wrapper I need to splice up this buffer. When calling a function that expects a POINTER(c_char) I can do: myfunction(self, byref(b, offset)) but in a Structure: class mystruct(Structure): _fields_ = [("buf", POINTER(c_char))] I am unable to do this, getting an argument type exception. So my question is: how can I assign .buf to be an offset into b. Direct assignment works so .buf = b, however this is unsuitable. (Python does not hold up to well against ~32,000 such buffers being created every second, hence my desire to use a single spliced buffer.)
[ "ctypes.cast\n>>> import ctypes\n>>> b = ctypes.create_string_buffer(500)\n>>> b[:6] = 'foobar'\n>>> ctypes.cast(ctypes.byref(b, 4), ctypes.POINTER(ctypes.c_char))\n<ctypes.LP_c_char object at 0x100756e60>\n>>> _.contents\nc_char('a')\n\n" ]
[ 3 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003517159_ctypes_python.txt
Q: Twisted: deferred that fires repeatedly? Deferreds are a great way to do asynchronous processing in Twisted. However, they, like the name implies, are for deferred computations, which only run and terminate once, firing the callbacks once. What if I have a repeated computation, like a button being clicked? Is there any Deferred-like object that can fire repeatedly, calling all callbacks attached to it whenever it is fired? A: I've set this up for now. For my limited use case it does what I want. class RepeatedDeferred: def __init__(self): self.callbacks = [] self.df = defer.Deferred() def addCallback(self, callback): self.callbacks.append(callback) self.df.addCallback(callback) def callback(self, res): self.df.callback(res) self.df = defer.Deferred() for c in self.callbacks: self.df.addCallback(c) Someone let me know if this is terrible. A: What you might be looking for is defer.inlineCallbacks which allows you to use a generator to create a sequential chain of Deferreds. Essentially you could just create a generator that never ends (or ends conditionally) and keep generating Deferreds from that. There is a great writeup on using inlineCallbacks at krondo.com.
Twisted: deferred that fires repeatedly?
Deferreds are a great way to do asynchronous processing in Twisted. However, they, like the name implies, are for deferred computations, which only run and terminate once, firing the callbacks once. What if I have a repeated computation, like a button being clicked? Is there any Deferred-like object that can fire repeatedly, calling all callbacks attached to it whenever it is fired?
[ "I've set this up for now. For my limited use case it does what I want.\nclass RepeatedDeferred:\n def __init__(self):\n self.callbacks = []\n\n self.df = defer.Deferred()\n\n def addCallback(self, callback):\n self.callbacks.append(callback)\n\n self.df.addCallback(callback)\n\n ...
[ 3, 1 ]
[]
[]
[ "callback", "multithreading", "python", "twisted" ]
stackoverflow_0003514529_callback_multithreading_python_twisted.txt
Q: Python raw literal string str = r'c:\path\to\folder\' # my comment IDE: Eclipse Python2.6 When the last character in the string is a backslash, it seems like it will escape the last single quote and treat my comment as part of the string. But the raw string is supposed to ignore all escape characters, right? What could be wrong? Thanks. A: Raw string literals don't treat backslashes as initiating escape sequences except when the immediately-following character is the quote-character that is delimiting the literal, in which case the backslash does escape it. The design motivation is that raw string literals really exist only for the convenience of entering regular expression patterns – that is all, no other design objective exists for such literals. And RE patterns never need to end with a backslash, but they might need to include all kinds of quote characters, whence the rule. Many people do try to use raw string literals to enable them to enter Windows paths the way they're used to (with backslashes) – but as you've noticed this use breaks down when you do need a path to end with a backslash. Usually, the simplest solution is to use forward slashes, which Microsoft's C runtime and all version of Python support as totally equivalent in paths: s = 'c:/path/to/folder/' (side note: don't shadow builtin names, like str, with your own identifiers – it's a horrible practice, without any upside, and unless you get into the habit of avoiding that horrible practice one day you'll find yourseld with a nasty-to-debug problem, when some part of your code tramples over a builtin name and another part needs to use the builtin name in its real meaning). A: It's IMHO an inconsistency in Python, but it's described in the documentation. Go to the second last paragraph: http://docs.python.org/reference/lexical_analysis.html#string-literals r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes)
Python raw literal string
str = r'c:\path\to\folder\' # my comment IDE: Eclipse Python2.6 When the last character in the string is a backslash, it seems like it will escape the last single quote and treat my comment as part of the string. But the raw string is supposed to ignore all escape characters, right? What could be wrong? Thanks.
[ "Raw string literals don't treat backslashes as initiating escape sequences except when the immediately-following character is the quote-character that is delimiting the literal, in which case the backslash does escape it.\nThe design motivation is that raw string literals really exist only for the convenience of e...
[ 36, 9 ]
[]
[]
[ "python", "rawstring", "string" ]
stackoverflow_0003517802_python_rawstring_string.txt
Q: Python list function argument names Is there a way to get the parameter names a function takes? def foo(bar, buz): pass magical_way(foo) == ["bar", "buz"] A: Use the inspect module from Python's standard library (the cleanest, most solid way to perform introspection). Specifically, inspect.getargspec(f) returns the names and default values of f's arguments -- if you only want the names and don't care about special forms *a, **k, import inspect def magical_way(f): return inspect.getargspec(f)[0] completely meets your expressed requirements. A: >>> import inspect >>> def foo(bar, buz): ... pass ... >>> inspect.getargspec(foo) ArgSpec(args=['bar', 'buz'], varargs=None, keywords=None, defaults=None) >>> def magical_way(func): ... return inspect.getargspec(func).args ... >>> magical_way(foo) ['bar', 'buz']
Python list function argument names
Is there a way to get the parameter names a function takes? def foo(bar, buz): pass magical_way(foo) == ["bar", "buz"]
[ "Use the inspect module from Python's standard library (the cleanest, most solid way to perform introspection).\nSpecifically, inspect.getargspec(f) returns the names and default values of f's arguments -- if you only want the names and don't care about special forms *a, **k,\nimport inspect\n\ndef magical_way(f):\...
[ 72, 17 ]
[]
[]
[ "arguments", "function", "python" ]
stackoverflow_0003517892_arguments_function_python.txt
Q: Which format should I save my python script output? I have an executable (converted to exe from python using py2exe) that outputs lists of numbers that could be from 0-50K lines long or a little bit more. While developing, I just saved them to a TXT file using simple f.write. The person wants to print this output on paper! (don't ask why lol) So, I'm wondering if I can output it to something like HTML? XML? Something that could display tables of 50K lines and maybe 3 columns and that would also run in any PC without additional programs? Suggestions? EDIT: Regarding CSV: In most situations the best way in my opinion would be to make a CSV. I'm not opposing it in anyway, rather I think others might find Lott's answer useful for their cases. Sorry I didn't explain it that well in my question as far as my constraints go. My constraints are: the user doesn't have an office suite, no python installed. Just think of a PC that has the bare minimum after a clean windows xp/vista installation, maybe Internet Explorer 7 or 8. This PC has to be able to open my output file and allow for reasonable viewing, searching, and printing. A: CSV. http://docs.python.org/library/csv.html http://en.wikipedia.org/wiki/Comma-separated_values They can load a spreadsheet and print anything they want. A: If you can't install anything on the computer, the you might be best off outputting an HTML file with the data in a <table> that the user could view/search/print in IE. A: You could use LaTeX to produce a PDF, maybe? But why exactly isn't a text file good enough? A: You can produce a PDF using Reportlab. After all if you really want full control of the printed output, there's nothing that beats PDF. A: Does 50k lines make too large a file? If not, just continue writing text files. Otherwise an easy solution would be to continue spitting out text files and compress them, e.g. with zip. You could use the zipfile library in Python. Most computers have no trouble reading zip files.
Which format should I save my python script output?
I have an executable (converted to exe from python using py2exe) that outputs lists of numbers that could be from 0-50K lines long or a little bit more. While developing, I just saved them to a TXT file using simple f.write. The person wants to print this output on paper! (don't ask why lol) So, I'm wondering if I can output it to something like HTML? XML? Something that could display tables of 50K lines and maybe 3 columns and that would also run in any PC without additional programs? Suggestions? EDIT: Regarding CSV: In most situations the best way in my opinion would be to make a CSV. I'm not opposing it in anyway, rather I think others might find Lott's answer useful for their cases. Sorry I didn't explain it that well in my question as far as my constraints go. My constraints are: the user doesn't have an office suite, no python installed. Just think of a PC that has the bare minimum after a clean windows xp/vista installation, maybe Internet Explorer 7 or 8. This PC has to be able to open my output file and allow for reasonable viewing, searching, and printing.
[ "CSV.\nhttp://docs.python.org/library/csv.html\nhttp://en.wikipedia.org/wiki/Comma-separated_values\nThey can load a spreadsheet and print anything they want.\n", "If you can't install anything on the computer, the you might be best off outputting an HTML file with the data in a <table> that the user could view/s...
[ 6, 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003515043_python.txt
Q: python function that modifies parameters def add(a,b): for i in range(len(a)): a[i] = a[i] + b def main(): amounts = [100,200] rate = 1 add(amounts,rate) print amounts main() The function add does not have a return. I read that changes are available to only mutable objects like list. But why did the person omits the return? Either with or without return is fine. Why? This is so different from C++. Thanks A: But why did the person omits the return? Either with or without return is fine. Why? This is so different from C++. Not at all - it's identical to C++ to all intent and purposes! Just make, in the C++ version, a void add and pass its argument a, say a std::vector<int>, by reference -- to all intents and purposes, this is what this Python add is doing, seen in C++ terms. In Python terms, when a function "falls off the end" that's exactly the same as if it executed return None at that point. It's better style in such cases (when a function always ends by "falling off the end") to avoid the redundant return None statement (don't waste pixels and screen space in redundant ornamentation of this kind). A: add() mutates a instead of rebinding it, so the change shows up in the original object. A: Everything is passed by reference in python, but integers, strings etc. are immutable so when you change it you create a new one which is bound to the local variable so the variable passed to the function isn't changed. Lists and dicts are, however, mutable - so if you change them no new object is created and due to this the change also affects the variable in the caller's scope. A: Consider the following C++ program: #include <vector> #include <iostream> void add_val(std::vector<int> addTo, int addThis) { for(std::vector<int>::iterator it = addTo.begin(); it!=addTo.end(); ++it) { *it += addThis; } } void add_ref(std::vector<int>& addTo, int addThis) { for(std::vector<int>::iterator it = addTo.begin(); it!=addTo.end(); ++it) { *it += addThis; } } int main() { std::vector<int> myVector; myVector.push_back(1); myVector.push_back(2); myVector.push_back(3); add_val(myVector, 3); std::cout<<"After add_val"<<std::endl; for (std::vector<int>::iterator it = myVector.begin(); it!=myVector.end(); ++it) { std::cout<<*it<<" "; } std::cout<<std::endl; add_ref(myVector, 3); std::cout<<"After add_ref"<<std::endl; for (std::vector<int>::iterator it = myVector.begin(); it!=myVector.end(); ++it) { std::cout<<*it<<" "; } std::cout<<std::endl; return 0; } The program outputs: After add_val 1 2 3 After add_ref 4 5 6 Passing the vector to add_val() results in the original vector remaining unchanged, since it is passed by value. Passing the vector to add_ref() however, causes the values inside the original vector to change, since it's passed by reference. In Python everything is passed by reference. However, a lot of the builtin types (str, tuple, int, float, etc.) are immutable. This means that any operation you perform on these types results in a new variable being bound in the current scope with the new value. For mutable types (list, dict, etc.), you end up with exactly the same result as passing a parameter by reference in C++.
python function that modifies parameters
def add(a,b): for i in range(len(a)): a[i] = a[i] + b def main(): amounts = [100,200] rate = 1 add(amounts,rate) print amounts main() The function add does not have a return. I read that changes are available to only mutable objects like list. But why did the person omits the return? Either with or without return is fine. Why? This is so different from C++. Thanks
[ "\nBut why did the person omits the\n return? Either with or without return\n is fine. Why? This is so different\n from C++.\n\nNot at all - it's identical to C++ to all intent and purposes! Just make, in the C++ version, a void add and pass its argument a, say a std::vector<int>, by reference -- to all intents...
[ 7, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003517860_python.txt
Q: drop into an interactive session to examine a failed unit test I'd like to be able to enter an interactive session, preferably with IPython, if a unit test fails. Is there an easy way to do this? edit: by "interactive session" I mean a full Python REPL rather than a pdb shell. edit edit: As a further explanation: I'd like to be able to start an interactive session that has access to the context in which the test failure occurred. So for example, the test's self variable would be available. A: In IPython, use %pdb before running the test In [9]: %pdb Automatic pdb calling has been turned ON A: Nosetests runner provides --pdb option that will put you into the debugger session on errors or failures. http://nose.readthedocs.org/en/latest/usage.html
drop into an interactive session to examine a failed unit test
I'd like to be able to enter an interactive session, preferably with IPython, if a unit test fails. Is there an easy way to do this? edit: by "interactive session" I mean a full Python REPL rather than a pdb shell. edit edit: As a further explanation: I'd like to be able to start an interactive session that has access to the context in which the test failure occurred. So for example, the test's self variable would be available.
[ "In IPython, use %pdb before running the test\nIn [9]: %pdb\nAutomatic pdb calling has been turned ON\n\n", "Nosetests runner provides --pdb option that will put you into the debugger session on errors or failures.\nhttp://nose.readthedocs.org/en/latest/usage.html\n" ]
[ 2, 1 ]
[ "Are you really sure you want to do this? Your unit tests should do one thing, should be well-named, and should clearly print what failed. If you do all of that, the failure message will pinpoint what went wrong; no need to go look at it interactively. In fact, one of the big advantages of TDD is that it helps y...
[ -2 ]
[ "interactive", "ipython", "python", "unit_testing" ]
stackoverflow_0003517410_interactive_ipython_python_unit_testing.txt
Q: When parsing html why do I need item.text sometimes and item.text_content() others Still learning lxml. I discovered that sometimes I cannot get to the text of an item from a tree using item.text. If I use item.text_content() I am good to go. I am not sure I see why yet. Any hints would be appreciated Okay I am not sure exactly how to provide an example without making you handle a file: here is some code I wrote to try to figure out why I was not getting some text I expected: theTree=html.fromstring(open(notmatched[0]).read()) text=[] text_content=[] notText=[] hasText=[] for each in theTree.iter(): if each.text: text.append(each.text) hasText.append(each) # list of elements that has text each.text is true text_content.append(each.text_content()) #the text for all elements if each not in hasText: notText.append(each) So after I run this I look at >>> len(notText) 3612 >>> notText[40] <Element b at 26ab650> >>> notText[40].text_content() '(I.R.S. Employer' >>> notText[40].text A: Accordng to the docs the text_content method: Returns the text content of the element, including the text content of its children, with no markup. So for example, import lxml.html as lh data = """<a><b><c>blah</c></b></a>""" doc = lh.fromstring(data) print(doc) # <Element a at b76eb83c> doc is the Element a. The a tag has no text immediately following it (between the <a> and the <b>. So doc.text is None: print(doc.text) # None but there is text after the c tag, so doc.text_content() is not None: print(doc.text_content()) # blah PS. There is a clear description of the meaning of the text attribute here. Although it is part of the docs for lxml.etree.Element, I think the meaning of the text and tail attributes applies equally well to lxml.html.Element objects. A: You maybe confusing different and incompatible interfaces that lxml implements -- the lxml.etree items have a .text attribute, while (for example) those from lxml.html implement the text_content method (and those from BeautifulSoup, also included in lxml, have a .string attribute... sometimes [[only nodes with a single child which is a string...]]). Yeah, it is inherently confusing that lxml chooses both to implement its own interfaces and emulate or include other libraries, but it can be convenient...;-).
When parsing html why do I need item.text sometimes and item.text_content() others
Still learning lxml. I discovered that sometimes I cannot get to the text of an item from a tree using item.text. If I use item.text_content() I am good to go. I am not sure I see why yet. Any hints would be appreciated Okay I am not sure exactly how to provide an example without making you handle a file: here is some code I wrote to try to figure out why I was not getting some text I expected: theTree=html.fromstring(open(notmatched[0]).read()) text=[] text_content=[] notText=[] hasText=[] for each in theTree.iter(): if each.text: text.append(each.text) hasText.append(each) # list of elements that has text each.text is true text_content.append(each.text_content()) #the text for all elements if each not in hasText: notText.append(each) So after I run this I look at >>> len(notText) 3612 >>> notText[40] <Element b at 26ab650> >>> notText[40].text_content() '(I.R.S. Employer' >>> notText[40].text
[ "Accordng to the docs the text_content method:\n\nReturns the text content of the element, including the text content of\n its children, with no markup.\n\nSo for example,\nimport lxml.html as lh\ndata = \"\"\"<a><b><c>blah</c></b></a>\"\"\"\ndoc = lh.fromstring(data)\nprint(doc)\n# <Element a at b76eb83c>\n\ndoc ...
[ 12, 4 ]
[]
[]
[ "html", "lxml", "parsing", "python" ]
stackoverflow_0003517461_html_lxml_parsing_python.txt
Q: how to implement thin client app with pyqt Here is what I would like to do, and I want to know how some people with experience in this field do this: With three POST requests I get from the http server: widgets and layout and then app logic (minimal) data Or maybe it's better to combine the first two or all three. I'm thinking of using pyqt. I think I can load .ui files. I can parse json data. I just think it would be rather dangerous to pass code over a network to be executed on the client. If someone can hijack the connection, or can change the apps setting to access a bogus server, that is nasty. I want to do it this way because it keeps all the clients up-to-date. It's sort of like a webapp but simpler because of Qt. Essentially the "thin" app is just a minimal compiled python file that loads data from a server. How can I do this without introducing security issues on the client? Is https good enough? Is there a way to get pyqt to run in a sandbox of sorts? PS. I'm not stuck on Qt or python. I do like the concept though. I don't really want to use Java - server or client side. A: Your desire to send "app logic" from the server to the client without sending "code" is inherently self-contradictory, though you may not realize that yet -- even if the "logic" you're sending is in some simplified ad-hoc "language" (which you don't even think of as a language;-), to all intents and purposes your Python code will be interpreting that language and thereby execute that code. You may "sandbox" things to some extent, but in the end, that's what you're doing. To avoid hijackings and other tricks, instead, use HTTPS and validate the server's cert in your client: that will protect you from all the problems you're worrying about (if somebody can edit the app enough to defeat the HTTPS cert validation, they can edit it enough to make it run whatever code they want, without any need to send that code from a server;-). Once you're using https, having the server send Python modules (in source form if you need to support multiple Python versions on the clients, else bytecode is fine) and the client thereby save them to disk and import / reload them, will be just fine. You'll basically be doing a variant of the classic "plugins architecture" where the "plugins" are in fact being sent from the server (instead of being found on disk in a given location). A: Use a web-browser it is a well documented system that does everything you want. It is also relatively fast to create simple graphical applications in a browser. Examples for my reasoning: The Sage math environment has built their graphical client as an application that runs in a browser, together with a local web-server. There is the Pyjamas project that compiles Python to Javascript. This is IMHO worth a try. Edit: You could try PyPy's sandbox interpreter, as a secure Python interpreter for the code that was transferred over a network. An then there is the most simple solution: Simply send Python modules over the network, but sign and/or encrypt them. This is the way all Linux distributions work. You store a cryptographic token on the local computer. The server signs/encrypts the code before it sends it, with a matching token. GPG should be able to do it.
how to implement thin client app with pyqt
Here is what I would like to do, and I want to know how some people with experience in this field do this: With three POST requests I get from the http server: widgets and layout and then app logic (minimal) data Or maybe it's better to combine the first two or all three. I'm thinking of using pyqt. I think I can load .ui files. I can parse json data. I just think it would be rather dangerous to pass code over a network to be executed on the client. If someone can hijack the connection, or can change the apps setting to access a bogus server, that is nasty. I want to do it this way because it keeps all the clients up-to-date. It's sort of like a webapp but simpler because of Qt. Essentially the "thin" app is just a minimal compiled python file that loads data from a server. How can I do this without introducing security issues on the client? Is https good enough? Is there a way to get pyqt to run in a sandbox of sorts? PS. I'm not stuck on Qt or python. I do like the concept though. I don't really want to use Java - server or client side.
[ "Your desire to send \"app logic\" from the server to the client without sending \"code\" is inherently self-contradictory, though you may not realize that yet -- even if the \"logic\" you're sending is in some simplified ad-hoc \"language\" (which you don't even think of as a language;-), to all intents and purpos...
[ 1, 1 ]
[]
[]
[ "networking", "pyqt", "python", "qt", "thin" ]
stackoverflow_0003517841_networking_pyqt_python_qt_thin.txt
Q: How do you override a the save method in Django and raise proper errors that will be caught by the Admin interface? I'm a little stumped here, I can't find what I'm looking for in the Django docs... What I want, is to be able to override the Save method of an Model. I want it to check for a certain set of conditions - if these conditions are met, it will create the object just fine, but if the conditions are not met, I want to raise an error. The main thing is that I am using the Admin interface for most of these, so I this isn't an error that I will catch myself - this is an error that I need the admin interface to catch and display to the user. How might I go about doing this chaps? Is there documentation I am missing out on reading? Oh, also to note, I am using Django 1.1, and thus, cannot override the clean / full_clean methods introduced by Django 1.2. Thanks! Shawn A: I want ... to check for a certain set of conditions - if these conditions are met, it will create the object just fine, but if the conditions are not met, I want to raise an error. This is what a ModelForm is for. http://docs.djangoproject.com/en/dev/topics/forms/modelforms/ A: I'm not 100% sure, but I think you should be able to raise either a ValueError or a django.forms.ValidationError in your save() method in your model def save(self): if yourvalidation: super(Model, self).save() #call super to actually do save else: raise #either ValueError or ValidationException Again, i'm not sure if this will work in 1.1... but this is what I would try.
How do you override a the save method in Django and raise proper errors that will be caught by the Admin interface?
I'm a little stumped here, I can't find what I'm looking for in the Django docs... What I want, is to be able to override the Save method of an Model. I want it to check for a certain set of conditions - if these conditions are met, it will create the object just fine, but if the conditions are not met, I want to raise an error. The main thing is that I am using the Admin interface for most of these, so I this isn't an error that I will catch myself - this is an error that I need the admin interface to catch and display to the user. How might I go about doing this chaps? Is there documentation I am missing out on reading? Oh, also to note, I am using Django 1.1, and thus, cannot override the clean / full_clean methods introduced by Django 1.2. Thanks! Shawn
[ "\nI want ... to check for a certain set of conditions - if these conditions are met, it will create the object just fine, but if the conditions are not met, I want to raise an error. \n\nThis is what a ModelForm is for.\nhttp://docs.djangoproject.com/en/dev/topics/forms/modelforms/\n", "I'm not 100% sure, but I ...
[ 1, 1 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0003516227_django_django_admin_django_models_python.txt
Q: grouping strings by substring in mysql/python or mysql/.net the data will be stored in a mysql database like this: 5911 CD $4.99 Eben, Landscapes of Patmos {w.Martin Lenniger, percussion}; 2 Choral Phantasies; Laudes. (All w.Sieglinde Ahrens, organ) 5913 CD $5.99 Turina, Sevilliana; Rafaga; Hommage a Tarrega; Sonata. Rodrigo, 3 Piezas Espanolas; En Los Trigales; Sarabande Lointaine. (Eric Hill, guitar^) 145460 CD $13.98 Wagner, The Flying Dutchman. (Hans Hotter, Astrid Varnay, Set Svanholm et al. Cond. Reiner. Rec.1950. PLEASE NOTE: Limited-pressing CDRs) 145461 CD $13.98 Montemezzi, L'Amore dei Tre Re. (Virgilio Lazzari, Dorothy Kirsten, Charles Kullman, Robert Weede, Leslie Chabay et al. Cond. Giuseppe Antonicelli. Rec. 1949. PLEASE NOTE: Limited-pressing CDRs) 145462 CD $13.98 Ponchielli, La Gioconda. (Zinka Milanov, Giacomo Vaghi, Leonard Warren, Rise Stevens, Richard Tucker, Margaret Harshaw et al. Cond. Emil Cooper. Rec. 1946. PLEASE NOTE: Limited-pressing CDRs) 145465 CD $5.99 ' Yankele: Yiddish Songs'. (16 titles incl. Az der Rebe, Rozhinkes mit Mandlekh, Shabes, Yankele, Belz, Di Grine Kuzine. Moshe Leiser, voice and guitar. Ami Flammer, violin. Gerard Barreaux, accordion. Rec. 'live', Lyon Opera. Total time: 78') 145467 CD $4.99 Brahms, Piano Trios 2 & 3. (Trio Bamberg: Evgeny Schuk, violin; Stephan Gerlinghaus, cello. Robert Benz, piano. Rec. Nuremberg, 4/7/2000. Total time: 51'45') 145468 CD $4.99 Gaubert, Piece Romantique; Trois Aquarelles. Debussy, Premier Trio in G. Francaix, Trio. (Trio Cantabile: Hans-Jorg Wegner, flute. Guido Larisch, cello. Christiane Kroeker, piano. Rec. Hannover, 3/2001. Total time: 62'35') 145469 CD $4.99 Gattermeyer, Heinrich [b.1923]: Ophelias Schattentheater [text by Michael Ende]. Matthias Drude [b.1960], Jorinde und Joringel. Christoph J. Keller [b.1959], Die Kristallkugel [both texts by Brother Grimm]. (Helmut Thiele, narrator w.Bernd-Christian Schulze, piano. Total time: 68'08') 145470 CD $2.99 Morrill, Dexter [b.1938]: Dance Bagatelles for Viola & Piano; Three Lyric Pieces for Violin and Piano [Laura Klugherz, viola & violin. Jill Timmons, piano]; Fantasy for Solo Cello [James Kirkwood, cello]; String Quartet #2 [Tremont String Quartet]. (Total time: 51'03') 145471 CD $2.99 Werntz, Julia: String Trio with Homage to Chopin [Curtis Macomber, violin. Lois Martin, viola. Ted Mook, cello]; 'To You Strangers'- Five Poems of Dylan Thomas for Mezzo-Soprano Solo [Christina Ascher]; Piano Piece [John McDonald]. John Mallia, Lock [Stephanie Kay, clarinet]; Poor Denizens of Hell [chamber ensemble/ Daniel Hosken]; Plexus 2. (Aura Group for New Music) 145472 CD $2.99 Morrill, Dexter [b.1938]- 'Music for Trumpets': 'Ponzo' for Two Trumpets; 'Nine Pieces' for Solo Trumpet; 'TARR' for Four Trumpets & Computer; 'Studies' for Trumpet & Computer; 'Trumpet Concerto' for Trumpet & Piano. (Mark Ponzo, trumpet with Barbara Butler [trumpet] & William Koehler, piano. Total time: 52'02') 145473 CD $2.99 Kallstrom, Michael [b.1956]: 'Stories'. (A chamber opera for solo performer with puppets and electronic tape based on Old Testament stories) 145474 CD $2.99 Carosio, Vailati, Lechi, Ponchielli, D'Alessandro, Sterzati, Riva, Pucci, Casazza, Denti, Gnaga, Anelli, Feroldi: 'The Mandolins of Stradivari'. (16 pieces for mandolin ensemble et al. Ugo Orlandi, mandolin. Alessandro Bono, guitar. Maura Mazzonetto, piano. Giampaolo Baldin, baritone. Quartetto romantico a plettro 'Umbert Sterzati'. Orchestra di Mandolini e Chitarre 'Citta di Brescia'/ Mandonico. Total time: 77'19') 145475 CD $3.99 Rachmaninov, Symphony #3; Symphonic Dances. (St. Petersburg Philharmonic/ Jansons. Total time: 72'16') i need each title to be grouped with 4 other titles that have words in common. for example if i would it to group 4 cds that have both the word BEETHOVEN and MOZART in the string. HOWEVER, i do not want to specify which words it should group by. i would like this to be done in sort of an artificially intelligent way here's what i think the algorithm should look like: do a frequency distribution on all words throw out any words that are frequently used in the english (like if, or, the, of where can i get a list of these)?? start to group by the words that occur least often does anyone know any intelligent way of grouping this? A: Re (2), what you want are called "stopwords" -- e.g., in NLTK (which is Python, but I imagine there will be C# equivalents), per chapter 2 in its excellent online book, >>> from nltk.corpus import stopwords >>> stopwords.words('english') ['a', "a's", 'able', 'about', 'above', 'according', 'accordingly', 'across', 'actually', 'after', 'afterwards', 'again', 'against', "ain't", 'all', 'allow', 'allows', 'almost', 'alone', 'along', 'already', 'also', 'although', 'always', ...] The book I quoted can also help with your point 1, but point 3 is really a different field -- clustering. You want a very peculiar kind of clustering (specified and identical cluster size), so existing algorithms may not be suitable for you, but it's not too hard to devise some based on what you mention. Basically you want each word to be worth a "score" that's higher for words that are rarer in English (and NLTK, or any equivalently powerful natural language processing toolkit in C#, can of course help you with that) -- minus the logarithm of the word's frequency for example could be a start. You only need to score non-stop words that occur in at least five documents, according to the specs you mentioned, so the number of meaningful words should be pretty low, and exhaustive search might even be feasible. In fact the biggest issue might be another -- what if there's a group of fewer than 5 docs that, collectively, don't have any non-stop words in common with any of the others? The possibility of such occurrences shows you'll have to relax your specs in some respect (since I don't know anything about your app I can't give specific suggestions, of course, but it might be anything from allowing groups with a number of docs different from 5, to relaxing the criteria for grouping, etc). Or, would you rather just diagnose that some situation exists where actually meeting your tight constraints is impossible, and provide an error message instead of any results if it occurs?
grouping strings by substring in mysql/python or mysql/.net
the data will be stored in a mysql database like this: 5911 CD $4.99 Eben, Landscapes of Patmos {w.Martin Lenniger, percussion}; 2 Choral Phantasies; Laudes. (All w.Sieglinde Ahrens, organ) 5913 CD $5.99 Turina, Sevilliana; Rafaga; Hommage a Tarrega; Sonata. Rodrigo, 3 Piezas Espanolas; En Los Trigales; Sarabande Lointaine. (Eric Hill, guitar^) 145460 CD $13.98 Wagner, The Flying Dutchman. (Hans Hotter, Astrid Varnay, Set Svanholm et al. Cond. Reiner. Rec.1950. PLEASE NOTE: Limited-pressing CDRs) 145461 CD $13.98 Montemezzi, L'Amore dei Tre Re. (Virgilio Lazzari, Dorothy Kirsten, Charles Kullman, Robert Weede, Leslie Chabay et al. Cond. Giuseppe Antonicelli. Rec. 1949. PLEASE NOTE: Limited-pressing CDRs) 145462 CD $13.98 Ponchielli, La Gioconda. (Zinka Milanov, Giacomo Vaghi, Leonard Warren, Rise Stevens, Richard Tucker, Margaret Harshaw et al. Cond. Emil Cooper. Rec. 1946. PLEASE NOTE: Limited-pressing CDRs) 145465 CD $5.99 ' Yankele: Yiddish Songs'. (16 titles incl. Az der Rebe, Rozhinkes mit Mandlekh, Shabes, Yankele, Belz, Di Grine Kuzine. Moshe Leiser, voice and guitar. Ami Flammer, violin. Gerard Barreaux, accordion. Rec. 'live', Lyon Opera. Total time: 78') 145467 CD $4.99 Brahms, Piano Trios 2 & 3. (Trio Bamberg: Evgeny Schuk, violin; Stephan Gerlinghaus, cello. Robert Benz, piano. Rec. Nuremberg, 4/7/2000. Total time: 51'45') 145468 CD $4.99 Gaubert, Piece Romantique; Trois Aquarelles. Debussy, Premier Trio in G. Francaix, Trio. (Trio Cantabile: Hans-Jorg Wegner, flute. Guido Larisch, cello. Christiane Kroeker, piano. Rec. Hannover, 3/2001. Total time: 62'35') 145469 CD $4.99 Gattermeyer, Heinrich [b.1923]: Ophelias Schattentheater [text by Michael Ende]. Matthias Drude [b.1960], Jorinde und Joringel. Christoph J. Keller [b.1959], Die Kristallkugel [both texts by Brother Grimm]. (Helmut Thiele, narrator w.Bernd-Christian Schulze, piano. Total time: 68'08') 145470 CD $2.99 Morrill, Dexter [b.1938]: Dance Bagatelles for Viola & Piano; Three Lyric Pieces for Violin and Piano [Laura Klugherz, viola & violin. Jill Timmons, piano]; Fantasy for Solo Cello [James Kirkwood, cello]; String Quartet #2 [Tremont String Quartet]. (Total time: 51'03') 145471 CD $2.99 Werntz, Julia: String Trio with Homage to Chopin [Curtis Macomber, violin. Lois Martin, viola. Ted Mook, cello]; 'To You Strangers'- Five Poems of Dylan Thomas for Mezzo-Soprano Solo [Christina Ascher]; Piano Piece [John McDonald]. John Mallia, Lock [Stephanie Kay, clarinet]; Poor Denizens of Hell [chamber ensemble/ Daniel Hosken]; Plexus 2. (Aura Group for New Music) 145472 CD $2.99 Morrill, Dexter [b.1938]- 'Music for Trumpets': 'Ponzo' for Two Trumpets; 'Nine Pieces' for Solo Trumpet; 'TARR' for Four Trumpets & Computer; 'Studies' for Trumpet & Computer; 'Trumpet Concerto' for Trumpet & Piano. (Mark Ponzo, trumpet with Barbara Butler [trumpet] & William Koehler, piano. Total time: 52'02') 145473 CD $2.99 Kallstrom, Michael [b.1956]: 'Stories'. (A chamber opera for solo performer with puppets and electronic tape based on Old Testament stories) 145474 CD $2.99 Carosio, Vailati, Lechi, Ponchielli, D'Alessandro, Sterzati, Riva, Pucci, Casazza, Denti, Gnaga, Anelli, Feroldi: 'The Mandolins of Stradivari'. (16 pieces for mandolin ensemble et al. Ugo Orlandi, mandolin. Alessandro Bono, guitar. Maura Mazzonetto, piano. Giampaolo Baldin, baritone. Quartetto romantico a plettro 'Umbert Sterzati'. Orchestra di Mandolini e Chitarre 'Citta di Brescia'/ Mandonico. Total time: 77'19') 145475 CD $3.99 Rachmaninov, Symphony #3; Symphonic Dances. (St. Petersburg Philharmonic/ Jansons. Total time: 72'16') i need each title to be grouped with 4 other titles that have words in common. for example if i would it to group 4 cds that have both the word BEETHOVEN and MOZART in the string. HOWEVER, i do not want to specify which words it should group by. i would like this to be done in sort of an artificially intelligent way here's what i think the algorithm should look like: do a frequency distribution on all words throw out any words that are frequently used in the english (like if, or, the, of where can i get a list of these)?? start to group by the words that occur least often does anyone know any intelligent way of grouping this?
[ "Re (2), what you want are called \"stopwords\" -- e.g., in NLTK (which is Python, but I imagine there will be C# equivalents), per chapter 2 in its excellent online book, \n>>> from nltk.corpus import stopwords\n>>> stopwords.words('english')\n['a', \"a's\", 'able', 'about', 'above', 'according', 'accordingly', 'a...
[ 2 ]
[]
[]
[ "c#", "mysql", "python" ]
stackoverflow_0003518375_c#_mysql_python.txt
Q: Linking a static library into Boost Python (shared library) - Import Error I am building a Boost Python module (.so shared library file) which depends on another external library (STXXL) While I can build and import the example Boost Python modules, I run into problems when STXXL is thrown into the mix. Specifically when running import fast_parts in python I get ImportError: ./fast_parts.so: undefined symbol: _ZN5stxxl10ran32StateE This says to me that the STXXL library isn't being linked, but I am not sure how that could be as I am linking against it and the linker isn't giving me any errors. It's worth noting I can successfully build and run standalone programs using STXXL and as far as I know the libraries are stored in a .a archive in the lib directory shown below. I have reduced my Makefile down to a single command as follows: g++ -I/home/zenna/Downloads/stxxl-1.3.0/include -include stxxl/bits/defines.h -I/home/zenna/local/include -I/usr/include/python2.6 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -O3 -Wall -g -DFOO=BAR -pthread -L/home/zenna/Downloads/stxxl-1.3.0/lib/ -lstxxl -L/home/zenna/local/lib/ -lboost_python -lpython2.6 -fPIC -shared -o fast_parts.so partition.cpp Any advice? A: I'm assuming Linux, please comment if this is incorrect. What does the ldd output for libfast_parts.so look like? Does it indicate libstxxl.so is not found? You might need to add /home/zenna/Downloads/stxxl-1.3.0/lib/ in your LD_LIBRARY_PATH or the rpath for libfast_parts.so. -Wl,-rpath,/home/zenna/Downloads/stxxl-1.3.0/lib -L/home/zenna/Downloads/stxxl-1.3.0/lib -lstxxl
Linking a static library into Boost Python (shared library) - Import Error
I am building a Boost Python module (.so shared library file) which depends on another external library (STXXL) While I can build and import the example Boost Python modules, I run into problems when STXXL is thrown into the mix. Specifically when running import fast_parts in python I get ImportError: ./fast_parts.so: undefined symbol: _ZN5stxxl10ran32StateE This says to me that the STXXL library isn't being linked, but I am not sure how that could be as I am linking against it and the linker isn't giving me any errors. It's worth noting I can successfully build and run standalone programs using STXXL and as far as I know the libraries are stored in a .a archive in the lib directory shown below. I have reduced my Makefile down to a single command as follows: g++ -I/home/zenna/Downloads/stxxl-1.3.0/include -include stxxl/bits/defines.h -I/home/zenna/local/include -I/usr/include/python2.6 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -O3 -Wall -g -DFOO=BAR -pthread -L/home/zenna/Downloads/stxxl-1.3.0/lib/ -lstxxl -L/home/zenna/local/lib/ -lboost_python -lpython2.6 -fPIC -shared -o fast_parts.so partition.cpp Any advice?
[ "I'm assuming Linux, please comment if this is incorrect. What does the ldd output for libfast_parts.so look like? Does it indicate libstxxl.so is not found?\nYou might need to add /home/zenna/Downloads/stxxl-1.3.0/lib/ in your LD_LIBRARY_PATH or the rpath for libfast_parts.so.\n-Wl,-rpath,/home/zenna/Downloads/stx...
[ 0 ]
[]
[]
[ "boost", "c++", "compilation", "linker", "python" ]
stackoverflow_0003518069_boost_c++_compilation_linker_python.txt
Q: Dealing with context classes in Python 2.4 I'm trying to use the python-daemon module. It supplies the daemon.DaemonContext class to properly daemonize a script. Although I'm primarily targeting Python 2.6+, I'd like to maintain backwards compatibility to version 2.4. Python 2.5 supports importing contexts from future, but Python 2.4 has no such facility. I figured I could just catch whatever error the with statement raises and enter and exit the context manually for 2.4, but I can't seem to catch the SyntaxError raised. Is there any way to accomplish this short of explicitly checking the interpreter version? Below is the gist of what I'm trying to do and the problem I'm getting. In Real Life I don't have control of the context class, so it needs to work without mangling the original class, ie not like these ideas. Nevermind if Python 2.4 can't run python-daemon; I'd at least like to able to catch the error and implement a fallback or something. Thanks for helping. #!/usr/bin/python2.4 from __future__ import with_statement # with_statement isn't in __future__ in 2.4. # In interactive mode this raises a SyntaxError. # During normal execution it doesn't, but I wouldn't be able to catch it # anyways because __future__ imports must be at the beginning of the file, so # that point is moot. class contextable(object): def __enter__(self): print('Entering context.') return None def __exit__(self, exc_type, exc_val, exc_tb): print('Exiting context.') return False def spam(): print('Within context.') context = contextable() try: with context: # This raises an uncatchable SyntaxError. spam() except SyntaxError, e: # This is how I would like to work around it. context.__enter__() try: spam() finally: context.__exit__(None, None, None) A: SyntaxError is diagnosed by the Python compiler as it compiles -- you're presumably trying to "catch" it from code that's being compiled as part of the same module (e.g., that's what you're doing in your code sample), so of course it won't work -- your "catching" code hasn't been compiled yet (because compilation has terminated unsuccessfully) so it can't catch anything. You need to ensure the code that might have a syntax error gets compiled later than the catching code -- either put it in a separate module that you import in the try clause, or in a string you compile with the built-in by that name (you can later execute the bytecode resulting from the compile call, if it terminates successfully). Neither possibility looks good for your purposes, I think. I suspect that using two separate modules (and probably picking between them depending on the "does this compile" check, but a version check sounds much cleaner to me) is the only "clean" solution, unfortunately. Edit: here's how to microbenchmark try/except against version checks: $ python2.4 -mtimeit 'try: compile("with x: pass", "", "exec") except SyntaxError: x=1 else: x=2' 100000 loops, best of 3: 10.8 usec per loop $ python2.6 -mtimeit 'try: compile("with x: pass", "", "exec") except SyntaxError: x=1 else: x=2' 10000 loops, best of 3: 40.5 usec per loop $ python2.4 -mtimeit -s'import sys' 'if sys.version>="2.5": x=2 else: x=1' 1000000 loops, best of 3: 0.221 usec per loop $ python2.6 -mtimeit -s'import sys' 'if sys.version>="2.5": x=2 else: x=1' 10000000 loops, best of 3: 0.156 usec per loop As you see, the version I consider cleaner is 10.8 / 0.221, almost 50 times faster, on 2.4, and 40.5 / 0.156, almost 260 times faster, on 2.6. In general (with rare exceptions), the clean (i.e., "pythonic") approach will turn out to be the better optimized one in Python -- often, at least part of the reason can be that Python core developers focus on facilitating and encouraging the use of constructs they like, rather than that of constructs they dislike.
Dealing with context classes in Python 2.4
I'm trying to use the python-daemon module. It supplies the daemon.DaemonContext class to properly daemonize a script. Although I'm primarily targeting Python 2.6+, I'd like to maintain backwards compatibility to version 2.4. Python 2.5 supports importing contexts from future, but Python 2.4 has no such facility. I figured I could just catch whatever error the with statement raises and enter and exit the context manually for 2.4, but I can't seem to catch the SyntaxError raised. Is there any way to accomplish this short of explicitly checking the interpreter version? Below is the gist of what I'm trying to do and the problem I'm getting. In Real Life I don't have control of the context class, so it needs to work without mangling the original class, ie not like these ideas. Nevermind if Python 2.4 can't run python-daemon; I'd at least like to able to catch the error and implement a fallback or something. Thanks for helping. #!/usr/bin/python2.4 from __future__ import with_statement # with_statement isn't in __future__ in 2.4. # In interactive mode this raises a SyntaxError. # During normal execution it doesn't, but I wouldn't be able to catch it # anyways because __future__ imports must be at the beginning of the file, so # that point is moot. class contextable(object): def __enter__(self): print('Entering context.') return None def __exit__(self, exc_type, exc_val, exc_tb): print('Exiting context.') return False def spam(): print('Within context.') context = contextable() try: with context: # This raises an uncatchable SyntaxError. spam() except SyntaxError, e: # This is how I would like to work around it. context.__enter__() try: spam() finally: context.__exit__(None, None, None)
[ "SyntaxError is diagnosed by the Python compiler as it compiles -- you're presumably trying to \"catch\" it from code that's being compiled as part of the same module (e.g., that's what you're doing in your code sample), so of course it won't work -- your \"catching\" code hasn't been compiled yet (because compilat...
[ 3 ]
[]
[]
[ "backwards_compatibility", "python", "with_statement" ]
stackoverflow_0003518472_backwards_compatibility_python_with_statement.txt
Q: Iterate across arbitrary dimension in numpy I have a multidimensional numpy array, and I need to iterate across a given dimension. Problem is, I won't know which dimension until runtime. In other words, given an array m, I could want m[:,:,:,i] for i in xrange(n) or I could want m[:,:,i,:] for i in xrange(n) etc. I imagine that there must be a straightforward feature in numpy to write this, but I can't figure out what it is/what it might be called. Any thoughts? A: There are many ways to do this. You could build the right index with a list of slices, or perhaps alter m's strides. However, the simplest way may be to use np.swapaxes: import numpy as np m=np.arange(24).reshape(2,3,4) print(m.shape) # (2, 3, 4) Let axis be the axis you wish to loop over. m_swapped is the same as m except the axis=1 axis is swapped with the last (axis=-1) axis. axis=1 m_swapped=m.swapaxes(axis,-1) print(m_swapped.shape) # (2, 4, 3) Now you can just loop over the last axis: for i in xrange(m_swapped.shape[-1]): assert np.all(m[:,i,:] == m_swapped[...,i]) Note that m_swapped is a view, not a copy, of m. Altering m_swapped will alter m. m_swapped[1,2,0]=100 print(m) assert(m[1,0,2]==100) A: You can use slice(None) in place of the :. For example, from numpy import * d = 2 # the dimension to iterate x = arange(5*5*5).reshape((5,5,5)) s = slice(None) # : for i in range(5): slicer = [s]*3 # [:, :, :] slicer[d] = i # [:, :, i] print x[slicer] # x[:, :, i]
Iterate across arbitrary dimension in numpy
I have a multidimensional numpy array, and I need to iterate across a given dimension. Problem is, I won't know which dimension until runtime. In other words, given an array m, I could want m[:,:,:,i] for i in xrange(n) or I could want m[:,:,i,:] for i in xrange(n) etc. I imagine that there must be a straightforward feature in numpy to write this, but I can't figure out what it is/what it might be called. Any thoughts?
[ "There are many ways to do this. You could build the right index with a list of slices, or perhaps alter m's strides. However, the simplest way may be to use np.swapaxes:\nimport numpy as np\nm=np.arange(24).reshape(2,3,4)\nprint(m.shape)\n# (2, 3, 4)\n\nLet axis be the axis you wish to loop over. m_swapped is the ...
[ 6, 5 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003513424_numpy_python.txt
Q: Generating a set random list of integers based on a distribution I hope I can explain this well, if I don't I'll try again. I want to generate an array of 5 random numbers that all add up to 10 but whose allocation are chosen on an interval of [0,2n/m]. I'm using numpy. The code I have so far looks like this: import numpy as np n=10 m=5 #interval that numbers are generated on randNumbers= np.random.uniform(0,np.divide(np.multiply(2.0,n),fronts),fronts) #Here I normalize the random numbers normNumbers = np.divide(randNumbers,np.sum(randNumbers)) #Next I multiply the normalized numbers by n newList = np.multiply(normNumbers,n) #Round the numbers two whole numbers finalList = np.around(newList) This works for the most part, however the rounding is off, it will add up to 9 or 11 as opposed to 10. Is there a way to do what I'm trying to do without worrying about rounding errors, or maybe a way to work around them? If you would like for me to be more clear I can, because I have trouble explaining what I'm trying to do with this when talking :). A: Just generate four of the numbers using the technique above, then subtract the sum of the four from 10 to pick the last number. A: This generates all the possible combinations that sum to 10 and selects a random one from itertools import product from random import choice n=10 m=5 finalList = choice([x for x in product(*[range(2*n/m+1)]*m) if sum(x) == 10]) There may be a more efficient way, but this will select fairly between the outcomes Lets see how this works when n=10 and m=5 2*n/m+1 = 5, so the expression becomes finalList = choice([x for x in product(*[range(5)]*5) if sum(x) == 10]) `*[range(5)]*5 is using argument unpacking. This is equivalent to finalList = choice([x for x in product(range(5),range(5),range(5),range(5),range(5)) if sum(x) == 10]) product() gives the cartesian product of the parameters, which in this case has 5**5 elements, but we then filter out the ones that don't add to 10, which leaves a list of 381 values choice() is used to select a random value from the resultant list
Generating a set random list of integers based on a distribution
I hope I can explain this well, if I don't I'll try again. I want to generate an array of 5 random numbers that all add up to 10 but whose allocation are chosen on an interval of [0,2n/m]. I'm using numpy. The code I have so far looks like this: import numpy as np n=10 m=5 #interval that numbers are generated on randNumbers= np.random.uniform(0,np.divide(np.multiply(2.0,n),fronts),fronts) #Here I normalize the random numbers normNumbers = np.divide(randNumbers,np.sum(randNumbers)) #Next I multiply the normalized numbers by n newList = np.multiply(normNumbers,n) #Round the numbers two whole numbers finalList = np.around(newList) This works for the most part, however the rounding is off, it will add up to 9 or 11 as opposed to 10. Is there a way to do what I'm trying to do without worrying about rounding errors, or maybe a way to work around them? If you would like for me to be more clear I can, because I have trouble explaining what I'm trying to do with this when talking :).
[ "Just generate four of the numbers using the technique above, then subtract the sum of the four from 10 to pick the last number.\n", "This generates all the possible combinations that sum to 10 and selects a random one\nfrom itertools import product\nfrom random import choice\nn=10\nm=5\nfinalList = choice([x for...
[ 1, 1 ]
[]
[]
[ "algorithm", "python", "random" ]
stackoverflow_0003518597_algorithm_python_random.txt
Q: Scrapy web scraper can not crawl link I'm very new to Scrapy. Here my spider to crawl twistedweb. class TwistedWebSpider(BaseSpider): name = "twistedweb3" allowed_domains = ["twistedmatrix.com"] start_urls = [ "http://twistedmatrix.com/documents/current/web/howto/", ] rules = ( Rule(SgmlLinkExtractor(), 'parse', follow=True, ), ) def parse(self, response): print response.url filename = response.url.split("/")[-1] filename = filename or "index.html" open(filename, 'wb').write(response.body) When I run scrapy-ctl.py crawl twistedweb3, it fetched only. Getting the index.html content, I tried using SgmlLinkExtractor, it extract links as I expected but these links can not be followed. Can you show me where I am going wrong? Suppose I want to get css, javascript file. How do I achieve this? I mean get full website? A: rules attribute belongs to CrawlSpider.Use class MySpider(CrawlSpider). Also, when you use CrawlSpider you must not override parse method, instead use parse_response or other similar name.
Scrapy web scraper can not crawl link
I'm very new to Scrapy. Here my spider to crawl twistedweb. class TwistedWebSpider(BaseSpider): name = "twistedweb3" allowed_domains = ["twistedmatrix.com"] start_urls = [ "http://twistedmatrix.com/documents/current/web/howto/", ] rules = ( Rule(SgmlLinkExtractor(), 'parse', follow=True, ), ) def parse(self, response): print response.url filename = response.url.split("/")[-1] filename = filename or "index.html" open(filename, 'wb').write(response.body) When I run scrapy-ctl.py crawl twistedweb3, it fetched only. Getting the index.html content, I tried using SgmlLinkExtractor, it extract links as I expected but these links can not be followed. Can you show me where I am going wrong? Suppose I want to get css, javascript file. How do I achieve this? I mean get full website?
[ "rules attribute belongs to CrawlSpider.Use class MySpider(CrawlSpider).\nAlso, when you use CrawlSpider you must not override parse method,\ninstead use parse_response or other similar name.\n" ]
[ 4 ]
[]
[]
[ "python", "scrapy", "screen_scraping" ]
stackoverflow_0003518303_python_scrapy_screen_scraping.txt
Q: Comma seperated file that I want to load into a dictionary I have a comma seperated file, a row looks like: "ABC234234", 23 I want to load this into a dictionary, with the key being the first part i.e. "ABC234234" I have to remote the double quotes also. What's the pythonic way of doing this? A: I would suggest (like always) opening the CSV file with the with statement (which ensures it will be closed when you're done!) -- apart from that, @carl's answer is generally fine: import csv with open('yourfile.csv', 'rb') as f: thedict = dict(csv.reader(f)) and then freely use thedict as you require. Note that the values (as well, of course, as the keys) will be strings. If you know that the second column always has an integer, and want to have ints as values, you could replace the assignment with thedict = dict((k, int(v)) for k, v in csv.reader(f)) or, if you prefer to avoid excessive compactness/density in your code, decompose this latest statement into, for example: ks_vs = ((k, int(v)) for k, v in csv.reader(f)) thedict = dict(ks_vs) or break it down even further, if you wish, of course. This works in Python 2.6 or better. If you're stuck with 2.5, to make it work, add from __future__ import with_statement at the top of the module -- the rest of my advice still applies;-). A: import csv d = dict(csv.reader(open("foo.txt", "rb"))) A: You asked for Pythonic. If you wish to follow one of the precepts in the Zen of Python ("Errors should never pass silently") and you want to check that there are no duplicate keys in your data, or do other error checking or sanitising (examples: key can't be an empty string, want to strip leading/trailing whitespace), you'll need to write more detailed code. #untested example import csv with open('the_file.csv', 'rb') as f: reader = csv.reader(f) the_dict = {} for rownum, row in enumerate(reader, start=1): if len(row) != 2: error('row length is not 2', rownum, row) continue k, v = [item.strip() for item in row] if not k: error('key is empty string', ...); continue if k in the_dict: error(...); continue the_dict[k] = v
Comma seperated file that I want to load into a dictionary
I have a comma seperated file, a row looks like: "ABC234234", 23 I want to load this into a dictionary, with the key being the first part i.e. "ABC234234" I have to remote the double quotes also. What's the pythonic way of doing this?
[ "I would suggest (like always) opening the CSV file with the with statement (which ensures it will be closed when you're done!) -- apart from that, @carl's answer is generally fine:\nimport csv\n\nwith open('yourfile.csv', 'rb') as f:\n thedict = dict(csv.reader(f))\n\nand then freely use thedict as you require....
[ 6, 4, 3 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003518722_dictionary_python.txt
Q: Java text extraction and data structure design I have a huge set of data of tables in Open Office 3.0 document format. Table 1: (x range)|(x1,y1) |(x2,y2)|(x3,x3)|(x4,y4) (-20,90) |(-20,0) |(-5,1) |(5,1) |(10,0) ... Like wise i have n number of tables.All of these tables are fuzzy set membership functions.In simple terms they are computational model's according to which i have to process the input data.There are many number of such tables with differing row size and column size 3/4 .These data's are not going to change once loaded. Example: When i get a value of x in between the range -20 to 90.I will apply the first rule(given above).Suppose that it is -1(which is in between value of -20 and -5).Then I have to find a corresponding value between 0 and 1. My First question is how to extract all the data from the tables in document format so that i can use in my java program.I know a bit of python and I know python can be useful in such cases.But then how to use it in my Java program. Secondly what would be the best data structure i should use in such a senario. Note: I'm not using any database.So i would prefer to keep the tables either in xml or some other format so that i can load it easily to the program.I also thinking of making a suitable data structure and then serializing them so that I can load them whenever required instead of parsing a file and recreating the data structure.Please post your comments. A: In order to parse an OpenOffice Document in Java (to extract data), you can use a dedicated API such as ODFDOM. I think this solution is very complicated for what you need. A easier solution would be to extract manually the OpenOffice table, to put it in a format more friendly to parse in Java: CSV DataBase (MySQL, etc.)
Java text extraction and data structure design
I have a huge set of data of tables in Open Office 3.0 document format. Table 1: (x range)|(x1,y1) |(x2,y2)|(x3,x3)|(x4,y4) (-20,90) |(-20,0) |(-5,1) |(5,1) |(10,0) ... Like wise i have n number of tables.All of these tables are fuzzy set membership functions.In simple terms they are computational model's according to which i have to process the input data.There are many number of such tables with differing row size and column size 3/4 .These data's are not going to change once loaded. Example: When i get a value of x in between the range -20 to 90.I will apply the first rule(given above).Suppose that it is -1(which is in between value of -20 and -5).Then I have to find a corresponding value between 0 and 1. My First question is how to extract all the data from the tables in document format so that i can use in my java program.I know a bit of python and I know python can be useful in such cases.But then how to use it in my Java program. Secondly what would be the best data structure i should use in such a senario. Note: I'm not using any database.So i would prefer to keep the tables either in xml or some other format so that i can load it easily to the program.I also thinking of making a suitable data structure and then serializing them so that I can load them whenever required instead of parsing a file and recreating the data structure.Please post your comments.
[ "In order to parse an OpenOffice Document in Java (to extract data), you can use a dedicated API such as ODFDOM.\nI think this solution is very complicated for what you need. A easier solution would be to extract manually the OpenOffice table, to put it in a format more friendly to parse in Java:\n\nCSV\nDataBase (...
[ 1 ]
[]
[]
[ "data_structures", "java", "python", "serialization", "text_extraction" ]
stackoverflow_0003519015_data_structures_java_python_serialization_text_extraction.txt
Q: python string conversion for eval I have list like: ['name','country_id', 'price','rate','discount', 'qty'] and a string expression like exp = 'qty * price - discount + 100' I want to convert this expression into exp = 'obj.qty * obj.price - obj.discount + 100' as I wanna eval this expression like eval(exp or False, dict(obj=my_obj)) my question is what would be the best way to generate the expression for python eval evaluation.... A: Of course you have to be very careful using eval. Would be interesting to know why you need to use eval for this at all This way makes it harder for something bad to happen if a malicious user finds a way to put non numeric data in the fields import re exp = 'qty * price - discount + 100' exp = re.sub('(qty|price|discount)','%(\\1)f', exp)%vars(obj) A: I assume that the list you have is the list of available obj properties. If it is so, I'd suggest to use regular expressions, like this: import re properties = ['name', 'country_id', 'price', 'rate', 'discount', 'qty'] prefix = 'obj' exp = 'qty * price - discount + 100' r = re.compile('(' + '|'.join(properties) + ')') new_exp = r.sub(prefix + r'.\1', exp) A: The simplest way would be to loop through each of your potential variables, and replace all instances of them in the target string. keys = ['name','country_id', 'price','rate','discount', 'qty'] exp = 'qty * price - discount + 100' for key in keys: exp = exp.replace(key, '%s.%s' % ('your_object', key)) Output: 'your_object.qty * your_object.price - your_object.discount + 100'
python string conversion for eval
I have list like: ['name','country_id', 'price','rate','discount', 'qty'] and a string expression like exp = 'qty * price - discount + 100' I want to convert this expression into exp = 'obj.qty * obj.price - obj.discount + 100' as I wanna eval this expression like eval(exp or False, dict(obj=my_obj)) my question is what would be the best way to generate the expression for python eval evaluation....
[ "Of course you have to be very careful using eval. Would be interesting to know why you need to use eval for this at all\nThis way makes it harder for something bad to happen if a malicious user finds a way to put non numeric data in the fields\nimport re\nexp = 'qty * price - discount + 100'\nexp = re.sub('(qty|pr...
[ 2, 1, 1 ]
[]
[]
[ "eval", "expression", "python", "regex", "string" ]
stackoverflow_0003519074_eval_expression_python_regex_string.txt
Q: Why Does Looping Beat Indexing Here? A few years ago, someone posted on Active State Recipes for comparison purposes, three python/NumPy functions; each of these accepted the same arguments and returned the same result, a distance matrix. Two of these were taken from published sources; they are both--or they appear to me to be--idiomatic numpy code. The repetitive calculations required to create a distance matrix are driven by numpy's elegant index syntax. Here's one of them: from numpy.matlib import repmat, repeat def calcDistanceMatrixFastEuclidean(points): numPoints = len(points) distMat = sqrt(sum((repmat(points, numPoints, 1) - repeat(points, numPoints, axis=0))**2, axis=1)) return distMat.reshape((numPoints,numPoints)) The third created the distance matrix using a single loop (which, obviously is a lot of looping given that a distance matrix of just 1,000 2D points, has one million entries). At first glance this function looked to me like the code I used to write when I was learning NumPy and I would write NumPy code by first writing Python code and then translating it, line by line. Several months after the Active State post, results of performance tests comparing the three were posted and discussed in a thread on the NumPy mailing list. The function with the loop in fact significantly outperformed the other two: from numpy import mat, zeros, newaxis def calcDistanceMatrixFastEuclidean2(nDimPoints): nDimPoints = array(nDimPoints) n,m = nDimPoints.shape delta = zeros((n,n),'d') for d in xrange(m): data = nDimPoints[:,d] delta += (data - data[:,newaxis])**2 return sqrt(delta) One participant in the thread (Keir Mierle) offered a reason why this might be true: The reason that I suspect this will be faster is that it has better locality, completely finishing a computation on a relatively small working set before moving onto the next one. The one liners have to pull the potentially large MxN array into the processor repeatedly. By this poster's own account, his remark is only a suspicion, and it doesn't appear that it was discussed any further. Any other thoughts about how to account for these results? In particular, is there a useful rule--regarding when to loop and when to index--that can be extracted from this example as guidance in writing numpy code? For those not familiar with NumPy, or who haven't looked at the code, this comparison is not based on an edge case--it certainly wouldn't be that interesting to me if it were. Instead, this comparison involves a function that performs a common task in matrix computation (i.e., creating a result array given two antecedents); moreover, each function is in turn comprised of among the most common numpy built-ins. A: TL; DR The second code above is only looping over the number of dimensions of the points (3 times through the for loop for 3D points) so the looping isn't much there. The real speed-up in the second code above is that it better harnesses the power of Numpy to avoid creating some extra matrices when finding the differences between points. This reduces memory used and computational effort. Longer Explanation I think that the calcDistanceMatrixFastEuclidean2 function is deceiving you with its loop perhaps. It is only looping over the number of dimensions of the points. For 1D points, the loop only executes once, for 2D, twice, and for 3D, thrice. This is really not much looping at all. Let's analyze the code a little bit to see why the one is faster than the other. calcDistanceMatrixFastEuclidean I will call fast1 and calcDistanceMatrixFastEuclidean2 will be fast2. fast1 is based on the Matlab way of doing things as is evidenced by the repmap function. The repmap function creates an array in this case that is just the original data repeated over and over again. However, if you look at the code for the function, it is very inefficient. It uses many Numpy functions (3 reshapes and 2 repeats) to do this. The repeat function is also used to create an array that contains the the original data with each data item repeated many times. If our input data is [1,2,3] then we are subtracting [1,2,3,1,2,3,1,2,3] from [1,1,1,2,2,2,3,3,3]. Numpy has had to create a lot of extra matrices in between running Numpy's C code which could have been avoided. fast2 uses more of Numpy's heavy lifting without creating as many matrices between Numpy calls. fast2 loops through each dimension of the points, does the subtraction and keeps a running total of the squared differences between each dimension. Only at the end is the square root done. So far, this may not sound quite as efficient as fast1, but fast2 avoids doing the repmat stuff by using Numpy's indexing. Let's look at the 1D case for simplicity. fast2 makes a 1D array of the data and subtracts it from a 2D (N x 1) array of the data. This creates the difference matrix between each point and all of the other points without having to use repmat and repeat and thereby bypasses creating a lot of extra arrays. This is where the real speed difference lies in my opinion. fast1 creates a lot of extra in between matrices (and they are created expensively computationally) to find the differences between points while fast2 better harnesses the power of Numpy to avoid these. By the way, here is a little bit faster version of fast2: def calcDistanceMatrixFastEuclidean3(nDimPoints): nDimPoints = array(nDimPoints) n,m = nDimPoints.shape data = nDimPoints[:,0] delta = (data - data[:,newaxis])**2 for d in xrange(1,m): data = nDimPoints[:,d] delta += (data - data[:,newaxis])**2 return sqrt(delta) The difference is that we are no longer creating delta as a zeros matrix. A: dis for fun: dis.dis(calcDistanceMatrixFastEuclidean) 2 0 LOAD_GLOBAL 0 (len) 3 LOAD_FAST 0 (points) 6 CALL_FUNCTION 1 9 STORE_FAST 1 (numPoints) 3 12 LOAD_GLOBAL 1 (sqrt) 15 LOAD_GLOBAL 2 (sum) 18 LOAD_GLOBAL 3 (repmat) 21 LOAD_FAST 0 (points) 24 LOAD_FAST 1 (numPoints) 27 LOAD_CONST 1 (1) 30 CALL_FUNCTION 3 4 33 LOAD_GLOBAL 4 (repeat) 36 LOAD_FAST 0 (points) 39 LOAD_FAST 1 (numPoints) 42 LOAD_CONST 2 ('axis') 45 LOAD_CONST 3 (0) 48 CALL_FUNCTION 258 51 BINARY_SUBTRACT 52 LOAD_CONST 4 (2) 55 BINARY_POWER 56 LOAD_CONST 2 ('axis') 59 LOAD_CONST 1 (1) 62 CALL_FUNCTION 257 65 CALL_FUNCTION 1 68 STORE_FAST 2 (distMat) 5 71 LOAD_FAST 2 (distMat) 74 LOAD_ATTR 5 (reshape) 77 LOAD_FAST 1 (numPoints) 80 LOAD_FAST 1 (numPoints) 83 BUILD_TUPLE 2 86 CALL_FUNCTION 1 89 RETURN_VALUE dis.dis(calcDistanceMatrixFastEuclidean2) 2 0 LOAD_GLOBAL 0 (array) 3 LOAD_FAST 0 (nDimPoints) 6 CALL_FUNCTION 1 9 STORE_FAST 0 (nDimPoints) 3 12 LOAD_FAST 0 (nDimPoints) 15 LOAD_ATTR 1 (shape) 18 UNPACK_SEQUENCE 2 21 STORE_FAST 1 (n) 24 STORE_FAST 2 (m) 4 27 LOAD_GLOBAL 2 (zeros) 30 LOAD_FAST 1 (n) 33 LOAD_FAST 1 (n) 36 BUILD_TUPLE 2 39 LOAD_CONST 1 ('d') 42 CALL_FUNCTION 2 45 STORE_FAST 3 (delta) 5 48 SETUP_LOOP 76 (to 127) 51 LOAD_GLOBAL 3 (xrange) 54 LOAD_FAST 2 (m) 57 CALL_FUNCTION 1 60 GET_ITER >> 61 FOR_ITER 62 (to 126) 64 STORE_FAST 4 (d) 6 67 LOAD_FAST 0 (nDimPoints) 70 LOAD_CONST 0 (None) 73 LOAD_CONST 0 (None) 76 BUILD_SLICE 2 79 LOAD_FAST 4 (d) 82 BUILD_TUPLE 2 85 BINARY_SUBSCR 86 STORE_FAST 5 (data) 7 89 LOAD_FAST 3 (delta) 92 LOAD_FAST 5 (data) 95 LOAD_FAST 5 (data) 98 LOAD_CONST 0 (None) 101 LOAD_CONST 0 (None) 104 BUILD_SLICE 2 107 LOAD_GLOBAL 4 (newaxis) 110 BUILD_TUPLE 2 113 BINARY_SUBSCR 114 BINARY_SUBTRACT 115 LOAD_CONST 2 (2) 118 BINARY_POWER 119 INPLACE_ADD 120 STORE_FAST 3 (delta) 123 JUMP_ABSOLUTE 61 >> 126 POP_BLOCK 8 >> 127 LOAD_GLOBAL 5 (sqrt) 130 LOAD_FAST 3 (delta) 133 CALL_FUNCTION 1 136 RETURN_VALUE I'm not an expert on dis, but it seems like you would have to look more at the functions that the first is calling to know why they take a while. There is a performance profiler tool with Python as well, cProfile.
Why Does Looping Beat Indexing Here?
A few years ago, someone posted on Active State Recipes for comparison purposes, three python/NumPy functions; each of these accepted the same arguments and returned the same result, a distance matrix. Two of these were taken from published sources; they are both--or they appear to me to be--idiomatic numpy code. The repetitive calculations required to create a distance matrix are driven by numpy's elegant index syntax. Here's one of them: from numpy.matlib import repmat, repeat def calcDistanceMatrixFastEuclidean(points): numPoints = len(points) distMat = sqrt(sum((repmat(points, numPoints, 1) - repeat(points, numPoints, axis=0))**2, axis=1)) return distMat.reshape((numPoints,numPoints)) The third created the distance matrix using a single loop (which, obviously is a lot of looping given that a distance matrix of just 1,000 2D points, has one million entries). At first glance this function looked to me like the code I used to write when I was learning NumPy and I would write NumPy code by first writing Python code and then translating it, line by line. Several months after the Active State post, results of performance tests comparing the three were posted and discussed in a thread on the NumPy mailing list. The function with the loop in fact significantly outperformed the other two: from numpy import mat, zeros, newaxis def calcDistanceMatrixFastEuclidean2(nDimPoints): nDimPoints = array(nDimPoints) n,m = nDimPoints.shape delta = zeros((n,n),'d') for d in xrange(m): data = nDimPoints[:,d] delta += (data - data[:,newaxis])**2 return sqrt(delta) One participant in the thread (Keir Mierle) offered a reason why this might be true: The reason that I suspect this will be faster is that it has better locality, completely finishing a computation on a relatively small working set before moving onto the next one. The one liners have to pull the potentially large MxN array into the processor repeatedly. By this poster's own account, his remark is only a suspicion, and it doesn't appear that it was discussed any further. Any other thoughts about how to account for these results? In particular, is there a useful rule--regarding when to loop and when to index--that can be extracted from this example as guidance in writing numpy code? For those not familiar with NumPy, or who haven't looked at the code, this comparison is not based on an edge case--it certainly wouldn't be that interesting to me if it were. Instead, this comparison involves a function that performs a common task in matrix computation (i.e., creating a result array given two antecedents); moreover, each function is in turn comprised of among the most common numpy built-ins.
[ "TL; DR The second code above is only looping over the number of dimensions of the points (3 times through the for loop for 3D points) so the looping isn't much there. The real speed-up in the second code above is that it better harnesses the power of Numpy to avoid creating some extra matrices when finding the dif...
[ 11, 1 ]
[]
[]
[ "memory_management", "numpy", "performance", "python" ]
stackoverflow_0003518574_memory_management_numpy_performance_python.txt
Q: Looking for strong/explicit-typed language without GIL Are there any languages which feature static type checking like in C++ with modern syntax like in Python, and does not have GIL? I belive, Python 3 with ability to explicitly declare type of each variable would be 'almost there', but GIL makes me sad. Java is nice, but I need something more 'embedable' without bulky JRE. Update: Anything .NET-related or non-open source is a no-go. Update2: I need explicit+strong typing to write safer code in the expense of development speed. GIL is important as the code is going to be quite computing extensive and will run on multicore servers, so it has to effectively use multiple CPU. Update3: Target platform is Linux(Debian) on x86 A: Boo Boo is an object oriented, statically typed programming language that seeks to make use of the Common Language Infrastructure's support for Unicode, internationalization and web applications, while using a Python-inspired syntax and a special focus on language and compiler extensibility. Some features of note include type inference, generators, multimethods, optional duck typing, macros, true closures, currying, and first-class functions. Boo has been actively developed since 2003. cython Cython is a language that makes writing C extensions for the Python language as easy as Python itself. Cython is based on the well-known Pyrex, but supports more cutting edge functionality and optimizations. The Cython language is very close to the Python language, but Cython additionally supports calling C functions and declaring C types on variables and class attributes. This allows the compiler to generate very efficient C code from Cython code. A: Anything in the ML family might work for you. Ocaml is a great place to start, but it does have a stop-the-world GC last I looked. Haskell is famous as a lab for innovative concurrency models. Python's comprehensions came from Haskell, where they'rr a convenient syntax for some very fundamental ideas. And Erlang is strongly dynamcally typed, fun to write in, and does concurrency better than anybody else. A: Ada is a strongly-typed, compiled language with a modern, easy-to-read syntax and proven reliability for multicore computing. Ada was designed for use in large, critical, real-time systems where software MUST work at all costs. "Ada supports run-time checks to protect against access to unallocated memory, buffer overflow errors, off-by-one errors, array access errors, and other detectable bugs. These checks can be disabled in the interest of runtime efficiency, but can often be compiled efficiently. It also includes facilities to help program verification. For these reasons, Ada is widely used in critical systems, where any anomaly might lead to very serious consequences, i.e., accidental death or injury. Examples of systems where Ada is used include avionics, weapon systems (including thermonuclear weapons), and spacecraft." (quote from Wikipedia article linked above). Ada is freely available as part of GCC / GNAT and should be an easy "apt-get install" on Debian. You can also find up-to-date compilers and libraries (both community-supported GPL-licensed and commercially-supported packages) at http://libre.adacore.com/libre/ Ada can compile to Java bytecode for use in a JVM or compile to binary for bare-metal or embedded use. A: I think GO would fit your requirements. This is my personal feeling but go code looks very similar to python code. It still has classic compile approach but google will develop some interpreter certainly. From google site: Go is a general-purpose language designed with systems programming in mind. It is strongly typed and garbage-collected and has explicit support for concurrent programming. Programs are constructed from packages, whose properties allow efficient management of dependencies. The existing implementations use a traditional compile/link model to generate executable binaries. A: After reading your updated spec: I need explicit+strong typing to write safer code in the expense of development speed. GIL is important as the code is going to be quite computing extensive and will run on multicore servers, so it has to effectively use multiple CPU What exactly does "computing extensive" mean? What problem domain? What do others who work in this problem domain use? If you are serious with this specification, you can't do much other things than using C++ in connection with well-tested libraries for multithreading and numerical computing. my $0.02 rbo
Looking for strong/explicit-typed language without GIL
Are there any languages which feature static type checking like in C++ with modern syntax like in Python, and does not have GIL? I belive, Python 3 with ability to explicitly declare type of each variable would be 'almost there', but GIL makes me sad. Java is nice, but I need something more 'embedable' without bulky JRE. Update: Anything .NET-related or non-open source is a no-go. Update2: I need explicit+strong typing to write safer code in the expense of development speed. GIL is important as the code is going to be quite computing extensive and will run on multicore servers, so it has to effectively use multiple CPU. Update3: Target platform is Linux(Debian) on x86
[ "Boo\n\nBoo is an object oriented, statically\n typed programming language that seeks\n to make use of the Common Language\n Infrastructure's support for Unicode,\n internationalization and web\n applications, while using a\n Python-inspired syntax and a\n special focus on language and compiler\n extensibi...
[ 4, 4, 3, 2, 2 ]
[]
[]
[ "gil", "java", "python" ]
stackoverflow_0003511922_gil_java_python.txt
Q: How to implement Google-style pagination on app engine? See the pagination on the app gallery? It has page numbers and a 'start' parameter which increases with the page number. Presumably this app was made on GAE. If so, how did they do this type of pagination? ATM I'm using cursors but passing them around in URLs is as ugly as hell. A: Ben Davies's outstanding PagedQuery class will do everything that you want and more. A: You can simply pass in the 'start' parameter as an offset to the .fetch() call on your query. This gets less efficient as people dive deeper into the results, but if you don't expect people to browse past 1000 or so, it's manageable. You may also want to consider keeping a cache, mapping queries and offsets to cursors, so that repeated queries can fetch the next set of results efficiently.
How to implement Google-style pagination on app engine?
See the pagination on the app gallery? It has page numbers and a 'start' parameter which increases with the page number. Presumably this app was made on GAE. If so, how did they do this type of pagination? ATM I'm using cursors but passing them around in URLs is as ugly as hell.
[ "Ben Davies's outstanding PagedQuery class will do everything that you want and more.\n", "You can simply pass in the 'start' parameter as an offset to the .fetch() call on your query. This gets less efficient as people dive deeper into the results, but if you don't expect people to browse past 1000 or so, it's m...
[ 1, 1 ]
[]
[]
[ "bigtable", "google_app_engine", "google_cloud_datastore", "pagination", "python" ]
stackoverflow_0003514230_bigtable_google_app_engine_google_cloud_datastore_pagination_python.txt
Q: Exception handling in Python http://docs.python.org/library/imaplib.html states that: exception IMAP4.error Exception raised on any errors. The reason for the exception is passed to the constructor as a string. What does "exception is passed to the constructor as a string" mean? What would the code look like that can print the reason. A: Just use print str(exception). A: You can specify the reason when constructing the exception yourself, and put it into a variable when catching the exception. try: raise imaplib.IMAP4.error('Some exception') except imaplib.IMAP4.error, error: print error
Exception handling in Python
http://docs.python.org/library/imaplib.html states that: exception IMAP4.error Exception raised on any errors. The reason for the exception is passed to the constructor as a string. What does "exception is passed to the constructor as a string" mean? What would the code look like that can print the reason.
[ "Just use print str(exception).\n", "You can specify the reason when constructing the exception yourself, and put it into a variable when catching the exception.\ntry:\n raise imaplib.IMAP4.error('Some exception')\nexcept imaplib.IMAP4.error, error:\n print error\n\n" ]
[ 2, 1 ]
[]
[]
[ "exception", "exception_handling", "python" ]
stackoverflow_0003519494_exception_exception_handling_python.txt
Q: Python Regex, re.sub, replacing multiple parts of pattern? I can't seem to find a good resource on this.. I am trying to do a simple re.place I want to replace the part where its (.*?), but can't figure out the syntax on how to do this.. I know how to do it in PHP, so I've been messing around with what I think it could be based on that (which is why it has the $1 but I know that isn't correct in python).. I would appreciate if anyone can show the proper syntax, I'm not asking specifics for any certain string, just how I can replace something like this, or if it had more than 1 () area.. thanks originalstring = 'fksf var:asfkj;' pattern = '.*?var:(.*?);' replacement_string='$1' + 'test' replaced = re.sub(re.compile(pattern, re.MULTILINE), replacement_string, originalstring) A: >>> import re >>> originalstring = 'fksf var:asfkj;' >>> pattern = '.*?var:(.*?);' >>> pattern_obj = re.compile(pattern, re.MULTILINE) >>> replacement_string="\\1" + 'test' >>> pattern_obj.sub(replacement_string, originalstring) 'asfkjtest' Edit: The Python Docs can be pretty useful reference. A: >>> import re >>> regex = re.compile(r".*?var:(.*?);") >>> regex.sub(r"\1test", "fksf var:asfkj;") 'asfkjtest'
Python Regex, re.sub, replacing multiple parts of pattern?
I can't seem to find a good resource on this.. I am trying to do a simple re.place I want to replace the part where its (.*?), but can't figure out the syntax on how to do this.. I know how to do it in PHP, so I've been messing around with what I think it could be based on that (which is why it has the $1 but I know that isn't correct in python).. I would appreciate if anyone can show the proper syntax, I'm not asking specifics for any certain string, just how I can replace something like this, or if it had more than 1 () area.. thanks originalstring = 'fksf var:asfkj;' pattern = '.*?var:(.*?);' replacement_string='$1' + 'test' replaced = re.sub(re.compile(pattern, re.MULTILINE), replacement_string, originalstring)
[ ">>> import re\n>>> originalstring = 'fksf var:asfkj;'\n>>> pattern = '.*?var:(.*?);'\n>>> pattern_obj = re.compile(pattern, re.MULTILINE)\n>>> replacement_string=\"\\\\1\" + 'test'\n>>> pattern_obj.sub(replacement_string, originalstring)\n'asfkjtest'\n\nEdit: The Python Docs can be pretty useful reference.\n", "...
[ 19, 7 ]
[ "The python docs are online, and the one for the re module is here. http://docs.python.org/library/re.html\nTo answer your question though, Python uses \\1 rather than $1 to refer to matched groups.\n" ]
[ -2 ]
[ "python", "regex" ]
stackoverflow_0003519487_python_regex.txt
Q: Validating an XMPP jid with python? What is the correct way to validate an xmpp jid? The syntax is described here:, but I don't really understand it. Also, it seems pretty complicated, so using a library to do it would seem like a good idea. I'm currently using xmpppy, but I can't seem to find how to validate a jid with it. Any help appreciated! A: First off, the current best reference for JIDs is RFC 6122. I was just going to give you the regex in here, but got a little carried away, and implemented all of the spec: import re import sys import socket import encodings.idna import stringprep # These characters aren't allowed in domain names that are used # in XMPP BAD_DOMAIN_ASCII = "".join([chr(c) for c in range(0,0x2d) + [0x2e, 0x2f] + range(0x3a,0x41) + range(0x5b,0x61) + range(0x7b, 0x80)]) # check bi-directional character validity def bidi(chars): RandAL = map(stringprep.in_table_d1, chars) for c in RandAL: if c: # There is a RandAL char in the string. Must perform further # tests: # 1) The characters in section 5.8 MUST be prohibited. # This is table C.8, which was already checked # 2) If a string contains any RandALCat character, the string # MUST NOT contain any LCat character. if filter(stringprep.in_table_d2, chars): raise UnicodeError("Violation of BIDI requirement 2") # 3) If a string contains any RandALCat character, a # RandALCat character MUST be the first character of the # string, and a RandALCat character MUST be the last # character of the string. if not RandAL[0] or not RandAL[-1]: raise UnicodeError("Violation of BIDI requirement 3") def nodeprep(u): chars = list(unicode(u)) i = 0 while i < len(chars): c = chars[i] # map to nothing if stringprep.in_table_b1(c): del chars[i] else: # case fold chars[i] = stringprep.map_table_b2(c) i += 1 # NFKC chars = stringprep.unicodedata.normalize("NFKC", "".join(chars)) for c in chars: if (stringprep.in_table_c11(c) or stringprep.in_table_c12(c) or stringprep.in_table_c21(c) or stringprep.in_table_c22(c) or stringprep.in_table_c3(c) or stringprep.in_table_c4(c) or stringprep.in_table_c5(c) or stringprep.in_table_c6(c) or stringprep.in_table_c7(c) or stringprep.in_table_c8(c) or stringprep.in_table_c9(c) or c in "\"&'/:<>@"): raise UnicodeError("Invalid node character") bidi(chars) return chars def resourceprep(res): chars = list(unicode(res)) i = 0 while i < len(chars): c = chars[i] # map to nothing if stringprep.in_table_b1(c): del chars[i] else: i += 1 # NFKC chars = stringprep.unicodedata.normalize("NFKC", "".join(chars)) for c in chars: if (stringprep.in_table_c12(c) or stringprep.in_table_c21(c) or stringprep.in_table_c22(c) or stringprep.in_table_c3(c) or stringprep.in_table_c4(c) or stringprep.in_table_c5(c) or stringprep.in_table_c6(c) or stringprep.in_table_c7(c) or stringprep.in_table_c8(c) or stringprep.in_table_c9(c)): raise UnicodeError("Invalid node character") bidi(chars) return chars def parse_jid(jid): # first pass m = re.match("^(?:([^\"&'/:<>@]{1,1023})@)?([^/@]{1,1023})(?:/(.{1,1023}))?$", jid) if not m: return False (node, domain, resource) = m.groups() try: # ipv4 address? socket.inet_pton(socket.AF_INET, domain) except socket.error: # ipv6 address? try: socket.inet_pton(socket.AF_INET6, domain) except socket.error: # domain name dom = [] for label in domain.split("."): try: label = encodings.idna.nameprep(unicode(label)) encodings.idna.ToASCII(label) except UnicodeError: return False # UseSTD3ASCIIRules is set, but Python's nameprep doesn't enforce it. # a) Verify the absence of non-LDH ASCII code points; that is, the for c in label: if c in BAD_DOMAIN_ASCII: return False # Verify the absence of leading and trailing hyphen-minus if label[0] == '-' or label[-1] == "-": return False dom.append(label) domain = ".".join(dom) try: if node is not None: node = nodeprep(node) if resource is not None: resource = resourceprep(resource) except UnicodeError: return False return node, domain, resource if __name__ == "__main__": results = parse_jid(sys.argv[1]) if not results: print "FAIL" else: print results Yes, this is a lot of work. There's good reasons for all of it, but we're hoping to simplify it in the future somewhat if the précis working group bears fruit.
Validating an XMPP jid with python?
What is the correct way to validate an xmpp jid? The syntax is described here:, but I don't really understand it. Also, it seems pretty complicated, so using a library to do it would seem like a good idea. I'm currently using xmpppy, but I can't seem to find how to validate a jid with it. Any help appreciated!
[ "First off, the current best reference for JIDs is RFC 6122.\nI was just going to give you the regex in here, but got a little carried away, and implemented all of the spec:\nimport re\nimport sys\nimport socket\nimport encodings.idna\nimport stringprep\n\n# These characters aren't allowed in domain names that are ...
[ 20 ]
[]
[]
[ "python", "validation", "xmpp" ]
stackoverflow_0003514342_python_validation_xmpp.txt
Q: Writing python client for SOAP with suds I want to convert a perl SOAP client into a python SOAP client. The perl client is initialized like $url = 'https://host:port/cgi-devel/Service.cgi'; $uri = 'https://host/Service'; my $soap = SOAP::Lite -> uri($uri) -> proxy($url); I tried to replicate this in python 2.4.2 with suds 0.3.6 doing from suds.client import Client url="https://host:port/cgi-devel/Service.cgi" client=Client(url) However when running this python script I get the error suds.transport.TransportError: HTTP Error 411: Length Required Is it because of https or what might be the problem? Any help would be greatly appreciated! A: urllib2 module doesn't add Content-Length (required for POST method) header automatically when Request object is constructed manually as suds does. You have to patch suds, probably suds.transport.HttpTransport.open() method or suds.transport.Request class. A: I had the same error, then switched to using a local WSDL file, this worked: import suds wsdl = 'file:///tmp/my.wsdl' client = suds.client.Client(wsdl, username='lbuser', password='lbpass', location='https://path.to.our.loadbalancer:9090/soap') A: You should ask this in the suds's mailing list. This library is under development, is open source, and the authors are very keen to get feedback from the users. Your code looks fine, this could be an error of the wsdl itself or of the suds library, therefore I encourage you to ask the author directly (after having checked with other wsdls that your installation is correct).
Writing python client for SOAP with suds
I want to convert a perl SOAP client into a python SOAP client. The perl client is initialized like $url = 'https://host:port/cgi-devel/Service.cgi'; $uri = 'https://host/Service'; my $soap = SOAP::Lite -> uri($uri) -> proxy($url); I tried to replicate this in python 2.4.2 with suds 0.3.6 doing from suds.client import Client url="https://host:port/cgi-devel/Service.cgi" client=Client(url) However when running this python script I get the error suds.transport.TransportError: HTTP Error 411: Length Required Is it because of https or what might be the problem? Any help would be greatly appreciated!
[ "urllib2 module doesn't add Content-Length (required for POST method) header automatically when Request object is constructed manually as suds does. You have to patch suds, probably suds.transport.HttpTransport.open() method or suds.transport.Request class.\n", "I had the same error, then switched to using a loca...
[ 3, 3, 0 ]
[]
[]
[ "https", "python", "soap", "suds" ]
stackoverflow_0001476814_https_python_soap_suds.txt
Q: How can I speed up update/replace operations in PostgreSQL? We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects). For sanity reasons we have created our own Data Mapper-like layer that works reasonably well, but it has one big bottleneck, the update performance. Of course, I'm not expecting the update/replace scenario to be as speedy as the 'insert to an empty table' one, but it would be nice to get a bit closer. Note that this system is free from concurrent updates We always set all the fields of each rows on an update, which can be seen in the terminology where I use the word 'replace' in my tests. I've so far tried two approaches to our update problem: Create a replace() procedure that takes an array of rows to update: CREATE OR REPLACE FUNCTION replace_item(data item[]) RETURNS VOID AS $$ BEGIN FOR i IN COALESCE(array_lower(data,1),0) .. COALESCE(array_upper(data,1),-1) LOOP UPDATE item SET a0=data[i].a0,a1=data[i].a1,a2=data[i].a2 WHERE key=data[i].key; END LOOP; END; $$ LANGUAGE plpgsql Create an insert_or_replace rule so that everything but the occasional delete becomes multi-row inserts CREATE RULE "insert_or_replace" AS ON INSERT TO "item" WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) DO INSTEAD (UPDATE item SET a0=NEW.a0,a1=NEW.a1,a2=NEW.a2 WHERE key=NEW.key); These both speeds up the updates a fair bit, although the latter slows down inserts a bit: Multi-row insert : 50000 items inserted in 1.32 seconds averaging 37807.84 items/s executemany() update : 50000 items updated in 26.67 seconds averaging 1874.57 items/s update_andres : 50000 items updated in 3.84 seconds averaging 13028.51 items/s update_merlin83 (i/d/i) : 50000 items updated in 1.29 seconds averaging 38780.46 items/s update_merlin83 (i/u) : 50000 items updated in 1.24 seconds averaging 40313.28 items/s replace_item() procedure : 50000 items replaced in 3.10 seconds averaging 16151.42 items/s Multi-row insert_or_replace: 50000 items inserted in 2.73 seconds averaging 18296.30 items/s Multi-row insert_or_replace: 50000 items replaced in 2.02 seconds averaging 24729.94 items/s Random notes about the test run: All tests are run on the same computer as the database resides; connecting to localhost. Inserts and updates are applied to the database in batches of of 500 items, each sent in its own transaction (UPDATED). All update/replace tests used the same values as were already in the database. All data was escaped using the psycopg2 adapt() function. All tables are truncated and vacuumed before use (ADDED, in previous runs only truncation happened) The table looks like this: CREATE TABLE item ( key MACADDR PRIMARY KEY, a0 VARCHAR, a1 VARCHAR, a2 VARCHAR ) So, the real question is: How can I speed up update/replace operations a bit more? (I think these findings might be 'good enough', but I don't want to give up without tapping the SO crowd :) Also anyones hints towards a more elegant replace_item(), or evidence that my tests are completely broken would be most welcome. The test script is available here if you'd like to attempt to reproduce. Remember to check it first though...it WorksForMe, but... You will need to edit the db.connect() line to suit your setup. EDIT Thanks to andres in #postgresql @ freenode I have another test with a single-query update; much like a multi-row insert (listed as update_andres above). UPDATE item SET a0=i.a0, a1=i.a1, a2=i.a2 FROM (VALUES ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ... ) AS i(key, a0, a1, a2) WHERE item.key=i.key::macaddr EDIT Thanks to merlin83 in #postgresql @ freenode and jug/jwp below I have another test with an insert-to-temp/delete/insert approach (listed as "update_merlin83 (i/d/i)" above). INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); DELETE FROM item USING temp_item WHERE item.key=temp_item.key; INSERT INTO item (key, a0, a1, a2) SELECT key, a0, a1, a2 FROM temp_item; My gut feeling is that these tests are not very representative to the performance in the real-world scenario, but I think the differences are great enough to give an indication of the most promising approaches for further investigation. The perftest.py script contains all updates as well for those of you who want to check it out. It's fairly ugly though, so don't forget your goggles :) EDIT andres in #postgresql @ freenode pointed out that I should test with an insert-to-temp/update variant (listed as "update_merlin83 (i/u)" above). INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); UPDATE item SET a0=temp_item.a0, a1=temp_item.a1, a2=temp_item.a2 FROM temp_item WHERE item.key=temp_item.key EDIT Probably final edit: I changed my script to match our load scenario better, and it seems the numbers hold even when scaling things up a bit and adding some randomness. If anyone gets very different numbers from some other scenario I'd be interested in knowing about it. A: The usual way I do these things in pg is: load raw data matching target table into temp table (no constraints) using copy, merge(the fun part), profit. I wrote a merge_by_key function specifically for these situations: http://mbk.projects.postgresql.org/ The docs aren't terribly friendly, but I'd suggest giving it a good look. A: I had a similar situation a few months ago and ended up getting the largest speed boost from a tuned chunk/transaction size. You may also want to check the log for a checkpoint warning during the test and tune appropriately. A: Sounds like you'd see benefits from using WAL (Write Ahead Logging) with a UPS to cache your updates between disk writes. wal_buffers This setting decides the number of buffers WAL(Write ahead Log) can have. If your database has many write transactions, setting this value bit higher than default could result better usage of disk space. Experiment and decide. A good start would be around 32-64 corresponding to 256-512K memory. http://www.varlena.com/GeneralBits/Tidbits/perf.html A: In your insert_or_replace. try this: WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key LIMIT 1) instead of WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) As noted in comments, that will probably do nothing. All I have to add, then, is that you can always speed up INSERT/UPDATE performance by removing indexes. This will likely not be something you want to do unless you find your table is overindexed, but that should at least be checked out. A: In Oracle, locking the table would definitely help. You might want to try that with PostgreSQL, too. A: For updates, you can lower your fillfactor for the tables and the indexes and that might help http://www.postgresql.org/docs/current/static/sql-createtable.html http://www.postgresql.org/docs/current/static/sql-createindex.html
How can I speed up update/replace operations in PostgreSQL?
We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects). For sanity reasons we have created our own Data Mapper-like layer that works reasonably well, but it has one big bottleneck, the update performance. Of course, I'm not expecting the update/replace scenario to be as speedy as the 'insert to an empty table' one, but it would be nice to get a bit closer. Note that this system is free from concurrent updates We always set all the fields of each rows on an update, which can be seen in the terminology where I use the word 'replace' in my tests. I've so far tried two approaches to our update problem: Create a replace() procedure that takes an array of rows to update: CREATE OR REPLACE FUNCTION replace_item(data item[]) RETURNS VOID AS $$ BEGIN FOR i IN COALESCE(array_lower(data,1),0) .. COALESCE(array_upper(data,1),-1) LOOP UPDATE item SET a0=data[i].a0,a1=data[i].a1,a2=data[i].a2 WHERE key=data[i].key; END LOOP; END; $$ LANGUAGE plpgsql Create an insert_or_replace rule so that everything but the occasional delete becomes multi-row inserts CREATE RULE "insert_or_replace" AS ON INSERT TO "item" WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) DO INSTEAD (UPDATE item SET a0=NEW.a0,a1=NEW.a1,a2=NEW.a2 WHERE key=NEW.key); These both speeds up the updates a fair bit, although the latter slows down inserts a bit: Multi-row insert : 50000 items inserted in 1.32 seconds averaging 37807.84 items/s executemany() update : 50000 items updated in 26.67 seconds averaging 1874.57 items/s update_andres : 50000 items updated in 3.84 seconds averaging 13028.51 items/s update_merlin83 (i/d/i) : 50000 items updated in 1.29 seconds averaging 38780.46 items/s update_merlin83 (i/u) : 50000 items updated in 1.24 seconds averaging 40313.28 items/s replace_item() procedure : 50000 items replaced in 3.10 seconds averaging 16151.42 items/s Multi-row insert_or_replace: 50000 items inserted in 2.73 seconds averaging 18296.30 items/s Multi-row insert_or_replace: 50000 items replaced in 2.02 seconds averaging 24729.94 items/s Random notes about the test run: All tests are run on the same computer as the database resides; connecting to localhost. Inserts and updates are applied to the database in batches of of 500 items, each sent in its own transaction (UPDATED). All update/replace tests used the same values as were already in the database. All data was escaped using the psycopg2 adapt() function. All tables are truncated and vacuumed before use (ADDED, in previous runs only truncation happened) The table looks like this: CREATE TABLE item ( key MACADDR PRIMARY KEY, a0 VARCHAR, a1 VARCHAR, a2 VARCHAR ) So, the real question is: How can I speed up update/replace operations a bit more? (I think these findings might be 'good enough', but I don't want to give up without tapping the SO crowd :) Also anyones hints towards a more elegant replace_item(), or evidence that my tests are completely broken would be most welcome. The test script is available here if you'd like to attempt to reproduce. Remember to check it first though...it WorksForMe, but... You will need to edit the db.connect() line to suit your setup. EDIT Thanks to andres in #postgresql @ freenode I have another test with a single-query update; much like a multi-row insert (listed as update_andres above). UPDATE item SET a0=i.a0, a1=i.a1, a2=i.a2 FROM (VALUES ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ... ) AS i(key, a0, a1, a2) WHERE item.key=i.key::macaddr EDIT Thanks to merlin83 in #postgresql @ freenode and jug/jwp below I have another test with an insert-to-temp/delete/insert approach (listed as "update_merlin83 (i/d/i)" above). INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); DELETE FROM item USING temp_item WHERE item.key=temp_item.key; INSERT INTO item (key, a0, a1, a2) SELECT key, a0, a1, a2 FROM temp_item; My gut feeling is that these tests are not very representative to the performance in the real-world scenario, but I think the differences are great enough to give an indication of the most promising approaches for further investigation. The perftest.py script contains all updates as well for those of you who want to check it out. It's fairly ugly though, so don't forget your goggles :) EDIT andres in #postgresql @ freenode pointed out that I should test with an insert-to-temp/update variant (listed as "update_merlin83 (i/u)" above). INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); UPDATE item SET a0=temp_item.a0, a1=temp_item.a1, a2=temp_item.a2 FROM temp_item WHERE item.key=temp_item.key EDIT Probably final edit: I changed my script to match our load scenario better, and it seems the numbers hold even when scaling things up a bit and adding some randomness. If anyone gets very different numbers from some other scenario I'd be interested in knowing about it.
[ "The usual way I do these things in pg is: load raw data matching target table into temp table (no constraints) using copy, merge(the fun part), profit.\nI wrote a merge_by_key function specifically for these situations:\nhttp://mbk.projects.postgresql.org/\nThe docs aren't terribly friendly, but I'd suggest giving...
[ 4, 2, 2, 1, 1, 1 ]
[]
[]
[ "postgresql", "psycopg2", "python", "sql" ]
stackoverflow_0000962361_postgresql_psycopg2_python_sql.txt
Q: How to convert unicode objects to normal objects in Python I currently have a deep object, and it is all unicode (sadly). I am to a point where a variable is either going to be a dict, or a bool. In this case, I do if type( my_variable ) is BooleanType: But this is not triggered because the type is actually Unicode for all values. How do I convert this unicode object to a normal object so I can correctly read the type, without destroying the data? Thanks! Here is the result of print(repr(variable)). It shows the Bools as not being unicode (unlike what I first though) but still giving me troubles. {u'forms': {u'financing': {u'view': True, u'delete': True}, u'employment': {u'view': True, u'delete': True}, u'service': {u'view': True, u'delete': True}}, u'content': {u'articles': {u'edit': True, u'add': True, u'view': True, u'delete': True}, u'slideshow': {u'edit': True, u'view': True}, u'pages': {u'edit': True, u'add': True, u'view': True, u'delete': True}}, u'people': {u'edit': True, u'sort-staff': True, u'sort-riders': True, u'add': True, u'delete': True, u'view': True}, u'events': {u'edit': True, u'add': True, u'view': True, u'delete': True}, u'settings': {u'edit': True, u'view': True}} A: Do not use type unless you are really really sure that you want to. In this case, you don't -- especially checking for bool, given Python's flexibility for what can be considered as boolean! For instance, what if you are given None? How about an empty string? How about []? The solution to this problem is the use of Abstract Base Classes (ABCs), which allow you to specify exactly what an object should be able to do, instead of what type it is. The collections module comes with a bunch of these: import collections if isinstance( ..., collections.MutableMapping ): ... This permits anything 'dictionary-like', so that you retain polymorphism. If you need more careful specification ("I want __getitem__ and __delitem__ but not necessarily __setitem__!"), you can write your own -- see the definition of the ABCs in the source of the collections module for starters. Are you sure that you want this functionality? If you do it correctly (with ABCs), it's not an inherently bad idea, but that's not to say you should abuse it! Edit: I'm not sure that you understand what Unicode is or how Python handles it. This is one of the major differences between Python 2.x and Python 3.x, which are you using? Re-edit: Ah, ok, you are using Python 2.x and you have a dictionary with Unicode string keys. I'm not sure what you were doing that caused a problem, since Unicode strings work basically just like ordinary strings. The MutableMapping check above will work fine. A: Maybe you should learn about the pretty print module as it makes you check things (even I agree that you put yourself in mess. This usually happens as result recursion with wrong kind of result, for example doing append, when you should do extend for list) Here your variable contents pretty printed: {u'content': {u'articles': {u'add': True, u'delete': True, u'edit': True, u'view': True}, u'pages': {u'add': True, u'delete': True, u'edit': True, u'view': True}, u'slideshow': {u'edit': True, u'view': True}}, u'events': {u'add': True, u'delete': True, u'edit': True, u'view': True}, u'forms': {u'employment': {u'delete': True, u'view': True}, u'financing': {u'delete': True, u'view': True}, u'service': {u'delete': True, u'view': True}}, u'people': {u'add': True, u'delete': True, u'edit': True, u'sort-riders': True, u'sort-staff': True, u'view': True}, u'settings': {u'edit': True, u'view': True}} From this it is evident that you have True value only, not False. What is use case of these values? Why for example you are not using set: {u'add',u'delete', u'edit', u'sort-riders',...} ? from pprint import pprint def alternative(yourdict): for key in yourdict: if yourdict[key] is True: yield set(yourdict.keys()) break else: yield tuple((key,tup) for tup in alternative(yourdict[key])) my_variable = {u'forms': {u'financing': {u'view': True, u'delete': True}, u'employment': {u'view': True, u'delete': True}, u'service': {u'view': True, u'delete': True}}, u'content': {u'articles': {u'edit': True, u'add': True, u'view': True, u'delete': True}, u'slideshow': {u'edit': True, u'view': True}, u'pages': {u'edit': True, u'add': True, u'view': True, u'delete': True}}, u'people': {u'edit': True, u'sort-staff': True, u'sort-riders': True, u'add': True, u'delete': True, u'view': True}, u'events': {u'edit': True, u'add': True, u'view': True, u'delete': True}, u'settings': {u'edit': True, u'view': True}} pprint(my_variable) print 50 * '-' print 'Alternative datastructure' pprint(tuple(alternative(my_variable)))
How to convert unicode objects to normal objects in Python
I currently have a deep object, and it is all unicode (sadly). I am to a point where a variable is either going to be a dict, or a bool. In this case, I do if type( my_variable ) is BooleanType: But this is not triggered because the type is actually Unicode for all values. How do I convert this unicode object to a normal object so I can correctly read the type, without destroying the data? Thanks! Here is the result of print(repr(variable)). It shows the Bools as not being unicode (unlike what I first though) but still giving me troubles. {u'forms': {u'financing': {u'view': True, u'delete': True}, u'employment': {u'view': True, u'delete': True}, u'service': {u'view': True, u'delete': True}}, u'content': {u'articles': {u'edit': True, u'add': True, u'view': True, u'delete': True}, u'slideshow': {u'edit': True, u'view': True}, u'pages': {u'edit': True, u'add': True, u'view': True, u'delete': True}}, u'people': {u'edit': True, u'sort-staff': True, u'sort-riders': True, u'add': True, u'delete': True, u'view': True}, u'events': {u'edit': True, u'add': True, u'view': True, u'delete': True}, u'settings': {u'edit': True, u'view': True}}
[ "Do not use type unless you are really really sure that you want to.\nIn this case, you don't -- especially checking for bool, given Python's flexibility for what can be considered as boolean! For instance, what if you are given None? How about an empty string? How about []?\nThe solution to this problem is the use...
[ 1, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0003520120_python_unicode.txt
Q: Set Host-header when using Python and urllib2 I'm using my own resolver and would like to use urllib2 to just connect to the IP (no resolving in urllib2) and I would like set the HTTP Host-header myself. But urllib2 is just ignoring my Host-header: txheaders = { 'User-Agent': UA, "Host: ": nohttp_url } robots = urllib2.Request("http://" + ip + "/robots.txt", txdata, txheaders) A: You have included ": " in the "Host" string. txheaders = { "User-Agent": UA, "Host": nohttp_url } robots = urllib2.Request("http://" + ip + "/robots.txt", txdata, txheaders)
Set Host-header when using Python and urllib2
I'm using my own resolver and would like to use urllib2 to just connect to the IP (no resolving in urllib2) and I would like set the HTTP Host-header myself. But urllib2 is just ignoring my Host-header: txheaders = { 'User-Agent': UA, "Host: ": nohttp_url } robots = urllib2.Request("http://" + ip + "/robots.txt", txdata, txheaders)
[ "You have included \": \" in the \"Host\" string.\ntxheaders = { \"User-Agent\": UA, \"Host\": nohttp_url }\nrobots = urllib2.Request(\"http://\" + ip + \"/robots.txt\", txdata, txheaders)\n\n" ]
[ 10 ]
[]
[]
[ "http", "python", "urllib2" ]
stackoverflow_0003520966_http_python_urllib2.txt
Q: How do I schedule a Python script to run as long as Windows XP is running? I wrote a temperature logger Python script and entered it as a scheduled task in Windows XP. It has the following command line: C:\Python26\pythonw.exe "C:\path\to\templogger.py" It writes data to a file in local public folder (e.g. fully accessible by all who login locally). So far, I was able to achieve this objective: 1. Get the task to run even before anyone logs in (i.e. at the "Press Ctrl+Alt+Del" screen) But I'm having problems with these: 1. When I log in, log out, then log back in, the scheduled task is no longer active. I can no longer see it in the Task Manager's Processes tab. I suspect it closes when I log out. 2. I tried to set the task's "Run As..." property to DOMAIN\my-username and also tried SYSTEM, but problem #1 above still persists. SUMMARY: I want my program to be running as long as Windows is active. It should not matter whether anyone has logged in or out. P.S. I asked the same question in Super User, and I was advised to write it as a service, which I know nothing about (except starting and stopping them). I hope to reach a wider audience here at SO. A: Is it possible to run a Python script as a service in Windows? If possible, how? http://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html A: Your scenario is exactly the required use case for a service, unfortunately tasks are ill suited for what you are looking to do. That said writing services in python is not a walk in the park either, to ease the pain here is a few links I have perused in the past: http://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html http://mail.python.org/pipermail/python-win32/2008-April/007298.html I used the second link in particular to create a windows scripts that was then compiled to a executable service with py2exe and installed with SrvAny.
How do I schedule a Python script to run as long as Windows XP is running?
I wrote a temperature logger Python script and entered it as a scheduled task in Windows XP. It has the following command line: C:\Python26\pythonw.exe "C:\path\to\templogger.py" It writes data to a file in local public folder (e.g. fully accessible by all who login locally). So far, I was able to achieve this objective: 1. Get the task to run even before anyone logs in (i.e. at the "Press Ctrl+Alt+Del" screen) But I'm having problems with these: 1. When I log in, log out, then log back in, the scheduled task is no longer active. I can no longer see it in the Task Manager's Processes tab. I suspect it closes when I log out. 2. I tried to set the task's "Run As..." property to DOMAIN\my-username and also tried SYSTEM, but problem #1 above still persists. SUMMARY: I want my program to be running as long as Windows is active. It should not matter whether anyone has logged in or out. P.S. I asked the same question in Super User, and I was advised to write it as a service, which I know nothing about (except starting and stopping them). I hope to reach a wider audience here at SO.
[ "Is it possible to run a Python script as a service in Windows? If possible, how?\nhttp://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html\n", "Your scenario is exactly the required use case for a service, unfortunately tasks are ill suited for what you are looking to do. That said writing ...
[ 3, 2 ]
[]
[]
[ "python", "scheduled_tasks", "windows_xp" ]
stackoverflow_0003520900_python_scheduled_tasks_windows_xp.txt
Q: pyGTK detect all window move events I'm trying to capture the configure-event for every window to create a windows 7-esque snap feature. I know there are solutions involving compiz-fusion, but my installation is running within vmware and doesn't have hardware acceleration to run compiz. I figured a simple python script could do what I wanted, but I can't seem to find the right place to bind the configure-event to. How/to what do you bind the configure-event callback, or is there a different event I need to watch for? I've tried binding it to the screen and the root window using get_root_window() with no luck. EDIT2 Now I can capture all events, the problem is that every event returned is of type GDK_NOTHING, so I can't tell the difference between focus events, move events, close events, etc. #!/usr/bin/python import pygtk pygtk.require('2.0') import gtk, wnck import inspect def move_event(e): print e.type, e.window print inspect.getmembers(e) return gtk.gdk.FILTER_CONTINUE def bind_win(screen, win): w = gtk.gdk.window_foreign_new(win.get_xid()) if w: w.set_events(w.get_events() | gtk.gdk.ALL_EVENTS_MASK) w.add_filter(move_event) if __name__ == "__main__": screen = wnck.screen_get_default() screen.connect("window_opened", bind_win) gtk.main() One iteration of move_event(e) while dragging a window: <enum GDK_NOTHING of type GdkEventType> <gtk.gdk.Window object at 0x7f38f72f8730 (GdkWindow at 0x196ce20)> [('copy', <built-in method copy of gtk.gdk.Event object at 0x7f3900513d00>), ('free', <built-in method free of gtk.gdk.Event object at 0x7f3900513d00>), ('get_axis', <built-in method get_axis of gtk.gdk.Event object at 0x7f3900513d00>), ('get_coords', <built-in method get_coords of gtk.gdk.Event object at 0x7f3900513d00>), ('get_root_coords', <built-in method get_root_coords of gtk.gdk.Event object at 0x7f3900513d00>), ('get_screen', <built-in method get_screen of gtk.gdk.Event object at 0x7f3900513d00>), ('get_state', <built-in method get_state of gtk.gdk.Event object at 0x7f3900513d00>), ('get_time', <built-in method get_time of gtk.gdk.Event object at 0x7f3900513d00>), ('put', <built-in method put of gtk.gdk.Event object at 0x7f3900513d00>), ('send_client_message', <built-in method send_client_message of gtk.gdk.Event object at 0x7f3900513d00>), ('send_clientmessage_toall', <built-in method send_clientmessage_toall of gtk.gdk.Event object at 0x7f3900513d00>), ('send_event', 1), ('set_screen', <built-in method set_screen of gtk.gdk.Event object at 0x7f3900513d00>), ('type', <enum GDK_NOTHING of type GdkEventType>), ('window', <gtk.gdk.Window object at 0x7f38f72f8730 (GdkWindow at 0x196ce20)>)] A: A quick search reveals this page, which, though written in C, communicates the basics pretty well (you'll have to grep it to find for "Moving Window") The configure-event is binded to your application's window. To do what you're going to want to do, you'll also have to find out the screen size, which resides in gtk.gdk.screen, documented here.
pyGTK detect all window move events
I'm trying to capture the configure-event for every window to create a windows 7-esque snap feature. I know there are solutions involving compiz-fusion, but my installation is running within vmware and doesn't have hardware acceleration to run compiz. I figured a simple python script could do what I wanted, but I can't seem to find the right place to bind the configure-event to. How/to what do you bind the configure-event callback, or is there a different event I need to watch for? I've tried binding it to the screen and the root window using get_root_window() with no luck. EDIT2 Now I can capture all events, the problem is that every event returned is of type GDK_NOTHING, so I can't tell the difference between focus events, move events, close events, etc. #!/usr/bin/python import pygtk pygtk.require('2.0') import gtk, wnck import inspect def move_event(e): print e.type, e.window print inspect.getmembers(e) return gtk.gdk.FILTER_CONTINUE def bind_win(screen, win): w = gtk.gdk.window_foreign_new(win.get_xid()) if w: w.set_events(w.get_events() | gtk.gdk.ALL_EVENTS_MASK) w.add_filter(move_event) if __name__ == "__main__": screen = wnck.screen_get_default() screen.connect("window_opened", bind_win) gtk.main() One iteration of move_event(e) while dragging a window: <enum GDK_NOTHING of type GdkEventType> <gtk.gdk.Window object at 0x7f38f72f8730 (GdkWindow at 0x196ce20)> [('copy', <built-in method copy of gtk.gdk.Event object at 0x7f3900513d00>), ('free', <built-in method free of gtk.gdk.Event object at 0x7f3900513d00>), ('get_axis', <built-in method get_axis of gtk.gdk.Event object at 0x7f3900513d00>), ('get_coords', <built-in method get_coords of gtk.gdk.Event object at 0x7f3900513d00>), ('get_root_coords', <built-in method get_root_coords of gtk.gdk.Event object at 0x7f3900513d00>), ('get_screen', <built-in method get_screen of gtk.gdk.Event object at 0x7f3900513d00>), ('get_state', <built-in method get_state of gtk.gdk.Event object at 0x7f3900513d00>), ('get_time', <built-in method get_time of gtk.gdk.Event object at 0x7f3900513d00>), ('put', <built-in method put of gtk.gdk.Event object at 0x7f3900513d00>), ('send_client_message', <built-in method send_client_message of gtk.gdk.Event object at 0x7f3900513d00>), ('send_clientmessage_toall', <built-in method send_clientmessage_toall of gtk.gdk.Event object at 0x7f3900513d00>), ('send_event', 1), ('set_screen', <built-in method set_screen of gtk.gdk.Event object at 0x7f3900513d00>), ('type', <enum GDK_NOTHING of type GdkEventType>), ('window', <gtk.gdk.Window object at 0x7f38f72f8730 (GdkWindow at 0x196ce20)>)]
[ "A quick search reveals this page, which, though written in C, communicates the basics pretty well (you'll have to grep it to find for \"Moving Window\")\nThe configure-event is binded to your application's window. \nTo do what you're going to want to do, you'll also have to find out the screen size, which resides ...
[ 1 ]
[]
[]
[ "events", "linux", "pygtk", "python" ]
stackoverflow_0003128536_events_linux_pygtk_python.txt
Q: Class menu in Tkinter Gui I'm working on a Gui and I'd like to know if it is possible to make the menu property of a window a separate class on my script for a clearer and more enhancement prone code. my code currently is : class Application(Frame): """ main window application """ def __init__(self, boss = None): (...) self.menu = Menu(self) self.master.config(menu = self.menu) self.select = Menu(self.menu) self.menu.add_cascade(label = 'Select', menu = self.select) self.select.add_command(label = 'Select all', command = self.select_all) ... And I would prefer something like : class MenuBar: # all the content of the menu here class Application(Frame): (...) self.menu = MenuBar(self) ? rgds, A: Yes, it's possible: import tkinter as tk # import Tkinter as tk # if using python 2 import sys class MenuBar(tk.Menu): def __init__(self, parent): tk.Menu.__init__(self, parent) fileMenu = tk.Menu(self, tearoff=False) self.add_cascade(label="File",underline=0, menu=fileMenu) fileMenu.add_command(label="Exit", underline=1, command=self.quit) def quit(self): sys.exit(0) class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) menubar = MenuBar(self) self.config(menu=menubar) if __name__ == "__main__": app=App() app.mainloop()
Class menu in Tkinter Gui
I'm working on a Gui and I'd like to know if it is possible to make the menu property of a window a separate class on my script for a clearer and more enhancement prone code. my code currently is : class Application(Frame): """ main window application """ def __init__(self, boss = None): (...) self.menu = Menu(self) self.master.config(menu = self.menu) self.select = Menu(self.menu) self.menu.add_cascade(label = 'Select', menu = self.select) self.select.add_command(label = 'Select all', command = self.select_all) ... And I would prefer something like : class MenuBar: # all the content of the menu here class Application(Frame): (...) self.menu = MenuBar(self) ? rgds,
[ "Yes, it's possible:\nimport tkinter as tk\n# import Tkinter as tk # if using python 2\nimport sys\n\nclass MenuBar(tk.Menu):\n def __init__(self, parent):\n tk.Menu.__init__(self, parent)\n\n fileMenu = tk.Menu(self, tearoff=False)\n self.add_cascade(label=\"File\",underline=0, menu=fileMe...
[ 14 ]
[]
[]
[ "class", "menu", "python", "tkinter", "user_interface" ]
stackoverflow_0003520494_class_menu_python_tkinter_user_interface.txt
Q: Does Python support something like literal objects? In Scala I could define an abstract class and implement it with an object: abstrac class Base { def doSomething(x: Int): Int } object MySingletonAndLiteralObject extends Base { override def doSomething(x: Int) = x*x } My concrete example in Python: class Book(Resource): path = "/book/{id}" def get(request): return aBook Inheritance wouldn't make sense here, since no two classes could have the same path. And only one instance is needed, so that the class doesn't act as a blueprint for objects. With other words: no class is needed here for a Resource (Book in my example), but a base class is needed to provide common functionality. I'd like to have: object Book(Resource): path = "/book/{id}" def get(request): return aBook What would be the Python 3 way to do it? A: Use a decorator to convert the inherited class to an object at creation time I believe that the concept of such an object is not a typical way of coding in Python, but if you must then the decorator class_to_object below for immediate initialisation will do the trick. Note that any parameters for object initialisation must be passed through the decorator: def class_to_object(*args): def c2obj(cls): return cls(*args) return c2obj using this decorator we get >>> @class_to_object(42) ... class K(object): ... def __init__(self, value): ... self.value = value ... >>> K <__main__.K object at 0x38f510> >>> K.value 42 The end result is that you have an object K similar to your scala object, and there is no class in the namespace to initialise other objects from. Note: To be pedantic, the class of the object K can be retrieved as K.__class__ and hence other objects may be initialised if somebody really want to. In Python there is almost always a way around things if you really want. A: Use an abc (Abstract Base Class): import abc class Resource( metaclass=abc.ABCMeta ): @abc.abstractproperty def path( self ): ... return p Then anything inheriting from Resource is required to implement path. Notice that path is actually implemented in the ABC; you can access this implementation with super. A: If you can instantiate Resource directly you just do that and stick the path and get method on directly. from types import MethodType book = Resource() def get(self): return aBook book.get = MethodType(get, book) book.path = path This assumes though that path and get are not used in the __init__ method of Resource and that path is not used by any class methods which it shouldn't be given your concerns. If your primary concern is making sure that nothing inherits from the Book non-class, then you could just use this metaclass class Terminal(type): classes = [] def __new__(meta, classname, bases, classdict): if [cls for cls in meta.classes if cls in bases]: raise TypeError("Can't Touch This") cls = super(Terminal, meta).__new__(meta, classname, bases, classdict) meta.classes.append(cls) return cls class Book(object): __metaclass__ = Terminal class PaperBackBook(Book): pass You might want to replace the exception thrown with something more appropriate. This would really only make sense if you find yourself instantiating a lot of one offs. And if that's not good enough for you and you're using CPython, you could always try some of this hackery: class Resource(object): def __init__(self, value, location=1): self.value = value self.location = location with Object('book', Resource, 1, location=2): path = '/books/{id}' def get(self): aBook = 'abook' return aBook print book.path print book.get() made possible by my very first context manager. class Object(object): def __init__(self, name, cls, *args, **kwargs): self.cls = cls self.name = name self.args = args self.kwargs = kwargs def __enter__(self): self.f_locals = copy.copy(sys._getframe(1).f_locals) def __exit__(self, exc_type, exc_val, exc_tb): class cls(self.cls): pass f_locals = sys._getframe(1).f_locals new_items = [item for item in f_locals if item not in self.f_locals] for item in new_items: setattr(cls, item, f_locals[item]) del f_locals[item] # Keyser Soze the new names from the enclosing namespace obj = cls(*self.args, **self.kwargs) f_locals[self.name] = obj # and insert the new object Of course I encourage you to use one of my above two solutions or Katrielalex's suggestion of ABC's.
Does Python support something like literal objects?
In Scala I could define an abstract class and implement it with an object: abstrac class Base { def doSomething(x: Int): Int } object MySingletonAndLiteralObject extends Base { override def doSomething(x: Int) = x*x } My concrete example in Python: class Book(Resource): path = "/book/{id}" def get(request): return aBook Inheritance wouldn't make sense here, since no two classes could have the same path. And only one instance is needed, so that the class doesn't act as a blueprint for objects. With other words: no class is needed here for a Resource (Book in my example), but a base class is needed to provide common functionality. I'd like to have: object Book(Resource): path = "/book/{id}" def get(request): return aBook What would be the Python 3 way to do it?
[ "Use a decorator to convert the inherited class to an object at creation time\nI believe that the concept of such an object is not a typical way of coding in Python, but if you must then the decorator class_to_object below for immediate initialisation will do the trick. Note that any parameters for object initialis...
[ 7, 2, 1 ]
[]
[]
[ "object_literal", "oop", "python", "scala", "singleton" ]
stackoverflow_0003520052_object_literal_oop_python_scala_singleton.txt
Q: Retrieving stdout from subprocess in Windows I can call FFmpeg with subprocess.Popen and retrieve the data I need, as it occurs (to get progress), but only in console. I've looked around and seen that you can't get the data "live" when running with pythonw. Yet, waiting until the process finishes to retrieve the data is moot, since I'm trying to wrap a PyQT GUI around FFmpeg so I can have pretty progress bars and whatnot. So the question is, can you retrieve "live" data from a subprocess call when using pythonw? I haven't tried simply compiling the application with py2exe yet as a windows application, would that fix the problem? A: process = subprocess.Popen(your_cmd, shell=true, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) count=0 while True: buff = process.stdout.readline() if buff == '': count += 1 if buff == '' and process.poll() != None: break sys.stdout.write(buff) process.wait() A: In your call to subprocess.Popen, use stdout=subprocess.PIPE. Then you will be able to read from the process's .stdout.
Retrieving stdout from subprocess in Windows
I can call FFmpeg with subprocess.Popen and retrieve the data I need, as it occurs (to get progress), but only in console. I've looked around and seen that you can't get the data "live" when running with pythonw. Yet, waiting until the process finishes to retrieve the data is moot, since I'm trying to wrap a PyQT GUI around FFmpeg so I can have pretty progress bars and whatnot. So the question is, can you retrieve "live" data from a subprocess call when using pythonw? I haven't tried simply compiling the application with py2exe yet as a windows application, would that fix the problem?
[ "process = subprocess.Popen(your_cmd, shell=true, stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n\ncount=0\nwhile True:\n buff = process.stdout.readline()\n\n if buff == '':\n count += 1\n\n if buff == '' and process.poll() != None:\n break\n\n sys.stdout.wr...
[ 4, 0 ]
[]
[]
[ "ffmpeg", "pyqt", "python", "subprocess", "windows" ]
stackoverflow_0003521887_ffmpeg_pyqt_python_subprocess_windows.txt
Q: Django mod-python error Can someone please tell what this strange error is Mod_python error: "PythonHandler django.core.handlers.modpython" Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 287, in HandlerDispatch log=debug) File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 464, in import_module module = imp.load_module(mname, f, p, d) File "/project/django/django/core/handlers/modpython.py", line 4, in ? from django import http File "/project/django/django/http/__init__.py", line 3, in ? from Cookie import SimpleCookie, CookieError ImportError: No module named Cookie Edit: Python Python 2.4.3 (#1, Jan 14 2008, 18:32:40) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from Cookie import SimpleCookie, CookieError >>> from http.Cookie import SimpleCookie, CookieError Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: No module named http.Cookie >>> import Cookie >>> import http.Cookie Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: No module named http.Cookie >>> import http.Cookie A: That you're missing the Cookie package (which is not part of Django), but it should be Builtin. If you're using Python 3 please note that Cookie has been renamed to http.cookies, and that Django is incompatible with Python not 2.x. That is what you're missing: http://docs.python.org/library/cookie.html. Edit I see you're running python 2.4. Consider switch to python 2.6 or 2.7, and check the presence of /usr/lib/python2.4/Cookie.py Solution The path was missing, so adding sys.path.append('/usr/lib/python2.4/') solves the issue.
Django mod-python error
Can someone please tell what this strange error is Mod_python error: "PythonHandler django.core.handlers.modpython" Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 287, in HandlerDispatch log=debug) File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 464, in import_module module = imp.load_module(mname, f, p, d) File "/project/django/django/core/handlers/modpython.py", line 4, in ? from django import http File "/project/django/django/http/__init__.py", line 3, in ? from Cookie import SimpleCookie, CookieError ImportError: No module named Cookie Edit: Python Python 2.4.3 (#1, Jan 14 2008, 18:32:40) [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from Cookie import SimpleCookie, CookieError >>> from http.Cookie import SimpleCookie, CookieError Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: No module named http.Cookie >>> import Cookie >>> import http.Cookie Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: No module named http.Cookie >>> import http.Cookie
[ "That you're missing the Cookie package (which is not part of Django), but it should be Builtin. \nIf you're using Python 3 please note that Cookie has been renamed to http.cookies, and that Django is incompatible with Python not 2.x.\nThat is what you're missing: http://docs.python.org/library/cookie.html.\nEdit\n...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003522029_django_python.txt
Q: html to text conversion using python language I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad. Update: html2text looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean. A: you would need to use urllib2 python library to get the html from the website and then parse through the html to grab the text that you want. Use BeautifulSoup to parse through the html import BeautifulSoup resp = urllib2.urlopen("http://stackoverflow.com") rawhtml = resp.read() #parse through html to get text soup=BeautifulSoup(rawhtml) A: I don't "copy-paste from browser" is a well-defined operation. For instance, what would happen if the entire page were covered with a transparent floating div? What if it had tables? What about dynamic content? BeautifulSoup is a powerful parser; you just need to know how to use it (it is easy, for instance, to remove the script tags from the page). Fortunately, it has a lot of documentation. You can use xml.sax.utils.unescape to unescape HTML entities.
html to text conversion using python language
I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad. Update: html2text looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.
[ "you would need to use urllib2 python library to get the html from the website and then parse through the html to grab the text that you want. \nUse BeautifulSoup to parse through the html\nimport BeautifulSoup\nresp = urllib2.urlopen(\"http://stackoverflow.com\")\nrawhtml = resp.read()\n#parse through html to get ...
[ 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003521999_python.txt
Q: Django Template Syntax Error in Google App Engine I tried launching my Google App Engine app on localhost, and got a Django error I am stuck on. "TemplateSyntaxError: Template 'base/_base.html' cannot be extended, because it doesn't exist" I put the templates in a /templates, and then _base.html & index.html in /templates/base . Thanks! Emile @ proudn00b.com The Error: Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 511, in __call__ handler.get(*groups) File "/Users/emilepetrone/code/thebuswheel/main.py", line 65, in get outstr = template.render(temp, { 'path': path }) …. ….. File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django/django/template/loader_tags.py", line 58, in get_parent raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent TemplateSyntaxError: Template 'base/_base.html' cannot be extended, because it doesn't exist Referring to : def get(self): path = self.request.path temp = os.path.join( os.path.dirname(__file__), 'templates' + path) if not os.path.isfile(temp): temp = os.path.join( os.path.dirname(__file__), 'templates/base/index.html') outstr = template.render(temp, { 'path': path }) self.response.out.write(outstr) A: Another thing you can double check is to make sure one of the paths in the TEMPLATE_DIRS setting points to the root directory for your templates. Also make sure it's a full absolute path in the setting, not relative to the project. A: I think you need to look in your templates. The important part of the traceback is at the end: Template 'base/_base.html' cannot be extended, because it doesn't exist Do you have a template named 'base/_base.html'? If not, find what other template file is trying to extend it. A: Solution from @jps rename base/_base.html to just base.html, no subdir. Update index.html with new path.
Django Template Syntax Error in Google App Engine
I tried launching my Google App Engine app on localhost, and got a Django error I am stuck on. "TemplateSyntaxError: Template 'base/_base.html' cannot be extended, because it doesn't exist" I put the templates in a /templates, and then _base.html & index.html in /templates/base . Thanks! Emile @ proudn00b.com The Error: Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 511, in __call__ handler.get(*groups) File "/Users/emilepetrone/code/thebuswheel/main.py", line 65, in get outstr = template.render(temp, { 'path': path }) …. ….. File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django/django/template/loader_tags.py", line 58, in get_parent raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent TemplateSyntaxError: Template 'base/_base.html' cannot be extended, because it doesn't exist Referring to : def get(self): path = self.request.path temp = os.path.join( os.path.dirname(__file__), 'templates' + path) if not os.path.isfile(temp): temp = os.path.join( os.path.dirname(__file__), 'templates/base/index.html') outstr = template.render(temp, { 'path': path }) self.response.out.write(outstr)
[ "Another thing you can double check is to make sure one of the paths in the TEMPLATE_DIRS setting points to the root directory for your templates. \nAlso make sure it's a full absolute path in the setting, not relative to the project.\n", "I think you need to look in your templates. The important part of the tra...
[ 1, 0, 0 ]
[]
[]
[ "django_templates", "google_app_engine", "python" ]
stackoverflow_0003516918_django_templates_google_app_engine_python.txt
Q: Loading mako templates from files I'm new to python and currently trying to use mako templating. I want to be able to take an html file and add a template to it from another html file. Let's say I got this index.html file: <html> <head> <title>Hello</title> </head> <body> <p>Hello, ${name}!</p> </body> </html> and this name.html file: world (yes, it just has the word world inside). I want the ${name} in index.html to be replaced with the content of the name.html file. I've been able to do this without the name.html file, by stating in the render method what name is, using the following code: @route(':filename') def static_file(filename): mylookup = TemplateLookup(directories=['html']) mytemplate = mylookup.get_template('hello/index.html') return mytemplate.render(name='world') This is obviously not useful for larger pieces of text. Now all I want is to simply load the text from name.html, but haven't yet found a way to do this. What should I try? A: return mytemplate.render(name=open(<path-to-file>).read()) A: Thanks for the replies. The idea is to use the mako framework since it does things like cache and check if the file has been updated... this code seems to eventually work: @route(':filename') def static_file(filename): mylookup = TemplateLookup(directories=['.']) mytemplate = mylookup.get_template('index.html') temp = mylookup.get_template('name.html').render() return mytemplate.render(name=temp) Thanks again. A: Did I understand you correctly that all you want is read the content from a file? If you want to read the complete content use something like this (Python >= 2.5): from __future__ import with_statement with open(my_file_name, 'r') as fp: content = fp.read() Note: The from __future__ line has to be the first line in your .py file (or right after the content encoding specification that can be placed in the first line) Or the old approach: fp = open(my_file_name, 'r') try: content = fp.read() finally: fp.close() If your file contains non-ascii characters, you should also take a look at the codecs page :-) Then, based on your example, the last section could look like this: from __future__ import with_statement @route(':filename') def static_file(filename): mylookup = TemplateLookup(directories=['html']) mytemplate = mylookup.get_template('hello/index.html') content = '' with open('name.html', 'r') as fp: content = fp.read() return mytemplate.render(name=content) You can find more details about the file object in the official documentation :-) There is also a shortcut version: content = open('name.html').read() But I personally prefer the long version with the explicit closing :-)
Loading mako templates from files
I'm new to python and currently trying to use mako templating. I want to be able to take an html file and add a template to it from another html file. Let's say I got this index.html file: <html> <head> <title>Hello</title> </head> <body> <p>Hello, ${name}!</p> </body> </html> and this name.html file: world (yes, it just has the word world inside). I want the ${name} in index.html to be replaced with the content of the name.html file. I've been able to do this without the name.html file, by stating in the render method what name is, using the following code: @route(':filename') def static_file(filename): mylookup = TemplateLookup(directories=['html']) mytemplate = mylookup.get_template('hello/index.html') return mytemplate.render(name='world') This is obviously not useful for larger pieces of text. Now all I want is to simply load the text from name.html, but haven't yet found a way to do this. What should I try?
[ "return mytemplate.render(name=open(<path-to-file>).read())\n\n", "Thanks for the replies.\nThe idea is to use the mako framework since it does things like cache and check if the file has been updated...\nthis code seems to eventually work:\n@route(':filename')\ndef static_file(filename): \n mylookup = Temp...
[ 2, 2, 1 ]
[]
[]
[ "mako", "python", "templates" ]
stackoverflow_0003521629_mako_python_templates.txt
Q: Removing broken tags and poorly formatted html from some text i have a huge database of scraped forum posts that i am inserting into a website. however alot of people try to use html in their forum posts and often times do it wrong. because of this, there are always stray <strike> <b> </strike> </div> </b> tags in the posts which will end up messing up the webpage format when i add say 15 forum posts. for now i have just been appending all possible end tags to the post just so that it might catch any open tag...is there a better way to do this short of parsing through the text and trying to manually remove each open tag. for loooooong forum posts this is an expensive transaction for a web app. A: Have a look at HTML Tidy There is a also a Python wrapper lib: µTidylib Alternatively there is HTML Purifier A: Beautiful Soup does a decent job at HTML cleanup. A: Look at lxml also.
Removing broken tags and poorly formatted html from some text
i have a huge database of scraped forum posts that i am inserting into a website. however alot of people try to use html in their forum posts and often times do it wrong. because of this, there are always stray <strike> <b> </strike> </div> </b> tags in the posts which will end up messing up the webpage format when i add say 15 forum posts. for now i have just been appending all possible end tags to the post just so that it might catch any open tag...is there a better way to do this short of parsing through the text and trying to manually remove each open tag. for loooooong forum posts this is an expensive transaction for a web app.
[ "Have a look at HTML Tidy\nThere is a also a Python wrapper lib: µTidylib\nAlternatively there is HTML Purifier\n", "Beautiful Soup does a decent job at HTML cleanup.\n", "Look at lxml also.\n" ]
[ 1, 0, 0 ]
[]
[]
[ "html_parsing", "python" ]
stackoverflow_0003522058_html_parsing_python.txt
Q: Python Server Help I have written a small HTTP server and everything is working fine locally, but I am not able to connect to the server from any other computer, including other computers on the network. I'm not sure if it is a server problem, or if I just need to make some adjustments to Windows. I turned the firewall off, so that can't be the probelm. I am using Python 2.6 on Windows 7. A: Without any code sample I can only assume that your server is listening on some private interface like localhost/127.0.0.1 and not something that is connected to the rest of your network. A: Some things to check: Can you connect to the server via your machine's IP instead of localhost? I.e. if your machine is 1.2.3.4 in the network and the server is listening on port 8080, can you see it by opening a browser to http://1.2.3.4:8080 on the same machine? Can you do (1) from another machine? (just a sanity check...) Do other servers work throughout the network? I.e. if you run a simple FTP server (like Filezilla server) on the machine, can you FTP to it from other machines? Can you ping one machine from another? Do you still have firewalls running? (i.e. default Windows firewall)
Python Server Help
I have written a small HTTP server and everything is working fine locally, but I am not able to connect to the server from any other computer, including other computers on the network. I'm not sure if it is a server problem, or if I just need to make some adjustments to Windows. I turned the firewall off, so that can't be the probelm. I am using Python 2.6 on Windows 7.
[ "Without any code sample I can only assume that your server is listening on some private interface like localhost/127.0.0.1 and not something that is connected to the rest of your network.\n", "Some things to check:\n\nCan you connect to the server via your machine's IP instead of localhost? I.e. if your machine ...
[ 2, 0 ]
[]
[]
[ "http", "python", "windows" ]
stackoverflow_0003522641_http_python_windows.txt
Q: How to get the name of dir from where a python script is called (not exaclty where it ran) I have a Python script, named script.py. It's located on ~/scripts/script.py. I have an alias in ~/.bash_aliases: alias script='python ~/scripts/script.py' I have some directories in a checked out repository, for example: ~/repository/project_dir/module_name/ I run on my terminal, inside ~/repository/project_dir/module_name/, the script alias I created. This script has a print statement printing the directory from where the script.py was run, but I want it to print from where it was called. How do I do it? (Now, I'm using os.path.abspath(sys.argv[0]) and it prints ~/scripts/script.py instead of ~/repository/project_dir/module_name/) A: import os print os.getcwd() For more details, check out the python docs.
How to get the name of dir from where a python script is called (not exaclty where it ran)
I have a Python script, named script.py. It's located on ~/scripts/script.py. I have an alias in ~/.bash_aliases: alias script='python ~/scripts/script.py' I have some directories in a checked out repository, for example: ~/repository/project_dir/module_name/ I run on my terminal, inside ~/repository/project_dir/module_name/, the script alias I created. This script has a print statement printing the directory from where the script.py was run, but I want it to print from where it was called. How do I do it? (Now, I'm using os.path.abspath(sys.argv[0]) and it prints ~/scripts/script.py instead of ~/repository/project_dir/module_name/)
[ "import os\nprint os.getcwd()\n\nFor more details, check out the python docs.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003522785_python.txt
Q: Rotating images using PHP and jQuery the fast way I wrote a python script that rotates an image 90 degrees. I am including the python code in case you want to see it; #! /usr/bin/python # This Python file uses the following encoding: utf-8 #argv[1] needs to be send formatted meaning spaces and paranthesis ARE problems __author__="john" __date__ ="$Aug 17, 2010 1:48:36 PM$" server_directory="some_directory" import os import os.path import sys import Image #for turkish characters def tr(utf): return utf.decode('utf-8') img_directory=sys.argv[1] img_directory_orig=img_directory.replace("\ ", " ") file_url_and_name=server_directory+img_directory_orig im = Image.open(file_url_and_name) im1=im.rotate(270) out=file(file_url_and_name,"w") im1.save(out,"JPEG") out.close() Simple enough. So what I used to do is simply when a link is clicked a sample link is as below; echo '<div style="text-align: center ;margin-left: auto ; margin-right: auto ;"><a class="button" href="fotograf.php?open='.$going_to_open_dir.'&rotate=temp/'."m_".$fake_going_to_open_dir."_".$fake_entry.'&num=foto'.$a1.'" onclick="this.blur();"><span>90&deg; turn</span></a></div>'; So far so good. Oh and let me add the php code calling my nice little python app; if(isset($_GET["rotate"])) { exec("python rotate_image.py ".$_GET["rotate"]); header("location: fotograf.php?open=".$_GET['open']."&num=".$_GET['num']."#".$_GET['num']); } So my problem is: Even though my system works its just too slow. Especially when there is about 600 pictures waiting to be loaded each time a picture turns. My question is there a way to speed it up using jQuery(Ajax)? Basically what I'm trying to do is : I am simply trying to rotate one image among 600 images in a web page and saving the rotated version on the server without the need of reloading the whole page. A: If you are happy to do this just in the browser, the tricks in this article will let you rotate any html content, including image tags. -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); A: You seem to be creating the rotated version each time it's requested from the PHP script. Check if it already exists and only rotate if not. In other words, in your PHP script, check if you already generated the rotated file before. If yes, don't run the python script again, just redirect to the rotated file. Example of what you have now - before anything is run: somefile.jpg request.php?rotate=somefile.jpg: rotate? yes -> exec python script after the script finishes (it doesn't matter what exactly the filenames are): somefile.jpg somefile_rotated.jpg So, at this point, you don't need to exec the python script again when requesting somefile.jpg, but you still do: request.php?rotate=somefile.jpg: rotate? yes -> exec python script // even though you already have the output file What you could do: request.php?rotate=somefile.jpg: rotate? yes did we rotate the file already? (=is there a rotated version on our server?) -> yes, redirect to it -> no, exec python script, then redirect to the rotated file A: What in particular is too slow? There are lots of ways to speed this up: Cache the rotated images. This is the obvious one. Load the rotated images when the page is loaded, set to invisible. This will cause the browser to cache them AJAX a request for the images.
Rotating images using PHP and jQuery the fast way
I wrote a python script that rotates an image 90 degrees. I am including the python code in case you want to see it; #! /usr/bin/python # This Python file uses the following encoding: utf-8 #argv[1] needs to be send formatted meaning spaces and paranthesis ARE problems __author__="john" __date__ ="$Aug 17, 2010 1:48:36 PM$" server_directory="some_directory" import os import os.path import sys import Image #for turkish characters def tr(utf): return utf.decode('utf-8') img_directory=sys.argv[1] img_directory_orig=img_directory.replace("\ ", " ") file_url_and_name=server_directory+img_directory_orig im = Image.open(file_url_and_name) im1=im.rotate(270) out=file(file_url_and_name,"w") im1.save(out,"JPEG") out.close() Simple enough. So what I used to do is simply when a link is clicked a sample link is as below; echo '<div style="text-align: center ;margin-left: auto ; margin-right: auto ;"><a class="button" href="fotograf.php?open='.$going_to_open_dir.'&rotate=temp/'."m_".$fake_going_to_open_dir."_".$fake_entry.'&num=foto'.$a1.'" onclick="this.blur();"><span>90&deg; turn</span></a></div>'; So far so good. Oh and let me add the php code calling my nice little python app; if(isset($_GET["rotate"])) { exec("python rotate_image.py ".$_GET["rotate"]); header("location: fotograf.php?open=".$_GET['open']."&num=".$_GET['num']."#".$_GET['num']); } So my problem is: Even though my system works its just too slow. Especially when there is about 600 pictures waiting to be loaded each time a picture turns. My question is there a way to speed it up using jQuery(Ajax)? Basically what I'm trying to do is : I am simply trying to rotate one image among 600 images in a web page and saving the rotated version on the server without the need of reloading the whole page.
[ "If you are happy to do this just in the browser, the tricks in this article will let you rotate any html content, including image tags.\n-webkit-transform: rotate(-90deg); \n-moz-transform: rotate(-90deg); \nfilter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);\n\n", "You seem to be creating the rota...
[ 1, 0, 0 ]
[]
[]
[ "image", "jquery", "php", "python", "rotation" ]
stackoverflow_0003522739_image_jquery_php_python_rotation.txt
Q: Python 2 or Python 3 as the student's first language Which is more suited as the platform for a first course in computing: Python 2 or Python 3? Reason for asking your opinion: Python 2 is used in the vast majority of installations worlwide, but Python 3 is the coming thing. A: Teach them both (imho). Teach the Python 2 (in the most pythonic way) and than present your students the 2to3 changes, and their meaning (print "string" => print("string") why?) By the way, if you use 2.7 http://docs.python.org/dev/library/stdtypes.html#memoryview is an interesting new feature! A: I would say that it depends on your curriculum. If you are going to be using/showing some open source libraries, you may have issues with some of them working on 3, so in that case go with 2. If you're just showing the language itself and having your students write everything from scratch without the use of any external libraries, I would say go with 3. A: Frankly, I think you have a great opportunity to teach your students a valuable lesson: keeping their skills up-to-date while daily dealing with "older" code. This is a simple reality in life they'll have to grasp if they want to be successful programmers (heck, it's likely true for most jobs). Here's how I would approach this: teach them 2.x as the primary language of the course. The majority of Python libraries will not be compatible with 3.x and the programming concepts aren't terribly different between the two major versions. During the course, however, give them assignments which require them to investigate Python 3, learning what's different and why. Take a little time to teach them about migration tools and some of the basic concepts for updating an older code base. For an entry-level class, you might also consider giving them a basic, 2.5 program, and have them manually update it to 3.1. A: Python 2. Unfortunately library support for python 3 is dismal. A: For a student, my recomendation is python 2.x, because older it is, easier you find code exapmles and usage of pythonic functions. If you choose to study python 3, you may have problem finding code examples and help. Also there is much more python 2.x expert than 3.0. A: I would say to teach Python 2.*, as while Python 3 is the new hotness, there are very few supported libraries yet, and the vast majority of resources on the web are for older Python versions. A: id say python 2, python 2 has been around for a while and is very mature, with a lot of libraries and modules and major frameworks available for it. Python 3 is very new, and doesnt have many libraries yet. I guess this will be the scenario for a couple of years.
Python 2 or Python 3 as the student's first language
Which is more suited as the platform for a first course in computing: Python 2 or Python 3? Reason for asking your opinion: Python 2 is used in the vast majority of installations worlwide, but Python 3 is the coming thing.
[ "Teach them both (imho).\nTeach the Python 2 (in the most pythonic way) and than present your students the 2to3 changes, and their meaning (print \"string\" => print(\"string\") why?)\nBy the way, if you use 2.7 http://docs.python.org/dev/library/stdtypes.html#memoryview is an interesting new feature!\n", "I woul...
[ 6, 4, 3, 0, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003522380_python_python_3.x.txt
Q: Problem with pyflakes in emacs on Windows I followed this link here to try and set up emacs for python dev on windows. Although everything seems fine, pyflakes is creating problems and not giving me the syntax checking. Everytime I open a '.py' file, I get the error "Failed to launch syntax check process 'pyflakes' with args 'foo.py': searching for program: No such file or directory pyflakes" Could anyone please help me with this? Update: Here is my .emacs ;; Abhi's c:\.emacs file (add-to-list 'load-path "C:/emacs/colors/") (require 'color-theme) (eval-after-load "color-theme" '(progn (color-theme-initialize) (color-theme-charcoal-black))) (set-default-font "-outline-Monaco-normal-r-normal-normal-13-97-96-96-c-*-iso8859-1") ;Mappings to zoom in and out (defun sacha/increase-font-size () (interactive) (set-face-attribute 'default (selected-frame) :height (ceiling (* 1.10 (face-attribute 'default :height))))) (defun sacha/decrease-font-size () (interactive) (set-face-attribute 'default nil :height (floor (* 0.9 (face-attribute 'default :height))))) (global-set-key (kbd "C-+") 'sacha/increase-font-size) (global-set-key (kbd "C--") 'sacha/decrease-font-size) ;muse mode mappings (add-to-list 'load-path "C:/emacs/Muse/muse-latest/lisp/") (require 'muse-mode) (require 'muse-latex) (require 'muse-book) (require 'muse-html) (require 'muse-colors) ;To do list mode config (add-to-list 'load-path "C:/emacs/lisp/") (autoload 'todo-list-mode "todo-list-mode") ;load when needed ;a simple function that opens the file, ;and switches to todo-list-mode. (defun open-todo-list () (interactive) (find-file "D:/AbhisLife/Tasks/TODO") (todo-list-mode)) ;then bind to control-f12 so i can call it with one keystroke ;this works well for me because i also bind calendar to f12 (global-set-key [C-f12] 'open-todo-list) ;Python development (require 'smart-operator) (add-to-list 'load-path "~/.emacs.d/") (require 'yasnippet) (yas/initialize) (yas/load-directory "~/.emacs.d/snippets/") (require 'auto-complete) (global-auto-complete-mode t) ;(require 'init-auto-complete) (load-library "init_python") And here is my init_python.el (autoload 'python-mode "python-mode" "Python Mode." t) (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode)) (add-to-list 'interpreter-mode-alist '("python" . python-mode)) (require 'python-mode) (add-hook 'python-mode-hook (lambda () (set-variable 'py-indent-offset 4) ;(set-variable 'py-smart-indentation nil) (set-variable 'indent-tabs-mode nil) (define-key py-mode-map (kbd "RET") 'newline-and-indent) ;(define-key py-mode-map [tab] 'yas/expand) ;(setq yas/after-exit-snippet-hook 'indent-according-to-mode) (smart-operator-mode-on) )) ;; pymacs (autoload 'pymacs-apply "pymacs") (autoload 'pymacs-call "pymacs") (autoload 'pymacs-eval "pymacs" nil t) (autoload 'pymacs-exec "pymacs" nil t) (autoload 'pymacs-load "pymacs" nil t) ;(eval-after-load "pymacs" ; (add-to-list 'pymacs-load-path "C:/Python26/MyDownloads/Pymacs/")) (pymacs-load "ropemacs" "rope-") (setq ropemacs-enable-autoimport t) ;(setq yas/trigger-key (kbd "C-c <kp-multiply>")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Auto-completion ;;; Integrates: ;;; 1) Rope ;;; 2) Yasnippet ;;; all with AutoComplete.el ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun prefix-list-elements (list prefix) (let (value) (nreverse (dolist (element list value) (setq value (cons (format "%s%s" prefix element) value)))))) (defvar ac-source-rope '((candidates . (lambda () (prefix-list-elements (rope-completions) ac-target)))) "Source for Rope") (defun ac-python-find () "Python `ac-find-function'." (require 'thingatpt) (let ((symbol (car-safe (bounds-of-thing-at-point 'symbol)))) (if (null symbol) (if (string= "." (buffer-substring (- (point) 1) (point))) (point) nil) symbol))) (defun ac-python-candidate () "Python `ac-candidates-function'" (let (candidates) (dolist (source ac-sources) (if (symbolp source) (setq source (symbol-value source))) (let* ((ac-limit (or (cdr-safe (assq 'limit source)) ac-limit)) (requires (cdr-safe (assq 'requires source))) cand) (if (or (null requires) (>= (length ac-target) requires)) (setq cand (delq nil (mapcar (lambda (candidate) (propertize candidate 'source source)) (funcall (cdr (assq 'candidates source))))))) (if (and (> ac-limit 1) (> (length cand) ac-limit)) (setcdr (nthcdr (1- ac-limit) cand) nil)) (setq candidates (append candidates cand)))) (delete-dups candidates))) (add-hook 'python-mode-hook (lambda () (auto-complete-mode 1) (set (make-local-variable 'ac-sources) (append ac-sources '(ac-source-rope))) (set (make-local-variable 'ac-find-function) 'ac-python-find) (set (make-local-variable 'ac-candidate-function) 'ac-python-candidate) (set (make-local-variable 'ac-auto-start) nil))) ;;Ryan's python specific tab completion (defun ryan-python-tab () ; Try the following: ; 1) Do a yasnippet expansion ; 2) Do a Rope code completion ; 3) Do an indent (interactive) (if (eql (ac-start) 0) (indent-for-tab-command))) (defadvice ac-start (before advice-turn-on-auto-start activate) (set (make-local-variable 'ac-auto-start) t)) (defadvice ac-cleanup (after advice-turn-off-auto-start activate) (set (make-local-variable 'ac-auto-start) nil)) (define-key py-mode-map "\t" 'ryan-python-tab) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; End Auto Completion ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Auto Syntax Error Hightlight ;(require 'flymake) ;;===== PyFlakes ;; code checking via pyflakes+flymake ;(load-file "C:/.emacs.d/flymake-cursor.el") ;Commented because this is giving mea problem ;(when (load "flymake" t) ; (defun flymake-pyflakes-init () ; (let* ((temp-file (flymake-init-create-temp-buffer-copy ; 'flymake-create-temp-inplace)) ; (local-file (file-relative-name ; temp-file ; (file-name-directory buffer-file-name)))) ; (list "pyflakes" (list local-file)))) ; (add-to-list 'flymake-allowed-file-name-masks ; '("\\.py\\'" flymake-pyflakes-init))) ;(add-hook 'find-file-hook 'flymake-find-file-hook) ; ;(provide 'init_python) A: Got it to work finally! Thanks to phils for pointing me in the right direction. After googling, found this and with the help of google translator (The page is in Russian) was able to finally get syntax checking to work! Details in english: After installing pyflakes the usual way, do the following: Create file called runpyflakes.py in _YourPythonRootDir_\Scripts with the following code: from pyflakes.scripts.pyflakes import main main() Create file called "pyflakes.bat" in _YourPythonRootDir_\Scripts with the following lines: @_YourPythonRootDir_\python.exe _YourPythonRootDir_\Scripts\runpyflakes.py %* Add _YourPythonRootDir_\Scripts to the "Path" environment variable PROBLEM SOLVED!!! Note: _YourPythonRootDir_=path to Python's root directory on your system. In mine its C:\Python26\ Thanks Phils,Starkey, and gelvaos of course!!! A: If you used apt-get as in those instructions then I don't imagine it's a permission issue*, so it sounds like emacs just can't see the executable. flymake calls start-process which looks for the program in the exec-path directories (C-hv exec-path RET) You can put something like (add-to-list 'exec-path "~/bin") in your .emacs to make the appropriate directory visible. (*) If you didn't install it with a package manager, OTOH, then I would also check permissions.
Problem with pyflakes in emacs on Windows
I followed this link here to try and set up emacs for python dev on windows. Although everything seems fine, pyflakes is creating problems and not giving me the syntax checking. Everytime I open a '.py' file, I get the error "Failed to launch syntax check process 'pyflakes' with args 'foo.py': searching for program: No such file or directory pyflakes" Could anyone please help me with this? Update: Here is my .emacs ;; Abhi's c:\.emacs file (add-to-list 'load-path "C:/emacs/colors/") (require 'color-theme) (eval-after-load "color-theme" '(progn (color-theme-initialize) (color-theme-charcoal-black))) (set-default-font "-outline-Monaco-normal-r-normal-normal-13-97-96-96-c-*-iso8859-1") ;Mappings to zoom in and out (defun sacha/increase-font-size () (interactive) (set-face-attribute 'default (selected-frame) :height (ceiling (* 1.10 (face-attribute 'default :height))))) (defun sacha/decrease-font-size () (interactive) (set-face-attribute 'default nil :height (floor (* 0.9 (face-attribute 'default :height))))) (global-set-key (kbd "C-+") 'sacha/increase-font-size) (global-set-key (kbd "C--") 'sacha/decrease-font-size) ;muse mode mappings (add-to-list 'load-path "C:/emacs/Muse/muse-latest/lisp/") (require 'muse-mode) (require 'muse-latex) (require 'muse-book) (require 'muse-html) (require 'muse-colors) ;To do list mode config (add-to-list 'load-path "C:/emacs/lisp/") (autoload 'todo-list-mode "todo-list-mode") ;load when needed ;a simple function that opens the file, ;and switches to todo-list-mode. (defun open-todo-list () (interactive) (find-file "D:/AbhisLife/Tasks/TODO") (todo-list-mode)) ;then bind to control-f12 so i can call it with one keystroke ;this works well for me because i also bind calendar to f12 (global-set-key [C-f12] 'open-todo-list) ;Python development (require 'smart-operator) (add-to-list 'load-path "~/.emacs.d/") (require 'yasnippet) (yas/initialize) (yas/load-directory "~/.emacs.d/snippets/") (require 'auto-complete) (global-auto-complete-mode t) ;(require 'init-auto-complete) (load-library "init_python") And here is my init_python.el (autoload 'python-mode "python-mode" "Python Mode." t) (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode)) (add-to-list 'interpreter-mode-alist '("python" . python-mode)) (require 'python-mode) (add-hook 'python-mode-hook (lambda () (set-variable 'py-indent-offset 4) ;(set-variable 'py-smart-indentation nil) (set-variable 'indent-tabs-mode nil) (define-key py-mode-map (kbd "RET") 'newline-and-indent) ;(define-key py-mode-map [tab] 'yas/expand) ;(setq yas/after-exit-snippet-hook 'indent-according-to-mode) (smart-operator-mode-on) )) ;; pymacs (autoload 'pymacs-apply "pymacs") (autoload 'pymacs-call "pymacs") (autoload 'pymacs-eval "pymacs" nil t) (autoload 'pymacs-exec "pymacs" nil t) (autoload 'pymacs-load "pymacs" nil t) ;(eval-after-load "pymacs" ; (add-to-list 'pymacs-load-path "C:/Python26/MyDownloads/Pymacs/")) (pymacs-load "ropemacs" "rope-") (setq ropemacs-enable-autoimport t) ;(setq yas/trigger-key (kbd "C-c <kp-multiply>")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Auto-completion ;;; Integrates: ;;; 1) Rope ;;; 2) Yasnippet ;;; all with AutoComplete.el ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun prefix-list-elements (list prefix) (let (value) (nreverse (dolist (element list value) (setq value (cons (format "%s%s" prefix element) value)))))) (defvar ac-source-rope '((candidates . (lambda () (prefix-list-elements (rope-completions) ac-target)))) "Source for Rope") (defun ac-python-find () "Python `ac-find-function'." (require 'thingatpt) (let ((symbol (car-safe (bounds-of-thing-at-point 'symbol)))) (if (null symbol) (if (string= "." (buffer-substring (- (point) 1) (point))) (point) nil) symbol))) (defun ac-python-candidate () "Python `ac-candidates-function'" (let (candidates) (dolist (source ac-sources) (if (symbolp source) (setq source (symbol-value source))) (let* ((ac-limit (or (cdr-safe (assq 'limit source)) ac-limit)) (requires (cdr-safe (assq 'requires source))) cand) (if (or (null requires) (>= (length ac-target) requires)) (setq cand (delq nil (mapcar (lambda (candidate) (propertize candidate 'source source)) (funcall (cdr (assq 'candidates source))))))) (if (and (> ac-limit 1) (> (length cand) ac-limit)) (setcdr (nthcdr (1- ac-limit) cand) nil)) (setq candidates (append candidates cand)))) (delete-dups candidates))) (add-hook 'python-mode-hook (lambda () (auto-complete-mode 1) (set (make-local-variable 'ac-sources) (append ac-sources '(ac-source-rope))) (set (make-local-variable 'ac-find-function) 'ac-python-find) (set (make-local-variable 'ac-candidate-function) 'ac-python-candidate) (set (make-local-variable 'ac-auto-start) nil))) ;;Ryan's python specific tab completion (defun ryan-python-tab () ; Try the following: ; 1) Do a yasnippet expansion ; 2) Do a Rope code completion ; 3) Do an indent (interactive) (if (eql (ac-start) 0) (indent-for-tab-command))) (defadvice ac-start (before advice-turn-on-auto-start activate) (set (make-local-variable 'ac-auto-start) t)) (defadvice ac-cleanup (after advice-turn-off-auto-start activate) (set (make-local-variable 'ac-auto-start) nil)) (define-key py-mode-map "\t" 'ryan-python-tab) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; End Auto Completion ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Auto Syntax Error Hightlight ;(require 'flymake) ;;===== PyFlakes ;; code checking via pyflakes+flymake ;(load-file "C:/.emacs.d/flymake-cursor.el") ;Commented because this is giving mea problem ;(when (load "flymake" t) ; (defun flymake-pyflakes-init () ; (let* ((temp-file (flymake-init-create-temp-buffer-copy ; 'flymake-create-temp-inplace)) ; (local-file (file-relative-name ; temp-file ; (file-name-directory buffer-file-name)))) ; (list "pyflakes" (list local-file)))) ; (add-to-list 'flymake-allowed-file-name-masks ; '("\\.py\\'" flymake-pyflakes-init))) ;(add-hook 'find-file-hook 'flymake-find-file-hook) ; ;(provide 'init_python)
[ "Got it to work finally!\nThanks to phils for pointing me in the right direction. After googling, found this and with the help of google translator (The page is in Russian) was able to finally get syntax checking to work!\nDetails in english:\nAfter installing pyflakes the usual way, do the following:\n\nCreate fil...
[ 5, 2 ]
[]
[]
[ "emacs", "pyflakes", "python" ]
stackoverflow_0003513975_emacs_pyflakes_python.txt
Q: Quickly remove first n lines from many text files I need to create an output text file by deleting the first two lines of the input file. At the moment I'm using sed "1,2d" input.txt > output.txt I need to do this for thousands of files, so am using python: import os for filename in somelist: os.system('sed "1,2d" %s-in.txt > %s-out.txt'%(filename,filename)) but this is quite slow. I need to keep the original file, so I can't sed in place. Is there a way to do this faster? Using something other than sed?Perhaps using some other scripting language than python? Is it worth writing a short C program, or is the file-writing disk-access likely to be the bottleneck? A: Use tail. Doubt anything could be significantly faster: tail -n +3 input.txt > output.txt Wrap it in your loop of choice. But I really doubt sed is a whole ton slower - as you say, disk i/o is usually the ultimate bottleneck. A: I think this will be faster than launching sed: import os import shutil path = '/some/path/to/files/' for filename in os.listdir(path): basename, ext = os.path.splitext(filename) fullname = os.path.join(path, filename) newname = os.path.join(path, basename + '-out' + ext) with open(fullname) as read: #skip first two lines for n in xrange(2): read.readline() # hand the rest to shutil.copyfileobj with open(newname, 'w') as write: shutil.copyfileobj(read, write) A: for file in *.ext do sed -i.bak -n '3,$p' $file done or just sed -i.bak -n '3,$p' *.ext
Quickly remove first n lines from many text files
I need to create an output text file by deleting the first two lines of the input file. At the moment I'm using sed "1,2d" input.txt > output.txt I need to do this for thousands of files, so am using python: import os for filename in somelist: os.system('sed "1,2d" %s-in.txt > %s-out.txt'%(filename,filename)) but this is quite slow. I need to keep the original file, so I can't sed in place. Is there a way to do this faster? Using something other than sed?Perhaps using some other scripting language than python? Is it worth writing a short C program, or is the file-writing disk-access likely to be the bottleneck?
[ "Use tail. Doubt anything could be significantly faster:\ntail -n +3 input.txt > output.txt\n\nWrap it in your loop of choice. But I really doubt sed is a whole ton slower - as you say, disk i/o is usually the ultimate bottleneck.\n", "I think this will be faster than launching sed:\nimport os\nimport shutil\n\np...
[ 10, 4, 3 ]
[]
[]
[ "file_io", "performance", "python", "sed" ]
stackoverflow_0003521812_file_io_performance_python_sed.txt
Q: Google App Engine, Python and IPython I want to use IPython under GAE to debug scripts locally: import ipdb; ipdb.set_trace() but GAE restricts loading some modules from sys.path. Can I bypass this somehow? A: You can hack the GAE SDK's restrictions of course (you do have its sources on your computer, and it's open-source code!-), but, if you do, it won't catch the cases in which your code erroneously tries to import modules it won't be allowed to use on Google's servers. So I suggest, at the very least, if you do perform such a hack, make it conditional on some environment variable (if os.getenv('MYHACK')=='Y': ...), so that it's disabled by default (and the GAE SDK behaves normally) and you only enable it explicitly at your shell with e.g. $ MYHACK=Y ipython ... at a bash (or sh;-) prompt.
Google App Engine, Python and IPython
I want to use IPython under GAE to debug scripts locally: import ipdb; ipdb.set_trace() but GAE restricts loading some modules from sys.path. Can I bypass this somehow?
[ "You can hack the GAE SDK's restrictions of course (you do have its sources on your computer, and it's open-source code!-), but, if you do, it won't catch the cases in which your code erroneously tries to import modules it won't be allowed to use on Google's servers. So I suggest, at the very least, if you do perf...
[ 0 ]
[]
[]
[ "google_app_engine", "ipython", "python" ]
stackoverflow_0003521816_google_app_engine_ipython_python.txt
Q: Writing certain lines to a file in python I have a large file called fulldataset. I would like to write lines from fulldataset to a new file called newdataset. I only want to write the lines from fulldataset though that contain the id numbers present in the listfile. Also all the id numbers start with XY. The id numbers occur in the middle of each line though. Here is an example line from list file: Robert, Brown, "XY-12344343", 1929232, 324934923, Here is the program I have so far. It runs fine, but doesn't write anything into the new file. datafile = open('C:\\listfile.txt', 'r') completedataset = open('C:\\fulldataset.txt', 'r') smallerdataset = open('C:\\newdataset.txt', 'w') matchedLines = [] for line in datafile: if line.find("XY"): matchedLines.append( line ) counter = 1 for line in completedataset: print counter counter +=1 for t in matchedLines: if t in line: fulldataset.write(line) del line break datafile.close() completedataset.close() fulldataset.close() EDIT: Ok here is the new program: datafile = open('C:\\tryexcel33.txt', 'r') completedataset = open('C:\\fulldataset.txt', 'r') smallerdataset = open('C:\\newdataset.txt', 'w') counter = 1 for line in completedataset: print counter counter +=1 if any( id in line for id in datafile ): smallerdataset.write( line ) break datafile.close() completedataset.close() fulldataset.close() I still don't have anything being written to the new file. I think a problem might be that in the full file the id numbers have a " in front of them but this doesn't exist in the listfile. Any thoughts? A: I don't understand your code. Here's the code to do what you've asked: ids = set( datafile.readlines( ) ) for line in fulldataset: if any( id in line for id in ids ): smallerdataset.write( line ) EDIT: I did the best I could with incomplete data. The fact that the IDs in the fulldataset are prefixed with XY is irrelevant, since we are searching through the whole string anyway ("foo" in "XY-foo" is still true). If no lines are being written, that's because the lines of datafile are not exactly IDs. Please post a sample from datafile. You are also reusing the variable line, which will make your code go wrong in mysterious ways. You also have a break statement, which will cause at most one line to be written. Why? EDIT Many apologies, I just re-read the code -- for some reason I had assumed that datafile was a list. It's actually a file, so my previous code won't work. Please see the fixed code.
Writing certain lines to a file in python
I have a large file called fulldataset. I would like to write lines from fulldataset to a new file called newdataset. I only want to write the lines from fulldataset though that contain the id numbers present in the listfile. Also all the id numbers start with XY. The id numbers occur in the middle of each line though. Here is an example line from list file: Robert, Brown, "XY-12344343", 1929232, 324934923, Here is the program I have so far. It runs fine, but doesn't write anything into the new file. datafile = open('C:\\listfile.txt', 'r') completedataset = open('C:\\fulldataset.txt', 'r') smallerdataset = open('C:\\newdataset.txt', 'w') matchedLines = [] for line in datafile: if line.find("XY"): matchedLines.append( line ) counter = 1 for line in completedataset: print counter counter +=1 for t in matchedLines: if t in line: fulldataset.write(line) del line break datafile.close() completedataset.close() fulldataset.close() EDIT: Ok here is the new program: datafile = open('C:\\tryexcel33.txt', 'r') completedataset = open('C:\\fulldataset.txt', 'r') smallerdataset = open('C:\\newdataset.txt', 'w') counter = 1 for line in completedataset: print counter counter +=1 if any( id in line for id in datafile ): smallerdataset.write( line ) break datafile.close() completedataset.close() fulldataset.close() I still don't have anything being written to the new file. I think a problem might be that in the full file the id numbers have a " in front of them but this doesn't exist in the listfile. Any thoughts?
[ "I don't understand your code. Here's the code to do what you've asked:\nids = set( datafile.readlines( ) )\nfor line in fulldataset:\n if any( id in line for id in ids ):\n smallerdataset.write( line )\n\n\nEDIT: I did the best I could with incomplete data. The fact that the IDs in the fulldataset are pr...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003523846_python.txt
Q: Python assertion error, converting string to int I am trying to rewrite my lib written in PHP into python. It handles all sphinx requests. In the init function, I am trying to set default search and match modes, but I have run into a little problem. I get the modes from a config file. In PHP, you need to use a constant as an input: $this->sphinx->SetMatchMode(constant($this->conf['match_mode'])); This will convert the string from config file into a constant and everything works. The tricky part starts in python, when I try to do this: self.sphinx.SetMatchMode(self.config['match_mode']) I get: AssertionError in assert(mode in [SPH_MATCH_ALL, SPH_MATCH_ANY, SPH_MATCH_PHRASE, SPH_MATCH_BOOLEAN, SPH_MATCH_EXTENDED, SPH_MATCH_FULLSCAN, SPH_MATCH_EXTENDED2]) In this case, the input should be an integer, but the input is a string and I cant convert it because I get an exception - the string is SPH_MATCH_ALL. invalid literal for int() with base 10: 'SPH_MATCH_ALL' When I try this: print type(self.config['match_mode']) # -- string print type(SPH_MATCH_ALL) # -- integer print SPH_MATCH_ALL # -- 1 print SPH_MATCH_ANY # -- 0 So my question would be, how can I convert the string into an integer or whatever it thinks it is, so I wont get an assertion error. Of course, that I could just do some if/else statements, but I dont want that. Is there any elegant way to do this? A: Python doesn't have a direct equivalent of the PHP constant() function. If the constant in question is imported from a module, the cleanest way to do it is like this: import myconstants num = int(getattr(myconstants, self.config['match_mode'])) Or if it's defined at global scope within the current module, you can do this: X = 1 num = int(globals()['X']) Either way, you're doing something slightly risky by letting the user control which objects your code deals with. It's not quite eval(), but it's a little way down that road. That's why I've included the int() conversions there - they should fail if the user configures the system with the name of something that isn't an integer. There may be more robust ways to do this - I'm not quite comfortable with it, but it's somewhere close to your PHP constant() code without a complete rewrite. A: I'm not familiar with sphinx, but based on you question, I would try something like this DEFAULT = 0 mode = getattr(self.sphinx, self.config['match_mode'], DEFAULT) self.sphinx.SetMatchMode(mode) That's assuming that the sphinx module defines the modes in the form SPH_MATCH_ANY = 0 SPH_MATCH_ALL = 1 # .... A: Write a function that converts the mode string to the corresponding integer, then use that when you call in the config: self.sphinx.SetMatchMode(modeToInt(self.config['match_mode'])) You can hive away whatever if/else ugliness is required into the function.
Python assertion error, converting string to int
I am trying to rewrite my lib written in PHP into python. It handles all sphinx requests. In the init function, I am trying to set default search and match modes, but I have run into a little problem. I get the modes from a config file. In PHP, you need to use a constant as an input: $this->sphinx->SetMatchMode(constant($this->conf['match_mode'])); This will convert the string from config file into a constant and everything works. The tricky part starts in python, when I try to do this: self.sphinx.SetMatchMode(self.config['match_mode']) I get: AssertionError in assert(mode in [SPH_MATCH_ALL, SPH_MATCH_ANY, SPH_MATCH_PHRASE, SPH_MATCH_BOOLEAN, SPH_MATCH_EXTENDED, SPH_MATCH_FULLSCAN, SPH_MATCH_EXTENDED2]) In this case, the input should be an integer, but the input is a string and I cant convert it because I get an exception - the string is SPH_MATCH_ALL. invalid literal for int() with base 10: 'SPH_MATCH_ALL' When I try this: print type(self.config['match_mode']) # -- string print type(SPH_MATCH_ALL) # -- integer print SPH_MATCH_ALL # -- 1 print SPH_MATCH_ANY # -- 0 So my question would be, how can I convert the string into an integer or whatever it thinks it is, so I wont get an assertion error. Of course, that I could just do some if/else statements, but I dont want that. Is there any elegant way to do this?
[ "Python doesn't have a direct equivalent of the PHP constant() function. If the constant in question is imported from a module, the cleanest way to do it is like this:\nimport myconstants\nnum = int(getattr(myconstants, self.config['match_mode']))\n\nOr if it's defined at global scope within the current module, yo...
[ 3, 1, 0 ]
[]
[]
[ "assertion", "python", "sphinx" ]
stackoverflow_0003523932_assertion_python_sphinx.txt
Q: Python module search path I have a project like that : foo/ | main.py | bar/ | | module1.py | | module2.py | | __init__.py with main.py doing import bar.module1 and module1.py doing import module2. This works using python 2.6 but not with python 3.1 (ImportError: No module named module2) Why did the behaviour change ? How to restore it ? A: In module1.py, do a: from . import module2 main.py import bar.module1 print(bar.module1.module2.thing) bar/init.py # bar/module1.py #import module2 # fails in python31 from . import module2 # intrapackage reference, works in python26 and python31 bar/module2.py thing = "blah" As for why/how, that's above my paygrade. The documentation doesn't seem to elucidate it. Maybe in Python 3 they decided to enforce submodules in packages being explicitly imported with the intrapackage style? http://docs.python.org/py3k/tutorial/modules.html#intra-package-references http://docs.python.org/tutorial/modules.html#intra-package-references
Python module search path
I have a project like that : foo/ | main.py | bar/ | | module1.py | | module2.py | | __init__.py with main.py doing import bar.module1 and module1.py doing import module2. This works using python 2.6 but not with python 3.1 (ImportError: No module named module2) Why did the behaviour change ? How to restore it ?
[ "In module1.py, do a: from . import module2\nmain.py\nimport bar.module1\nprint(bar.module1.module2.thing)\n\nbar/init.py\n#\n\nbar/module1.py\n#import module2 # fails in python31\nfrom . import module2 # intrapackage reference, works in python26 and python31\n\nbar/module2.py\nthing = \"blah\"\n\nAs for why/how, t...
[ 6 ]
[]
[]
[ "module", "path", "python" ]
stackoverflow_0003523827_module_path_python.txt
Q: Trouble setting up sqlite3 with django! :/ I'm in the settings.py module, and I'm supposed to add the directory to the sqlite database. How do I know where the database is and what the full directory is? I'm using Windows 7. A: The absolute path of the database directory is what you need. For e.g. if your database is named my.db and lives in C:\users\you\ then: DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = 'C:/users/you/my.db' Update AFAIK you do not have to create the database yourself. The database will be created when you run syncdb. The database can live in any directory you wish. If you want the database to be in you Django project directory just change the path accordingly. For e.g. let us say your Django project lives in C:\users\you\myproject\. You would then change your settings thus: DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = 'C:/users/you/myproject/my.db' A: if you don't provide full path, it will use the current directory of settings.py, and if you wish to specify static path you can specify it like: c:/projects/project1/my_proj.db or in case you want to make it dynamic then you can use os.path module so os.path.dirname(file) will give you the path of settings.py and accordingly you can alter the path for your database like os.path.join(os.path.dirname(file),'my_proj.db')
Trouble setting up sqlite3 with django! :/
I'm in the settings.py module, and I'm supposed to add the directory to the sqlite database. How do I know where the database is and what the full directory is? I'm using Windows 7.
[ "The absolute path of the database directory is what you need. For e.g. if your database is named my.db and lives in C:\\users\\you\\ then:\nDATABASE_ENGINE = 'sqlite3'\nDATABASE_NAME = 'C:/users/you/my.db' \n\nUpdate \nAFAIK you do not have to create the database yourself. The database will be created when you ru...
[ 3, 1 ]
[]
[]
[ "database", "django", "python", "sqlite" ]
stackoverflow_0003524236_database_django_python_sqlite.txt
Q: Using a variable as an object key in Django Template Tags I have two 4 tier objects that I am passing to the django template. I am currently for looping through each tier, and going down a level if it exists. I ended up having key, key2 and key3 that represents the current location in the object while looping. I would like to reference the other object that has the same tiers using those variables, but am having some trouble. If I was trying to do this in python, it would look like this my_object[ key ][ key2 ][ key3 ] But in django templates, it doesn't seem I can use brackets, and if I used periods it would think key is the key name, and not look at it as a variable. If you need more details on my code, let me know. Thanks! Edit: Here is an example of what my object looks like, and my template code. variable1 = { "content": { "pages": { "view":True, "add":True, "edit":True, "delete":True }, "articles": { "view":True, "add":True, "edit":True, "delete":True }, "slideshow": { "view":True, "edit":True }, }, "people": { "view":True, "add":True, "edit":True, "delete":True, "sort-staff":True, "sort-riders":True } } variable2 is the same as variable one, with the same keys, but some keys are missing. Here is what my template looks like to sort through this object. {% for key, value in variable1.items %} <strong>{{ key|title }}</strong> {% for key2, value2 in value.items %} {% if value2.items %} <p class="indent">{{ key2|title }} {% for key3, value3 in value2.items %} <p class="indent"><input type="checkbox" name="form_permission_{{ key }}_{{ key2 }}_{{ key3 }}" {% if variable2[key][key2][key3] %}checked="checked"{% endif %}> {{ key3|title }}</p> {% endfor %} </p> {% else %} <p class="indent"><input type="checkbox" name="form_permission_{{ key }}_{{ key2 }}"> {{ key2|title }}</p> {% endif %} {% endfor %} {% endfor %} If you look at the most indented line, you will see {% if variable2[key][key2][key3] %}checked="checked"{% endif %}. You should be able to understand what I'm trying to accomplish with that code. A: That cannot be done this way. Look into writing a template tag or filter for this. A: I ended up doing the sorting and comparing before the data was sent to the template so this question is no longer needed. Feel free to post other options.
Using a variable as an object key in Django Template Tags
I have two 4 tier objects that I am passing to the django template. I am currently for looping through each tier, and going down a level if it exists. I ended up having key, key2 and key3 that represents the current location in the object while looping. I would like to reference the other object that has the same tiers using those variables, but am having some trouble. If I was trying to do this in python, it would look like this my_object[ key ][ key2 ][ key3 ] But in django templates, it doesn't seem I can use brackets, and if I used periods it would think key is the key name, and not look at it as a variable. If you need more details on my code, let me know. Thanks! Edit: Here is an example of what my object looks like, and my template code. variable1 = { "content": { "pages": { "view":True, "add":True, "edit":True, "delete":True }, "articles": { "view":True, "add":True, "edit":True, "delete":True }, "slideshow": { "view":True, "edit":True }, }, "people": { "view":True, "add":True, "edit":True, "delete":True, "sort-staff":True, "sort-riders":True } } variable2 is the same as variable one, with the same keys, but some keys are missing. Here is what my template looks like to sort through this object. {% for key, value in variable1.items %} <strong>{{ key|title }}</strong> {% for key2, value2 in value.items %} {% if value2.items %} <p class="indent">{{ key2|title }} {% for key3, value3 in value2.items %} <p class="indent"><input type="checkbox" name="form_permission_{{ key }}_{{ key2 }}_{{ key3 }}" {% if variable2[key][key2][key3] %}checked="checked"{% endif %}> {{ key3|title }}</p> {% endfor %} </p> {% else %} <p class="indent"><input type="checkbox" name="form_permission_{{ key }}_{{ key2 }}"> {{ key2|title }}</p> {% endif %} {% endfor %} {% endfor %} If you look at the most indented line, you will see {% if variable2[key][key2][key3] %}checked="checked"{% endif %}. You should be able to understand what I'm trying to accomplish with that code.
[ "That cannot be done this way. Look into writing a template tag or filter for this.\n", "I ended up doing the sorting and comparing before the data was sent to the template so this question is no longer needed. Feel free to post other options.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003517928_django_django_templates_python.txt
Q: Are twisted RPCs guaranteed to arrive in order? I'm using twisted to implement a client and a server. I've set up RPC between the client and the server. So on the client I do protocol.REQUEST_UPDATE_STATS(stats), which translates into sending a message with transport.write on the client transport that is some encoded version of ["update_stats", stats]. When the server receives this message, the dataReceived function on the server protocol is called, it decodes it, and calls a function based on the message, like CMD_UPDATE_STATS(stats) in this case. If, on the client, I do something like: protocol.REQUEST_UPDATE_STATS("stats1") protocol.REQUEST_UPDATE_STATS("stats2") ...am I guaranteed that the "stats1" message arrives before the "stats2" message on the server? UPDATE: Edited for more clarity. But now the answer seems obvious - no way. A: They will arrive in the order that the request is received by the Python process. This includes the connection setup time plus the packets containing the request data. So no, this is not guaranteed to be the order that the sending processes sent the request, because of network latency, dropped packets, sender-side packet queuing, etc. "In-order" is also loosely defined for distributed systems. But yes, in general you can count on them being delivered in-order as long as they're separated by a relatively large amount of time (100's of ms over the internet).
Are twisted RPCs guaranteed to arrive in order?
I'm using twisted to implement a client and a server. I've set up RPC between the client and the server. So on the client I do protocol.REQUEST_UPDATE_STATS(stats), which translates into sending a message with transport.write on the client transport that is some encoded version of ["update_stats", stats]. When the server receives this message, the dataReceived function on the server protocol is called, it decodes it, and calls a function based on the message, like CMD_UPDATE_STATS(stats) in this case. If, on the client, I do something like: protocol.REQUEST_UPDATE_STATS("stats1") protocol.REQUEST_UPDATE_STATS("stats2") ...am I guaranteed that the "stats1" message arrives before the "stats2" message on the server? UPDATE: Edited for more clarity. But now the answer seems obvious - no way.
[ "They will arrive in the order that the request is received by the Python process. This includes the connection setup time plus the packets containing the request data. So no, this is not guaranteed to be the order that the sending processes sent the request, because of network latency, dropped packets, sender-side...
[ 1 ]
[]
[]
[ "concurrency", "consistency", "python", "rpc", "twisted" ]
stackoverflow_0003524384_concurrency_consistency_python_rpc_twisted.txt
Q: Python ~ accessing tuple members in template class I am new to Python - be forewarned! I have a template class that takes a list as an argument and applies the members of the list to the template. Here's the first class: class ListTemplate: def __init__(self, input_list=[]): self.input_list = input_list def __str__(self): return "\n".join([self._template % x for x in self.input_list]) Here's the template code/class: class HTML_Template(ListTemplate): _template = """ <li> <table width="100%%" border="0"> <tr> <td>Title: %(title)s</td> <td>Link: %(isbn)s</td> </tr> <tr> <td>Author: %(author)s</td> <td>Date: %(pub_date)s</td> </tr> <tr> <td>Summary: %(isbn)s</td> <td>Description: %(descr)s</td> </tr> </table> <hr> </li>""" Here's the problem: I'm pulling data from a sqlite database using fetchall, which return a list of tuples. I can pass this list of tuples to this method fine by changing the template to %s instead of %(isbn) ...etc., however, I need to access the isbn member multiple times in the template. To do this now, I load the tuples in to dictionaries and push them into another list ...then pass the list of dictionaries. This strikes me as inefficient. My question is: how would you rewrite this so that the original list of tuples could be passed to the template (thus, saving a step ), while still allowing access to the individual members by ie., item[0] or similar? Thanks ~ Bubnoff A: If you are using Python 2.6 or newer, you can use the format method of strings instead of the % operator. This allows you to specify the index of the given arguments: >>> template = 'First value: {0}, Second value: {1}, First again: {0}' >>> values = (123, 456) >>> template.format(*values) 'First value: 123, Second value: 456, First again: 123' A: If you use the new string formatting, it may be possible to operate solely on indices... But that will be horrible to decipher, even with the database scheme at hand. The list-of-dict approach sounds much saner, and unless you operate a really frequently-visited service, the performance impact won't be too bad (this depends on the size of the data set - but you don't get 3k 7-tuples at once, do you?). Dictionaries are rather efficient in Python. Caching could also help performance-wise.
Python ~ accessing tuple members in template class
I am new to Python - be forewarned! I have a template class that takes a list as an argument and applies the members of the list to the template. Here's the first class: class ListTemplate: def __init__(self, input_list=[]): self.input_list = input_list def __str__(self): return "\n".join([self._template % x for x in self.input_list]) Here's the template code/class: class HTML_Template(ListTemplate): _template = """ <li> <table width="100%%" border="0"> <tr> <td>Title: %(title)s</td> <td>Link: %(isbn)s</td> </tr> <tr> <td>Author: %(author)s</td> <td>Date: %(pub_date)s</td> </tr> <tr> <td>Summary: %(isbn)s</td> <td>Description: %(descr)s</td> </tr> </table> <hr> </li>""" Here's the problem: I'm pulling data from a sqlite database using fetchall, which return a list of tuples. I can pass this list of tuples to this method fine by changing the template to %s instead of %(isbn) ...etc., however, I need to access the isbn member multiple times in the template. To do this now, I load the tuples in to dictionaries and push them into another list ...then pass the list of dictionaries. This strikes me as inefficient. My question is: how would you rewrite this so that the original list of tuples could be passed to the template (thus, saving a step ), while still allowing access to the individual members by ie., item[0] or similar? Thanks ~ Bubnoff
[ "If you are using Python 2.6 or newer, you can use the format method of strings instead of the % operator. This allows you to specify the index of the given arguments:\n>>> template = 'First value: {0}, Second value: {1}, First again: {0}'\n>>> values = (123, 456)\n>>> template.format(*values)\n'First value: 123, S...
[ 0, 0 ]
[]
[]
[ "dictionary", "python", "sqlite" ]
stackoverflow_0003524478_dictionary_python_sqlite.txt
Q: Improvizing a drop-in replacement for the "with" statement for Python 2.4 Can you suggest a way to code a drop-in replacement for the "with" statement that will work in Python 2.4? It would be a hack, but it would allow me to port my project to Python 2.4 more nicely. EDIT: Removed irrelevant metaclass sketch A: Just use try-finally. Really, this may be nice as a mental exercise, but if you actually do it in code you care about you will end up with ugly, hard to maintain code. A: You could (ab)use decorators to do this, I think. The following works, eg: def execute_with_context_manager(man): def decorator(f): target = man.__enter__() exc = True try: try: f(target) except: exc = False if not man.__exit__(*sys.exc_info()): raise finally: if exc: man.__exit__(None, None, None) return None return decorator @execute_with_context_manager(open("/etc/motd")) def inside(motd_file): for line in motd_file: print line, (Well, in Python 2.4 file objects don't have __enter__ and __exit__ methods, but otherwise it works) The idea is you're replacing the with line in: with bar() as foo: do_something_with(foo) do_something_else_with(foo) # etc... with the decorated function "declaration" in: @execute_with_context_manager( bar() ) def dummyname( foo ): do_something_with(foo) do_something_else_with(foo) # etc... but getting the same behaviour (the do_something_... code executed). Note the decorator changes the function declaration into an immediate invocation which is more than a little evil. A: Since you need to exit the context manager both during errors and not errors, I don't think it's possible to do a generic usecase with metaclasses, or in fact at all. You are going to need try/finally blocks for that. But maybe it's possible to do something else in your case. That depends on what you use the context manager for. Using __del__ can help in some cases, like deallocating resource, but since you can't be sure it gets called, it can only be used of you need to release resources that will be released when the program exits. That also won't work if you are handling exceptions in the __exit__ method. I guess the cleanest method is to wrap the whole context management in a sort of context managing call, and extract the code block into a method. Something like this (untested code, but mostly stolen from PEP 343): def call_as_context_manager(mgr, function): exit = mgr.__exit__ value = mgr.__enter__() exc = True try: try: function(value) except: exc = False if not exit(*sys.exc_info()): raise finally: if exc: exit(None, None, None) A: How about this? def improvize_context_manager(*args, **kwargs): assert (len(args) + len(kwargs)) == 1 if args: context_manager = args[0] as_ = None else: # It's in kwargs (as_, context_manager) = kwargs.items()[0] def decorator(f): exit_ = context_manager.__exit__ # Not calling it yet enter_ = context_manager.__enter__() exc = True try: try: if as_: f(*{as_: enter_}) else: f() except: exc = False if not exit_(*sys.exc_info()): raise finally: if exc: exit_(None, None, None) return None return decorator Usage: @improvize_context_manager(lock) def null(): do(stuff) Which parallels the with keyword without as. Or: @improvize_context_manager(my_lock=lock) def null(my_lock): do(stuff_with, my_lock) Which parallels the with keyword with the as. A: If you are OK with using def just to get a block, and decorators that immediately execute, you could use the function signature to get something more natural for the named case. import sys def with(func): def decorated(body = func): contexts = body.func_defaults try: exc = None, None, None try: for context in contexts: context.__enter__() body() except: exc = sys.exc_info() raise finally: for context in reversed(contexts): context.__exit__(*exc) decorated() class Context(object): def __enter__(self): print "Enter %s" % self def __exit__(self, *args): print "Exit %s(%s)" % (self, args) x = Context() @with def _(it = x): print "Body %s" % it @with def _(it = x): print "Body before %s" % it raise "Nothing" print "Body after %s" % it
Improvizing a drop-in replacement for the "with" statement for Python 2.4
Can you suggest a way to code a drop-in replacement for the "with" statement that will work in Python 2.4? It would be a hack, but it would allow me to port my project to Python 2.4 more nicely. EDIT: Removed irrelevant metaclass sketch
[ "Just use try-finally.\nReally, this may be nice as a mental exercise, but if you actually do it in code you care about you will end up with ugly, hard to maintain code.\n", "You could (ab)use decorators to do this, I think. The following works, eg:\ndef execute_with_context_manager(man):\n def decorator(f):\n...
[ 7, 4, 1, 1, 1 ]
[]
[]
[ "python", "with_statement" ]
stackoverflow_0001547526_python_with_statement.txt
Q: Why the second time I run "readlines" on the same file nothing is returned? >>> f = open('/tmp/version.txt', 'r') >>> f <open file '/tmp/version.txt', mode 'r' at 0xb788e2e0> >>> f.readlines() ['2.3.4\n'] >>> f.readlines() [] >>> I've tried this in Python's interpreter. Why does this happen? A: You need to seek to the beginning of the file. Use f.seek(0) to return to the begining: >>> f = open('/tmp/version.txt', 'r') >>> f <open file '/tmp/version.txt', mode 'r' at 0xb788e2e0> >>> f.readlines() ['2.3.4\n'] >>> f.seek(0) >>> f.readlines() ['2.3.4\n'] >>> A: Python keeps track of where you are in the file. When you're at the end, it doesn't automatically roll back over. Try f.seek(0). A: The important part to understand that some of the other posters don't explicitly state is that files are read with a cursor that marks the current position in the file. So on the first readlines() call the cursor is at the beginning of your file, and is progressed all the way to the end of the file since all the files data was returned. On the second readlines call the cursor is at the end of the file, so when it reads to the end of the file, it doesn't move at all, and no data is returned. For educational purposes, you could write a quick bit of code that would open a file, read a few bytes or lines out, and then call readlines(), you will see that the output of the readlines() call begins where you left off with your previous reads, and continues until the end of the file. The seek(0) call mentioned by other will allow you to reset the cursor at the beginning of the file to start over with the reads. A: In addition to seeking to the beginning of the file, you can also store the value as something that you can reuse later if you just need them in memory. Something like this: with open('tmp/version.txt', 'r') as f: lines = f.readlines() The with statement is new in 2.6 I believe, in prior versions you'd need to import it from future.
Why the second time I run "readlines" on the same file nothing is returned?
>>> f = open('/tmp/version.txt', 'r') >>> f <open file '/tmp/version.txt', mode 'r' at 0xb788e2e0> >>> f.readlines() ['2.3.4\n'] >>> f.readlines() [] >>> I've tried this in Python's interpreter. Why does this happen?
[ "You need to seek to the beginning of the file. Use f.seek(0) to return to the begining:\n>>> f = open('/tmp/version.txt', 'r')\n>>> f\n<open file '/tmp/version.txt', mode 'r' at 0xb788e2e0>\n>>> f.readlines()\n['2.3.4\\n']\n>>> f.seek(0)\n>>> f.readlines()\n['2.3.4\\n']\n>>>\n\n", "Python keeps track of where y...
[ 20, 6, 6, 4 ]
[]
[]
[ "python" ]
stackoverflow_0003524528_python.txt
Q: Creation of simple CRUD website using Python which framework? I need to create a simple python website showing customer by salesman and sales by customer. No update of data at all at this time. Which framework might be best. I am not a web guru by any means can read HTML, and Understand CSS. Data is in MySQL. This is a quick and dirty. Thanks A: Probably Django is your best bet as it has a simple ORM and an automatic admin interface which might prove useful. You might be able to simple "switch off" the ability to update records in the admin interface and just use that. A: "Best" is really an opinion question. My personal preference is for Django. If you already have a database, you can auto-generate models for the data, assuming all your tables have primary keys and aren't too "weird". The admin application will quickly give you the ability to view and modify all of your data. http://www.djangoproject.com/
Creation of simple CRUD website using Python which framework?
I need to create a simple python website showing customer by salesman and sales by customer. No update of data at all at this time. Which framework might be best. I am not a web guru by any means can read HTML, and Understand CSS. Data is in MySQL. This is a quick and dirty. Thanks
[ "Probably Django is your best bet as it has a simple ORM and an automatic admin interface which might prove useful. You might be able to simple \"switch off\" the ability to update records in the admin interface and just use that.\n", "\"Best\" is really an opinion question. My personal preference is for Django. ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003524733_python.txt
Q: Does this regex mean it has to start with A, end with Z? re.search "\A[0-9A-Za-z_-]+\Z" Does this regex mean it has to start with A, end with Z? re.search("\A[0-9A-Za-z_-]+\Z", sometext) A: No, those are anchors. \A means start of string, and \Z means end of string. Similarly ^ means start of line and $ means end of line. See the documentation for the re module. \A - Matches only at the start of the string. \Z - Matches only at the end of the string. A: What is "it"? If you're talking about a string. Yes, it does: \A means beginning of a string , \Z means end of a string. If you are talking about a line (inside a string), you will have to insert boundary operators: "^[0-9A-Za-z_-]+$" ^ ("caret") specifies beginning of a line; $ ("dollar sign") specifies the end of a line. If you are talking about a word: no, it does not; you did not specify start or end of a word. A: Just remove the '\' and you will get what you want. "^A[0-9A-Za-z_-]+Z$"
Does this regex mean it has to start with A, end with Z? re.search "\A[0-9A-Za-z_-]+\Z"
Does this regex mean it has to start with A, end with Z? re.search("\A[0-9A-Za-z_-]+\Z", sometext)
[ "No, those are anchors.\n\\A means start of string, and \\Z means end of string. Similarly ^ means start of line and $ means end of line.\nSee the documentation for the re module.\n\n\\A - Matches only at the start of the string.\n \\Z - Matches only at the end of the string.\n\n", "What is \"it\"?\nIf you're ta...
[ 7, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003524788_python_regex.txt
Q: Problems matching caret in Python regex I have the following regular expression, which I think should match any character that is not alphanumeric, '!', '?', or '.' re.compile('[^A-z ?!.]') However, I get the following weird result in iPython: In [21]: re.sub(a, ' ', 'Hey !$%^&*.#$%^&.') Out[21]: 'Hey ! ^ . ^ .' The result is the same when I escape the '.' in the regular expression. How do I match the caret so that it is removed from the string as well? A: You have an error in your regular expression. Note that the case of the a and z is important. A-z includes all characters between ASCII value 65 (A) and 122 (Z), which includes the caret character (ASCII code 94). Try this instead: re.compile('[^A-Za-z ?!.]') Example: import re regex = re.compile('[^A-Za-z ?!.]') result = regex.sub(' ', 'Hey !$%^&*.#$%^&.') print result Result: Hey ! . . A: The caret falls between the upper and lower cases in ASCII. You need [^a-zA-Z ?!\.]
Problems matching caret in Python regex
I have the following regular expression, which I think should match any character that is not alphanumeric, '!', '?', or '.' re.compile('[^A-z ?!.]') However, I get the following weird result in iPython: In [21]: re.sub(a, ' ', 'Hey !$%^&*.#$%^&.') Out[21]: 'Hey ! ^ . ^ .' The result is the same when I escape the '.' in the regular expression. How do I match the caret so that it is removed from the string as well?
[ "You have an error in your regular expression. Note that the case of the a and z is important. A-z includes all characters between ASCII value 65 (A) and 122 (Z), which includes the caret character (ASCII code 94).\nTry this instead:\nre.compile('[^A-Za-z ?!.]')\n\nExample:\nimport re\nregex = re.compile('[^A-Za-z ...
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003524867_python_regex.txt
Q: How to handle a one line for loop without putting it in a List? Maybe the question is a bit vague, but what I mean is this code: 'livestream' : [cow.legnames for cow in listofcows] Now the problem is cow.legnames is also a list so I will get a list in a list when I try to return it with Json. How should I make it to return a single list. This is the json that would be returned. 'livestream' : [['blue leg', 'red leg']] I hope the code explains what my question is. A: In addition to shahjapan's reduce you can use this syntax to flatten list. [legname for cow in listofcows for legname in cow.legnames] A: The name listofcows implies there may be, possibly in a distant future, several cows. Flattening a list of list with more than one item would be simply wrong. But if the name is misleading (and why a one-lement list anyway, for that matter?), you have several options to flatten it. Nested list comprehension: [legname for cow in listofcows cow.legnames for legname in cow.legnames] Getting the first item: [your list comprehension][0] And very likely some useful thingy from the standard library I don't remember right now. A: From my understanding, you have something like this: class Cow(object): def __init__(self, legnames): self.legnames = legnames listofcows = [Cow(['Red Leg', 'Blue Leg']), Cow(['Green Leg', 'Red Leg'])] It's easiest extend a temporary list, like this: legs = [] # As @delnan noted, its generally a bad idea to use a list # comprehension to modify something else, so use a for loop # instead. for cow in listofcows: legs.extend(cow.legnames) # Now use the temporary legs list... print {'livestream':legs} A: Is this what you're looking for? 'livestream' : [cow.legnames[0] for cow in listofcows] A: you can try reduce, 'livestream' : reduce(lambda a,b:a+b,[cow.legs for cow in listofcows]) if you need unique legs use set 'livestream' :list(set(reduce(lambda a,b:a+b,[cow.legs for cow in listofcows])))
How to handle a one line for loop without putting it in a List?
Maybe the question is a bit vague, but what I mean is this code: 'livestream' : [cow.legnames for cow in listofcows] Now the problem is cow.legnames is also a list so I will get a list in a list when I try to return it with Json. How should I make it to return a single list. This is the json that would be returned. 'livestream' : [['blue leg', 'red leg']] I hope the code explains what my question is.
[ "In addition to shahjapan's reduce you can use this syntax to flatten list.\n[legname for cow in listofcows for legname in cow.legnames]\n\n", "The name listofcows implies there may be, possibly in a distant future, several cows. Flattening a list of list with more than one item would be simply wrong.\nBut if the...
[ 10, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003524339_python.txt
Q: Python, creating a new variable from a dictionary? not as straightforward as it seems? I'm trying to create a new variable that will consist of an existing dictionary so that I can change things in this new dictionary without it affecting the old one. When I try this below, which I think would be the obvious way to do this, it still seems to edit my original dictionary when I make edits to the new one.. I have been searching for info on this but can't seem to find anything, any info is appreciated newdictionary = olddictionary A: You're creating a reference, instead of a copy. In order to make a complete copy and leave the original untouched, you need copy.deepcopy(). So: from copy import deepcopy dictionary_new = deepcopy(dictionary_old) Just using a = dict(b) or a = b.copy() will make a shallow copy and leave any lists in your dictionary as references to each other (so that although editing other items won't cause problems, editing the list in one dictionary will cause changes in the other dictionary, too). A: You are just giving making newdictionary point to the same reference olddictionary points to. See this page (it's about lists, but it is also applicable to dicts). Use .copy() instead (note: this creates a shallow copy): newdictionary = olddictionary.copy() To create a deep copy, you can use .deepcopy() from the copy module newdictionary = copy.deepcopy(olddictionary) Wikepedia : Shallow vs Deep Copy A: Assignment like that in Python just makes the newdictionary name refer to the same thing as olddictionary, as you've noticed. You can create a new dictionary with the dict() constructor: newdictionary = dict(olddictionary) Note that this makes a shallow copy. For deep copies, see the copy standard library module. A: newdictionary = dict(olddictionary.items()) This creates a new copy (more specifically, it feeds the contents of olddict as (key,value) pairs to dict, which constructs a new dictionary from (key,value) pairs). Edit: Oh yeah, copy - totally forgot it, that's the right way to do it. a = b just copies a reference, but not the object. A: You are merely creating another reference to the same dictionary. You need to make a copy: use one of the following (after checking in the docs what each does): new = dict(old) new = old.copy() import copy new = copy.copy(old) import copy new = copy.deepcopy(old) A: I think you need a deep copy for what you are asking. See here. It looks like dict.copy() does a shallow copy, which is what Rick does not want. from copy import deepcopy d = {} d['names'] = ['Alfred', 'Bertrand'] c = d.copy() dc = deepcopy(d)
Python, creating a new variable from a dictionary? not as straightforward as it seems?
I'm trying to create a new variable that will consist of an existing dictionary so that I can change things in this new dictionary without it affecting the old one. When I try this below, which I think would be the obvious way to do this, it still seems to edit my original dictionary when I make edits to the new one.. I have been searching for info on this but can't seem to find anything, any info is appreciated newdictionary = olddictionary
[ "You're creating a reference, instead of a copy. In order to make a complete copy and leave the original untouched, you need copy.deepcopy(). So:\nfrom copy import deepcopy\ndictionary_new = deepcopy(dictionary_old)\n\nJust using a = dict(b) or a = b.copy() will make a shallow copy and leave any lists in your dicti...
[ 7, 6, 3, 1, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003525453_dictionary_python.txt
Q: Simplifying complex class hierarchy With the goal of maximizing code reuse, I have created a rather complex class hierarchy for my Python code. It goes something like this: class ElectionMethod class IterativeMethod class SNTV ... class NonIterativeMethod class OrderDependent class CambridgeSTV ... class OrderIndependent class WIGM class ERS97STV ... class Recursive class MeekSTV ... Only the leaves of the class hierarchy are ever instantiated into objects. This does serve its purpose of maximizing code reuse, but the code itself is complicated (some classes have 20 or so methods) and given the many levels it can be time consuming to find where something is implemented. I've tried pulling out chunks of functionality and putting that functionality in a separate object, but I haven't found a good way to do this since nearly all the functionality depends on common data. I.e., I can move some code to a different object but it needs to refer back to the big complex hierarchy to get the data it needs so it isn't really encapsulation. Does anyone have any advice as to how to make this more manageable? A: If the only difficulty is finding where something is implemented, perhaps you don't need to refactor. Instead, look for extensions to your current editor, or switch to one that supports jumping-to-definitions. For example, emacs with ropemacs installed jumps to definitions when the the cursor is placed over an object name and Ctrl-c g is pressed. I'm sure there are similar tricks if you use vi/vim. A: Multi-methods might, depending on your architecture, be another valid solution to this sort of problem. The idea is to make the methods module level functions that can act on any class instance which it would be desirable to pass to them. Here's a another link that examines them as an alternative to multiple inheritance. It call's them generic functions but the idea is similar. It also discusses python's un-documented built in implementation of the concept. If you could move everything that doesn't have to do with setting or getting a particular instances values out of a class to module level functions and just have the class level code concerned with implementing a state-exposure/modification interface, then you might not even need multi-methods. A: This is classic problem, so there isn't universal answer ( otherwise it wasn't a problem ). But has several commonly used solutions. One of them - SOLID principles in design. So you haven't to search functionality trough the levels of your hierarchy, you can easily find or implement it in appropriate single-responsible code element. And if you need to access to some common data, you should create objects responsible for access to this data. Design by Contract and especially Dependency Injection technique generally needs for some framework support, so make search for suitable platform.
Simplifying complex class hierarchy
With the goal of maximizing code reuse, I have created a rather complex class hierarchy for my Python code. It goes something like this: class ElectionMethod class IterativeMethod class SNTV ... class NonIterativeMethod class OrderDependent class CambridgeSTV ... class OrderIndependent class WIGM class ERS97STV ... class Recursive class MeekSTV ... Only the leaves of the class hierarchy are ever instantiated into objects. This does serve its purpose of maximizing code reuse, but the code itself is complicated (some classes have 20 or so methods) and given the many levels it can be time consuming to find where something is implemented. I've tried pulling out chunks of functionality and putting that functionality in a separate object, but I haven't found a good way to do this since nearly all the functionality depends on common data. I.e., I can move some code to a different object but it needs to refer back to the big complex hierarchy to get the data it needs so it isn't really encapsulation. Does anyone have any advice as to how to make this more manageable?
[ "If the only difficulty is finding where something is implemented, perhaps you don't need to refactor. Instead, look for extensions to your current editor, or switch to one that supports jumping-to-definitions.\nFor example, emacs with ropemacs installed jumps to definitions when the the cursor is placed over an o...
[ 2, 2, 0 ]
[]
[]
[ "class_hierarchy", "python" ]
stackoverflow_0003524681_class_hierarchy_python.txt
Q: wxPython: switching text control focus on tab press I made a frame that asks the user to put in a bunch of information in several text control fields. How can I make it so that when you hit the 'tab' key your cursor moves to the next text control? A: If you put a wx.Panel as the only child of the ScrolledWindow and put the other widgets on the panel, then it should work automatically. You could also use ScrolledPanel instead.
wxPython: switching text control focus on tab press
I made a frame that asks the user to put in a bunch of information in several text control fields. How can I make it so that when you hit the 'tab' key your cursor moves to the next text control?
[ "If you put a wx.Panel as the only child of the ScrolledWindow and put the other widgets on the panel, then it should work automatically. You could also use ScrolledPanel instead.\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003525005_python_wxpython.txt
Q: passing R function arguments in rpy I have the following two lines of code that both run fine in both R and Python (via Rpy): [R] rcut = cut(vector, brks) [Python] rcut = r.cut(vector, brks) However, if I want to add the argument of include.lowest=TRUE, it runs as expected in R: [R] rcut = cut(vector, brks, include.lowest=TRUE) But it doesn't work in Rpy: [Python] rcut = r.cut(vector, brks, include_lowest="TRUE") which gives the following error: rpy.RPy_RException: Error in ok && include.lowest : invalid 'y' type in 'x && y' Do you know what might cause that and what should I do to make it work? Thx! A: I don't know rpy, but could it be due to using "TRUE" (a character) instead of TRUE (a logical)? EDIT: The rpy documentation seems to indicate using r.TRUE: http://rpy.sourceforge.net/rpy/doc/rpy_html/R-boolean-objects.html#R-boolean-objects A: I know nothing about Rpy, but I would guess it needs to be include_lowest=True (No quotes, True is a boolean value in python.)
passing R function arguments in rpy
I have the following two lines of code that both run fine in both R and Python (via Rpy): [R] rcut = cut(vector, brks) [Python] rcut = r.cut(vector, brks) However, if I want to add the argument of include.lowest=TRUE, it runs as expected in R: [R] rcut = cut(vector, brks, include.lowest=TRUE) But it doesn't work in Rpy: [Python] rcut = r.cut(vector, brks, include_lowest="TRUE") which gives the following error: rpy.RPy_RException: Error in ok && include.lowest : invalid 'y' type in 'x && y' Do you know what might cause that and what should I do to make it work? Thx!
[ "I don't know rpy, but could it be due to using \"TRUE\" (a character) instead of TRUE (a logical)?\nEDIT: The rpy documentation seems to indicate using r.TRUE:\nhttp://rpy.sourceforge.net/rpy/doc/rpy_html/R-boolean-objects.html#R-boolean-objects\n", "I know nothing about Rpy, but I would guess it needs to be inc...
[ 5, 1 ]
[]
[]
[ "python", "r", "rpy2" ]
stackoverflow_0003525658_python_r_rpy2.txt
Q: String concatenation produces incorrect output in Python? I have this code: filenames=["file1","FILE2","file3","fiLe4"] def alignfilenames(): #build a string that can be used to add labels to the R variables. #format goal: suffixes=c(".fileA",".fileB") filestring='suffixes=c(".' for filename in filenames: filestring=filestring+str(filename)+'",".' print filestring[:-3] #now delete the extra characters filestring=filestring[-1:-4] filestring=filestring+')' print "New String" print str(filestring) alignfilenames() I'm trying to get the string variable to look like this format: suffixes=c(".fileA",".fileB".....) but adding on the final parenthesis is not working. When I run this code as is, I get: suffixes=c(".file1",".FILE2",".file3",".fiLe4" New String ) Any idea what's going on or how to fix it? A: Does this do what you want? >>> filenames=["file1","FILE2","file3","fiLe4"] >>> c = "suffixes=c(%s)" % (",".join('".%s"' %f for f in filenames)) >>> c 'suffixes=c(".file1",".FILE2",".file3",".fiLe4")' Using a string.join is a much better way to add a common delimiter to a list of items. It negates the need to have to check for being on the last item before adding the delimiter, or in your case attempting to strip off the last one added. Also, you may want to look into List Comprehensions A: It looks like you might be trying to use python to write an R script, which can be a quick solution if you don't know how to do it in R. But in this case the R-only solution is actually rather simple: R> filenames= c("file1","FILE2","file3","fiLe4") R> suffixes <- paste(".", tolower(filenames), sep="") R> suffixes [1] ".file1" ".file2" ".file3" ".file4" R> A: What's going on is that this slicing returns an empty string filestring=filestring[-1:-4] Because the end is before the begin. Try the following on the command line: >>> a = "hello world" >>> a[-1:-4] '' The solution is to instead do filestring=filestring[:-4]+filestring[-1:] But I think what you actually wanted was to just drop the last three characters. filestring=filestring[:-3] The better solution is to use the join method of strings as sberry2A suggested
String concatenation produces incorrect output in Python?
I have this code: filenames=["file1","FILE2","file3","fiLe4"] def alignfilenames(): #build a string that can be used to add labels to the R variables. #format goal: suffixes=c(".fileA",".fileB") filestring='suffixes=c(".' for filename in filenames: filestring=filestring+str(filename)+'",".' print filestring[:-3] #now delete the extra characters filestring=filestring[-1:-4] filestring=filestring+')' print "New String" print str(filestring) alignfilenames() I'm trying to get the string variable to look like this format: suffixes=c(".fileA",".fileB".....) but adding on the final parenthesis is not working. When I run this code as is, I get: suffixes=c(".file1",".FILE2",".file3",".fiLe4" New String ) Any idea what's going on or how to fix it?
[ "Does this do what you want?\n>>> filenames=[\"file1\",\"FILE2\",\"file3\",\"fiLe4\"]\n>>> c = \"suffixes=c(%s)\" % (\",\".join('\".%s\"' %f for f in filenames))\n>>> c\n'suffixes=c(\".file1\",\".FILE2\",\".file3\",\".fiLe4\")'\n\nUsing a string.join is a much better way to add a common delimiter to a list of items...
[ 11, 2, 1 ]
[]
[]
[ "concatenation", "python", "r", "string" ]
stackoverflow_0003525659_concatenation_python_r_string.txt
Q: web2py list reference I am trying to get the list:reference field type to work for web2py, but for some reason I am getting an error. I am trying the example on http://web2py.com/book/default/chapter/06: db.define_table('tag',Field('name'),format='%(name)s') db.define_table('product', Field('name'), Field('tags','list:reference tag')) When I try this, I get the following error: Traceback (most recent call last): File "gluon/restricted.py", line 178, in restricted File "C:/web2py/applications/idd/models/db.py", line 93, in <module> File "gluon/sql.py", line 1309, in define_table File "gluon/sql.py", line 1664, in _create SyntaxError: Field: unknown field type: list:reference tag for tags This should be really simple, but is not working. Am I missing something that the book doesn't tell us about? A: You have an old web2py version. This feature was released in 1.83.2 the same time as the 3rd ed of the book.
web2py list reference
I am trying to get the list:reference field type to work for web2py, but for some reason I am getting an error. I am trying the example on http://web2py.com/book/default/chapter/06: db.define_table('tag',Field('name'),format='%(name)s') db.define_table('product', Field('name'), Field('tags','list:reference tag')) When I try this, I get the following error: Traceback (most recent call last): File "gluon/restricted.py", line 178, in restricted File "C:/web2py/applications/idd/models/db.py", line 93, in <module> File "gluon/sql.py", line 1309, in define_table File "gluon/sql.py", line 1664, in _create SyntaxError: Field: unknown field type: list:reference tag for tags This should be really simple, but is not working. Am I missing something that the book doesn't tell us about?
[ "You have an old web2py version. This feature was released in 1.83.2 the same time as the 3rd ed of the book.\n" ]
[ 2 ]
[]
[]
[ "foreign_key_relationship", "foreign_keys", "python", "web2py" ]
stackoverflow_0003524083_foreign_key_relationship_foreign_keys_python_web2py.txt
Q: Google app engine python problem I'm having a problem with the datastore trying to replicate a left join to find items from model a that don't have a matching relation in model b: class Page(db.Model): url = db.StringProperty(required=True) class Item(db.Model): page = db.ReferenceProperty(Page, required=True) name = db.StringProperty(required=True) I want to find any pages that don't have any associated items. A: You cannot query for items using a "property is null" filter. However, you can add a boolean property to Page that signals if it has items or not: class Page(db.Model): url = db.StringProperty(required=True) has_items = db.BooleanProperty(default=False) Then override the "put" method of Item to flip the flag. But you might want to encapsulate this logic in the Page model (maybe Page.add_item(self, *args, **kwargs)): class Item(db.Model): page = db.ReferenceProperty(Page, required=True) name = db.StringProperty(required=True) def put(self): if not self.page.has_items: self.page.has_items = True self.page.put() return db.put(self) Hence, the query for pages with no items would be: pages_with_no_items = Page.all().filter("has_items =", False) A: The datastore doesn't support joins, so you can't do this with a single query. You need to do a query for items in A, then for each, do another query to determine if it has any matching items in B.
Google app engine python problem
I'm having a problem with the datastore trying to replicate a left join to find items from model a that don't have a matching relation in model b: class Page(db.Model): url = db.StringProperty(required=True) class Item(db.Model): page = db.ReferenceProperty(Page, required=True) name = db.StringProperty(required=True) I want to find any pages that don't have any associated items.
[ "You cannot query for items using a \"property is null\" filter. However, you can add a boolean property to Page that signals if it has items or not:\nclass Page(db.Model):\n url = db.StringProperty(required=True)\n has_items = db.BooleanProperty(default=False)\n\nThen override the \"put\" method of Item to f...
[ 3, 1 ]
[ "Did you try it like :\nPage.all().filter(\"item_set = \", None)\n\nShould work.\n" ]
[ -1 ]
[ "google_app_engine", "python" ]
stackoverflow_0003521373_google_app_engine_python.txt
Q: Translating curl to python urllib2 Can someone please show me how to convert this curl call into call using python urllib2 curl -X POST -H "Content-Type:application/json" -d "{\"data\":{}}" -H "Authorization: GoogleLogin auth=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789...XYZ" https://www.googleapis.com/prediction/v1/training?data=${mybucket}%2F${mydata} A: Found it here: http://blog.notdot.net/2010/06/Trying-out-the-new-Prediction-API
Translating curl to python urllib2
Can someone please show me how to convert this curl call into call using python urllib2 curl -X POST -H "Content-Type:application/json" -d "{\"data\":{}}" -H "Authorization: GoogleLogin auth=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789...XYZ" https://www.googleapis.com/prediction/v1/training?data=${mybucket}%2F${mydata}
[ "Found it here:\nhttp://blog.notdot.net/2010/06/Trying-out-the-new-Prediction-API\n" ]
[ 1 ]
[]
[]
[ "curl", "libcurl", "python", "urllib", "urllib2" ]
stackoverflow_0003516250_curl_libcurl_python_urllib_urllib2.txt
Q: Are there any IDE's that support Python 3 syntax? I recently saw an announcement and article outlining the release of the first Python 3.0 release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax. A: Python 3 is just not that different from Python 2.x. In terms of syntax per se, things that will actually need to be handled differently by the parser, the only major change is in the replacement of the print statement with the print function. Most of the features of Python can be easily probed via introspection (online help, method completion, function signatures, etc.), so there's no reason why any Python IDE will require major changes to work with Python 3.0. I expect IDLE and SPE and the other open-source IDEs will be support it before the final release. A: Komodo 5 beta 1 was released in October 2008 and has initial support for Python 3 but I don't think I'd be using it for production code yet. Given that Python 3 is still a very early release candidate, you may have some trouble finding mature support in IDEs. A: PyDev for Eclipse does support 3.0. You can configure multiple interpreters in the plug-in settings. In the project properties you can set: Project type (Python, Jython, IronPython) Grammar version (2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 3.0). (PyDev version at time of writing: 1.4.7.) A: Can get PyDev. from http://pydev.sourceforge.net. Its a plugin for Eclipse and is more than handy. Not to mention benefits of the old and trusted Eclipse. A: Emacs + python.el continues to be better than anything else I've tried. A: Pyscripter is the PERFECT Python IDE on windows; it's compatible even with the newly released Python 3.1. A: Geany works with python 3 if you install it and then: sudo gedit /usr/share/geany/filetypes.python change the last 2 lines with: compiler=python3 -c "import py_compile; py_compile.compile('%f')" run_cmd=python3 "%f" A: I can say that at the time of posting this (Apr. 28 2009, version 0.8.4h) that SPE does not correctly handle some python3 syntax - specifically exception handling. For example, the follow code is flagged as an error (and irritatingly, is jumped to whenever the file is saved): except urllib.error.URLError as e: if hasattr(e, 'reason'): #...
Are there any IDE's that support Python 3 syntax?
I recently saw an announcement and article outlining the release of the first Python 3.0 release candidate. I was wondering whether there were any commercial, free, open source etc. IDE's that support its syntax.
[ "Python 3 is just not that different from Python 2.x. In terms of syntax per se, things that will actually need to be handled differently by the parser, the only major change is in the replacement of the print statement with the print function.\nMost of the features of Python can be easily probed via introspection...
[ 6, 5, 3, 1, 1, 1, 1, 0 ]
[]
[]
[ "ide", "python", "python_3.x", "syntax" ]
stackoverflow_0000207763_ide_python_python_3.x_syntax.txt
Q: Python variable resolving Given the following code: a = 0 def foo(): # global a a += 1 foo() When run, Python complains: UnboundLocalError: local variable 'a' referenced before assignment However, when it's a dictionary... a = {} def foo(): a['bar'] = 0 foo() The thing runs just fine... Anyone know why we can reference a in the 2nd chunk of code, but not the 1st? A: The difference is that in the first example you are assigning to a which creates a new local name a that hides the global a. In the second example you are not making an assignment to a so the global a is used. This is covered in the documentation. A special quirk of Python is that – if no global statement is in effect – assignments to names always go into the innermost scope. A: The question is one of update. You cannot update a because it is not a variable in your function's local namespace. The update-in-place assignment operation fails to update a in place. Interestingly, a = a + 1 also fails. Python generates slightly optimized code for these kind of statements. It uses a "LOAD_FAST" instruction. 2 0 LOAD_FAST 0 (a) 3 LOAD_CONST 1 (1) 6 INPLACE_ADD 7 STORE_FAST 0 (a) 10 LOAD_CONST 0 (None) 13 RETURN_VALUE Note that the use of a on left and right side of the equal sign leads to this optimization. You can, however, access a because Python will search local and global namespaces for you. Since a does not appear on the left side of an assignment statement, a different kind of access is used, "LOAD_GLOBAL". 2 0 LOAD_CONST 1 (0) 3 LOAD_GLOBAL 0 (a) 6 LOAD_CONST 2 ('bar') 9 STORE_SUBSCR 10 LOAD_CONST 0 (None) 13 RETURN_VALUE A: a += 1 is equivalent to a = a + 1. By assigning to variable a, it is made local. The value you attempt to assign a + 1 fails because a hasn't been bound yet. A: That's a very common Python gotcha: if you assign to a variable inside a function (as you do, with +=), anywhere at all (not necessarily before you use it some other way), it doesn't use the global one. However, since what you're doing is effectively "a = a + 1", you're trying to access a (on the right-hand side of the expression) before assigning to it. Try using global a at the beginning of your function (but beware that you'll overwrite the global a value). On your second example, you're not assigning the the variable a, but only to one of its items. So the global dict a is used.
Python variable resolving
Given the following code: a = 0 def foo(): # global a a += 1 foo() When run, Python complains: UnboundLocalError: local variable 'a' referenced before assignment However, when it's a dictionary... a = {} def foo(): a['bar'] = 0 foo() The thing runs just fine... Anyone know why we can reference a in the 2nd chunk of code, but not the 1st?
[ "The difference is that in the first example you are assigning to a which creates a new local name a that hides the global a.\nIn the second example you are not making an assignment to a so the global a is used.\nThis is covered in the documentation.\n\nA special quirk of Python is that – if no global statement is ...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003525985_python.txt
Q: Python - why is it not reading my variables? I'm a python newbie and I don't understand why it won't read my IP and ADDR variables in the function dns.zone.query(IP, ADDR)??? import dns.query import dns.zone import sys IP = sys.stdin.readline() ADDR = sys.stdin.readline() z = dns.zone.from_xfr(dns.query.xfr(IP , ADDR)) names = z.nodes.keys() names.sort() for n in names: print z[n].to_text(n) It works when I pass an actual IP and Domain, but not with the variables... I don't get what's wrong? A: readline() will include a trailing newline. You can use sys.stdin.readline().strip() A: Try sys.stdin.readline().strip(). You need to remove the newlines. A: I would try with: IP = sys.stdin.readline().strip() ADDR = sys.stdin.readline().strip() Add some prints after the variables to debug it: print '_%s_' % IP print '_%s_' % ADDR
Python - why is it not reading my variables?
I'm a python newbie and I don't understand why it won't read my IP and ADDR variables in the function dns.zone.query(IP, ADDR)??? import dns.query import dns.zone import sys IP = sys.stdin.readline() ADDR = sys.stdin.readline() z = dns.zone.from_xfr(dns.query.xfr(IP , ADDR)) names = z.nodes.keys() names.sort() for n in names: print z[n].to_text(n) It works when I pass an actual IP and Domain, but not with the variables... I don't get what's wrong?
[ "readline() will include a trailing newline. You can use sys.stdin.readline().strip()\n", "Try sys.stdin.readline().strip(). You need to remove the newlines.\n", "I would try with:\nIP = sys.stdin.readline().strip()\nADDR = sys.stdin.readline().strip()\n\nAdd some prints after the variables to debug it:\nprint...
[ 6, 2, 2 ]
[]
[]
[ "function", "python", "variables" ]
stackoverflow_0003526065_function_python_variables.txt
Q: String Division in Python I have a list of strings that all follow a format of parts of the name divided by underscores. Here is the format: string="somethingX_somethingY_one_two" What I want to know how to do it extract "one_two" from each string in the list and rebuild the list so that each entry only has "somethingX_somethingY". I know that in C, there is a strtok function that is useful for splitting into tokens, but I'm not sure if there is a method like that or a strategy to get that same effect in Python. Help me please? A: You can use split and a list comprehension: l = ['_'.join(s.split('_')[:2]) for s in l] A: If you're literally trying to remove "_one_two" from the end of the strings, then you can do this: tail_len = len("_one_two") strs = [s[:-tail_len] for s in strs] If you want to remove the last two underscore-separated components, then you can do this: strs = ["_".join(s.split("_")[:-2]) for s in strs] If neither of these is what you want, then let update the question with more details. A: I think this does what you're asking for. s = "somethingX_somethingY_one_two" splitted = s.split( "_" ) splitted = [ x for x in splitted if "something" in x ] print "_".join( splitted )
String Division in Python
I have a list of strings that all follow a format of parts of the name divided by underscores. Here is the format: string="somethingX_somethingY_one_two" What I want to know how to do it extract "one_two" from each string in the list and rebuild the list so that each entry only has "somethingX_somethingY". I know that in C, there is a strtok function that is useful for splitting into tokens, but I'm not sure if there is a method like that or a strategy to get that same effect in Python. Help me please?
[ "You can use split and a list comprehension:\nl = ['_'.join(s.split('_')[:2]) for s in l]\n\n", "If you're literally trying to remove \"_one_two\" from the end of the strings, then you can do this:\ntail_len = len(\"_one_two\")\nstrs = [s[:-tail_len] for s in strs]\n\nIf you want to remove the last two underscore...
[ 6, 3, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003526098_python_string.txt
Q: When should I submit my Django form's results? The contents of my form must be submitted to another application server for validation and execution (specifically, I call a RESTful web service with the posted values in the form). The service will either return a 200 SUCCESS or a 400/409 error with a body that describes the exact field errors. When should I do this submission? Should I do it in the view: if form.is_valid: result = submit_to_service(POST) if result.code in (400, 409): somehow_set_errors_on_the_form(form) else: go_on... Or in the Form.clean method? def clean(self): result = submit_to_service(POST) if result.code in (400, 409): for field in result.errors: self._errors[field].append(result.errors[field]) else: pass Which of these is clearer? A: validation and execution No execution or stateful changes in the form clean(). Please. The form's clean() should only mess with data on the form, not anywhere else. If there is a stateful change, it must be in a view function inside a non-GET request handler. A: I usually encapsulate these type of logic in the form. Since you use the form to validate the data you also use it to send the data. This makes sense because the form already knows about the data and its types etc (it has the cleaned_data dictionary). But processing data and changing state of your application should not live directly inside your validation logic (e.g. in your clean method). You should put it in an extra method of your form - like ModelForm is doing it with the save() method. So my suggestion is to have an extra method named save() (if the method actually saves your processing to the REST service) or post_result() or something similar that fits better. Here is an example: # forms.py class ValidateDataForm(forms.Form): ... def clean(self): # validation logic def save(self): post_results_to_service(self.cleaned_data) # views.py def view(request): if request.method == 'POST': form = ValidateDataForm(request.POST) if form.is_valid(): form.save() else: form = ValidateDataForm() The above assumes that the REST service is changing state for your application, e.g. it implements some business logic. If this is not the case and you only use the service as validation for the input data on your form - and use the form data then for something different - I would suggest something different. In this case the code should go into the clean() method like you suggested in your second code example.
When should I submit my Django form's results?
The contents of my form must be submitted to another application server for validation and execution (specifically, I call a RESTful web service with the posted values in the form). The service will either return a 200 SUCCESS or a 400/409 error with a body that describes the exact field errors. When should I do this submission? Should I do it in the view: if form.is_valid: result = submit_to_service(POST) if result.code in (400, 409): somehow_set_errors_on_the_form(form) else: go_on... Or in the Form.clean method? def clean(self): result = submit_to_service(POST) if result.code in (400, 409): for field in result.errors: self._errors[field].append(result.errors[field]) else: pass Which of these is clearer?
[ "\nvalidation and execution \n\nNo execution or stateful changes in the form clean(). Please. The form's clean() should only mess with data on the form, not anywhere else.\nIf there is a stateful change, it must be in a view function inside a non-GET request handler.\n", "I usually encapsulate these type of log...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003525956_django_python.txt
Q: Pydev can't find matplotlib modules I just installed matplotlib on my windows 7 Python 2.6.5 machine with the win32 installer . I've tried some examples from the matplotlib site to test the installation, under Idle everthing works fine but Pydev 1.9 (Eclipse 3.6) cant find any of the sub modules. e.g import matplotlib doesn't cause any errors but from matplotlib.path import Path throws ImportError: No module named path Ive added the matplotlib path to the system PYTHONPATH in eclipse, is there anything else I need to do? from pylab import * import numpy as np from matplotlib.transforms import Bbox from matplotlib.path import Path from matplotlib.patches import Rectangle rect = Rectangle((-1, -1), 2, 2, facecolor="#aaaaaa") gca().add_patch(rect) bbox = Bbox.from_bounds(-1, -1, 2, 2) for i in range(12): vertices = (np.random.random((4, 2)) - 0.5) * 6.0 vertices = np.ma.masked_array(vertices, [[False, False], [True, True], [False, False], [False, False]]) path = Path(vertices) if path.intersects_bbox(bbox): color = 'r' else: color = 'b' plot(vertices[:,0], vertices[:,1], color=color) show() Traceback (most recent call last): File "I:\My Documents\Programming\Python\Eclipse Projects\test\src\matplotlib.py", line 1, in <module> from pylab import * File "C:\Python26\lib\site-packages\pylab.py", line 1, in <module> from matplotlib.pylab import * File "I:\My Documents\Programming\Python\Eclipse Projects\test\src\matplotlib.py", line 3, in <module> from matplotlib.transforms import Bbox ImportError: No module named transforms A: Seems that your file is called matplotlib.py. Then it's clear why this doesn't work: The current directory is always prepended to the system path, and your file will be found first. Since it doesn't contain a transforms submodule, the import will fail. import matplotlib itself works because there is a module called matplotlib—your file called matplotlib.py. Simply rename the file.
Pydev can't find matplotlib modules
I just installed matplotlib on my windows 7 Python 2.6.5 machine with the win32 installer . I've tried some examples from the matplotlib site to test the installation, under Idle everthing works fine but Pydev 1.9 (Eclipse 3.6) cant find any of the sub modules. e.g import matplotlib doesn't cause any errors but from matplotlib.path import Path throws ImportError: No module named path Ive added the matplotlib path to the system PYTHONPATH in eclipse, is there anything else I need to do? from pylab import * import numpy as np from matplotlib.transforms import Bbox from matplotlib.path import Path from matplotlib.patches import Rectangle rect = Rectangle((-1, -1), 2, 2, facecolor="#aaaaaa") gca().add_patch(rect) bbox = Bbox.from_bounds(-1, -1, 2, 2) for i in range(12): vertices = (np.random.random((4, 2)) - 0.5) * 6.0 vertices = np.ma.masked_array(vertices, [[False, False], [True, True], [False, False], [False, False]]) path = Path(vertices) if path.intersects_bbox(bbox): color = 'r' else: color = 'b' plot(vertices[:,0], vertices[:,1], color=color) show() Traceback (most recent call last): File "I:\My Documents\Programming\Python\Eclipse Projects\test\src\matplotlib.py", line 1, in <module> from pylab import * File "C:\Python26\lib\site-packages\pylab.py", line 1, in <module> from matplotlib.pylab import * File "I:\My Documents\Programming\Python\Eclipse Projects\test\src\matplotlib.py", line 3, in <module> from matplotlib.transforms import Bbox ImportError: No module named transforms
[ "Seems that your file is called matplotlib.py. Then it's clear why this doesn't work: The current directory is always prepended to the system path, and your file will be found first. Since it doesn't contain a transforms submodule, the import will fail. import matplotlib itself works because there is a module calle...
[ 4 ]
[]
[]
[ "eclipse", "importerror", "matplotlib", "pydev", "python" ]
stackoverflow_0003526389_eclipse_importerror_matplotlib_pydev_python.txt
Q: Substring Comparison in python If i have List PhoneDirectory Eg: ['John:009878788677' , 'Jefrey:67654654645' , 'Maria:8787677766'] Which is the function that can be use to compare the Presence of Substring (Eg: Joh) in each entry in the List . I have tried using if(PhoneDirectory.find(Joh) != -1) but it doesnt work kindly Help.. A: If you want to check each entry separately: for entry in PhoneDirectory: if 'John' in entry: ... If you just want to know if any entry satisfies the condition and don't care which one: if any('John' in entry for entry in PhoneDirectory): ... Note that any will do no "wasted" work -- it will return True as soon as it finds any one entry meeting the condition (if no entries meet the condition, it does have to check every single one of them to confirm that, of course, and then returns False). A: if any(entry.startswith('John:') in entry for entry in PhoneDirectory) But I would prepare something with two elements as you list of strings is not well suited to task: PhoneList = ['John:009878788677' , 'Jefrey:67654654645' , 'Maria:8787677766'] numbers = { a:b for item in PhoneList for a,_,b in (item.partition(':'),) } print numbers print "%s's number is %s." % ( 'John', numbers['John'] ) A: Since no one has recommended this yet, I would do: all_johns = [p for p in PhoneDirectory if 'Joh' in p] A: You can do a split on ":" and look for occurrences of what you are looking for in the first element of the resulting array. dir = ['John:009878788677' , 'Jefrey:67654654645' , 'Maria:8787677766']; for a in dir: values = a.split(":") if values[0] == "John": print("John's number is %s" % (values[1])) A: If performance counts for this task use some SuffixTree implementation. Or just make any DBMS engine do the indexing job.
Substring Comparison in python
If i have List PhoneDirectory Eg: ['John:009878788677' , 'Jefrey:67654654645' , 'Maria:8787677766'] Which is the function that can be use to compare the Presence of Substring (Eg: Joh) in each entry in the List . I have tried using if(PhoneDirectory.find(Joh) != -1) but it doesnt work kindly Help..
[ "If you want to check each entry separately:\nfor entry in PhoneDirectory:\n if 'John' in entry: ...\n\nIf you just want to know if any entry satisfies the condition and don't care which one:\nif any('John' in entry for entry in PhoneDirectory):\n ...\n\nNote that any will do no \"wasted\" work -- it will ret...
[ 19, 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003524611_python.txt