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: problem when zooming pictures in wxpython I need to draw over image (to comment over it) in a scrolled panel. I'm having troubles with it since it doesn't behave right when I zoom it in or out. it stops drawing , and then it shows it after a while in a wrong place. right in the upper left corner of the window. and doesn't draw lines correctly . below is the code for the (onLeftDown) function (the button that should draw). the right button event (zoom in). hope it is clear enough. do you guys have any idea what is going on, and how do I solve it? thanks in advance def OnLeftButtonEvent(self, event): self.curLine = [] self.x, self.y = event.GetPositionTuple() self.CaptureMouse() def OnMotion(self, event): if self.HasCapture() and event.Dragging(): dc = wx.BufferedDC(None,self.buffer) dc.SetUserScale(self.scale,self.scale) # to zoom in and out ( increases whenever someone presses the right mouse button dc.BeginDrawing() dc.SetPen(wx.Pen(wx.BLUE, 3)) coords = (self.x, self.y) + event.GetPositionTuple() self.curLine.append(coords) dc.DrawLine(*coords) self.x, self.y = event.GetPositionTuple() self.SetXY(event) dc.EndDrawing() def OnRightDown(self,event): print self.scale self.scale=self.scale*2.0 self.initDrawing() self.maxHeight=self.maxHeight*2 self.maxWidth=self.maxWidth*2 A: You need to scale mouse co-ordinates so that it is in sync with scaling of drawing, so if you are using userScale=2, mouse at x=10 will end up at 20 . so you need to do this sx, sy = x/cur_scale, y/cur_scale You also need to be do drawing in EVT_PAINT event not on onmotion, on motion you just need to refresh window and paint event should take care of what you want to draw.
problem when zooming pictures in wxpython
I need to draw over image (to comment over it) in a scrolled panel. I'm having troubles with it since it doesn't behave right when I zoom it in or out. it stops drawing , and then it shows it after a while in a wrong place. right in the upper left corner of the window. and doesn't draw lines correctly . below is the code for the (onLeftDown) function (the button that should draw). the right button event (zoom in). hope it is clear enough. do you guys have any idea what is going on, and how do I solve it? thanks in advance def OnLeftButtonEvent(self, event): self.curLine = [] self.x, self.y = event.GetPositionTuple() self.CaptureMouse() def OnMotion(self, event): if self.HasCapture() and event.Dragging(): dc = wx.BufferedDC(None,self.buffer) dc.SetUserScale(self.scale,self.scale) # to zoom in and out ( increases whenever someone presses the right mouse button dc.BeginDrawing() dc.SetPen(wx.Pen(wx.BLUE, 3)) coords = (self.x, self.y) + event.GetPositionTuple() self.curLine.append(coords) dc.DrawLine(*coords) self.x, self.y = event.GetPositionTuple() self.SetXY(event) dc.EndDrawing() def OnRightDown(self,event): print self.scale self.scale=self.scale*2.0 self.initDrawing() self.maxHeight=self.maxHeight*2 self.maxWidth=self.maxWidth*2
[ "You need to scale mouse co-ordinates so that it is in sync with scaling of drawing, so if you are using userScale=2, mouse at x=10 will end up at 20 .\nso you need to do this\nsx, sy = x/cur_scale, y/cur_scale\n\nYou also need to be do drawing in EVT_PAINT event not on onmotion, on motion you just need to refresh window and paint event should take care of what you want to draw.\n" ]
[ 3 ]
[]
[]
[ "drawing", "image", "python", "wxpython", "zooming" ]
stackoverflow_0002041418_drawing_image_python_wxpython_zooming.txt
Q: Django: information leakage problem when using @login_required and setting LOGIN_URL I found a form of information leakage when using the @login_required decorator and setting the LOGIN_URL variable. I have a site that requires a mandatory login for all content. The problem is that you get redirected to the login page with the next variable set when it's a existing page. So when not logged in and asking for: http://localhost:8000/validurl/ You see this: http://localhost:8000/login/?next=/validurl/ And when requesting an non existing page: http://localhost:8000/faultyurl/ You see this: http://localhost:8000/login/ Which reveals some information that I dont want. I thought of overriding the login method, forcing the next to empty and calling 'super' on this subclassed method. An additional problem is that some of my tests fail without the LOGIN_URL set. they redirect to '/accounts/login/' instead of '/login/'. Hence why I'd like to use the LOGIN_URL but disable the 'auto next' feature. Anybody that can shed some light on the subject? Thanx a lot. Gerard. A: You can include this line as the last pattern in your urls.py file. It will re-route urls that do not match any other pattern to the login page. urlpatterns = patterns('', ... (r'^(?P<path>.+)$', 'django.views.generic.simple.redirect_to', { 'url': '/login/?next=/%(path)s', 'permanent': False }), ) EDIT: To keep raising 404 pages to authenticated users, do the following: from django.http import Http404, HttpResponseRedirect def fake_redirect(request, path): if request.user.is_authenticated: raise Http404() else: return HttpResponseRedirect('/login/?next=/%s' % path) urlpatterns = patterns('', ... (r'^(?P<path>.+)$', fake_redirect), )
Django: information leakage problem when using @login_required and setting LOGIN_URL
I found a form of information leakage when using the @login_required decorator and setting the LOGIN_URL variable. I have a site that requires a mandatory login for all content. The problem is that you get redirected to the login page with the next variable set when it's a existing page. So when not logged in and asking for: http://localhost:8000/validurl/ You see this: http://localhost:8000/login/?next=/validurl/ And when requesting an non existing page: http://localhost:8000/faultyurl/ You see this: http://localhost:8000/login/ Which reveals some information that I dont want. I thought of overriding the login method, forcing the next to empty and calling 'super' on this subclassed method. An additional problem is that some of my tests fail without the LOGIN_URL set. they redirect to '/accounts/login/' instead of '/login/'. Hence why I'd like to use the LOGIN_URL but disable the 'auto next' feature. Anybody that can shed some light on the subject? Thanx a lot. Gerard.
[ "You can include this line as the last pattern in your urls.py file. It will re-route urls that do not match any other pattern to the login page.\nurlpatterns = patterns('',\n\n ...\n\n (r'^(?P<path>.+)$', 'django.views.generic.simple.redirect_to', {\n 'url': '/login/?next=/%(path)s', \n 'permanent': False\n }),\n)\n\nEDIT: To keep raising 404 pages to authenticated users, do the following:\nfrom django.http import Http404, HttpResponseRedirect\ndef fake_redirect(request, path):\n if request.user.is_authenticated:\n raise Http404()\n else:\n return HttpResponseRedirect('/login/?next=/%s' % path)\n\nurlpatterns = patterns('',\n\n ...\n\n (r'^(?P<path>.+)$', fake_redirect),\n)\n\n" ]
[ 5 ]
[]
[]
[ "authentication", "django", "django_urls", "python" ]
stackoverflow_0002042201_authentication_django_django_urls_python.txt
Q: How to copy a file from a network share to local disk with variables? If I use the following line: shutil.copyfile(r"\\mynetworkshare\myfile.txt","C:\TEMP\myfile.txt") everything works fine. However, what I can't seem to figure out is how to use a variable with the network share path, because I need the 'r' (relative?) flag. The end result I would imagine would be something like: source_path = "\\mynetworkshare" dest_path = "C:\TEMP" file_name = "\\myfile.txt" shutil.copyfile(r source_path + file_name,dest_path + file_name) But I have had no luck with different variations of this approach. A: The r used in your first code example is making the string a "raw" string. In this example, that means the string will see the backslashes and not try to use them to escape \\ to just \. To get your second code sample working, you'd use the r on the strings, and not in the copyfile command: source_path = r"\\mynetworkshare" dest_path = r"C:\TEMP" file_name = "\\myfile.txt" shutil.copyfile(source_path + file_name, dest_path + file_name) A: The r is for "raw string", not for relative. When you don't prefix your string with r, Python will treat the backslash "\" as an escape character. So when your string contains backslashes, you either have to put an r before it, or put two backslashes for each single one you want to appear. >>> r"\\myfile" == "\\\\myfile" True A: This looks like an escaping issue - as balpha says, the r makes the \ character a literal, rather than a control sequence. Have you tried: source_path = r"\\mynetworkshare" dest_path = r"C:\TEMP" filename = r"\my_file.txt" shutil.copyfile(source_path + filename, dest_path + filename) (Using an interactive python session, you can see the following: >>> source_path = r"\\mynetworkshare" >>> dest_path = r"C:\TEMP" >>> filename = r"\my_file.txt" >>> print (source_path + filename) \\mynetworkshare\my_file.txt >>> print (dest_path + filename) C:\TEMP\my_file.txt A: From your example paths, it's clear that we are discussing the Windows OS. Python implementation on this OS use a common (C) runtime library that accepts forward slashes as equivalent to back-slashes. This way you can avoid escape char issues. source_path = "//mynetworkshare" dest_path = "C:/TEMP" file_name = "/myfile.txt" Note that filename composition is handled by os.path.join: Join one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) inserted between components, unless path2 is empty. Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo. import os shutil.copyfile(os.path.join(source_path, file_name), os.path.join(dest_path, file_name))
How to copy a file from a network share to local disk with variables?
If I use the following line: shutil.copyfile(r"\\mynetworkshare\myfile.txt","C:\TEMP\myfile.txt") everything works fine. However, what I can't seem to figure out is how to use a variable with the network share path, because I need the 'r' (relative?) flag. The end result I would imagine would be something like: source_path = "\\mynetworkshare" dest_path = "C:\TEMP" file_name = "\\myfile.txt" shutil.copyfile(r source_path + file_name,dest_path + file_name) But I have had no luck with different variations of this approach.
[ "The r used in your first code example is making the string a \"raw\" string. In this example, that means the string will see the backslashes and not try to use them to escape \\\\ to just \\.\nTo get your second code sample working, you'd use the r on the strings, and not in the copyfile command:\nsource_path = r\"\\\\mynetworkshare\"\ndest_path = r\"C:\\TEMP\"\nfile_name = \"\\\\myfile.txt\"\n\nshutil.copyfile(source_path + file_name, dest_path + file_name)\n\n", "The r is for \"raw string\", not for relative. When you don't prefix your string with r, Python will treat the backslash \"\\\" as an escape character.\nSo when your string contains backslashes, you either have to put an r before it, or put two backslashes for each single one you want to appear.\n>>> r\"\\\\myfile\" == \"\\\\\\\\myfile\"\nTrue\n\n", "This looks like an escaping issue - as balpha says, the r makes the \\ character a literal, rather than a control sequence. Have you tried:\nsource_path = r\"\\\\mynetworkshare\"\ndest_path = r\"C:\\TEMP\"\nfilename = r\"\\my_file.txt\"\n\nshutil.copyfile(source_path + filename, dest_path + filename)\n\n(Using an interactive python session, you can see the following:\n>>> source_path = r\"\\\\mynetworkshare\"\n>>> dest_path = r\"C:\\TEMP\"\n>>> filename = r\"\\my_file.txt\"\n>>> print (source_path + filename)\n\\\\mynetworkshare\\my_file.txt\n>>> print (dest_path + filename)\nC:\\TEMP\\my_file.txt\n\n", "From your example paths, it's clear that we are discussing the Windows OS.\nPython implementation on this OS use a common (C) runtime library that accepts forward slashes as equivalent to back-slashes. This way you can avoid escape char issues.\nsource_path = \"//mynetworkshare\"\ndest_path = \"C:/TEMP\"\nfile_name = \"/myfile.txt\"\n\nNote that filename composition is handled by os.path.join:\n\nJoin one or more path components intelligently. If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues. The return value is the concatenation of path1, and optionally path2, etc., with exactly one directory separator (os.sep) inserted between components, unless path2 is empty. Note that on Windows, since there is a current directory for each drive, os.path.join(\"c:\", \"foo\") represents a path relative to the current directory on drive C: (c:foo), not c:\\foo.\n\nimport os\nshutil.copyfile(os.path.join(source_path, file_name),\n os.path.join(dest_path, file_name))\n\n" ]
[ 28, 5, 3, 1 ]
[]
[]
[ "network_programming", "python", "share" ]
stackoverflow_0002042342_network_programming_python_share.txt
Q: A more pythonic way of iterating a list while excluding an element each iteration I have the following code: items = ["one", "two", "three"] for i in range(0, len(items)): for index, element in enumerate(items): if index != i: # do something with element Basically I want to exclude every element once and iterate the rest. So for the list I have above, I'd like the following iterations: "two", "three" "one", "three" "one", "two" The code I've written now seems a little C++-ish, is there a better solution? (I do not want to hold all possible lists in a variable) EDIT: I didn't state this but the lists size isn't necessarily 3. It can be of any size. EDIT 2: It seems there's another misunderstanding: if I have a list of N, then I want N lists of size N-1, each missing an element from the original list. EDIT 3: A list with 4 items, should give this result: 1, 2, 3 1, 3, 4 1, 2, 4 2, 3, 4 A: Although upvoted like crazy, my first solution wasn't what the OP wanted, which is N lists, each missing exactly one of the N original elements: >>> from itertools import combinations >>> L = ["one", "two", "three", "four"] >>> for R in combinations(L, len(L) - 1): ... print " and ".join(R) ... one and two and three one and two and four one and three and four two and three and four See the revision history for the source of the discussion below. A: [items[:i]+items[i+1:] for i in range(len(items))] in py2.x use xrange. obviously, slicing all the time on a big sequence is not very efficient, but it's fine for short ones. Better option would be using itertools.combinations: >>> for a in itertools.combinations(items, len(items)-1): print(a) ('one', 'two') ('one', 'three') ('two', 'three') A: As roger predicted, an answer which doesn't really improve the existing code :) a = ["one", "two", "three"] for i in range(0, len(a)): print [val[1] for val in enumerate(a) if val[0] != i]
A more pythonic way of iterating a list while excluding an element each iteration
I have the following code: items = ["one", "two", "three"] for i in range(0, len(items)): for index, element in enumerate(items): if index != i: # do something with element Basically I want to exclude every element once and iterate the rest. So for the list I have above, I'd like the following iterations: "two", "three" "one", "three" "one", "two" The code I've written now seems a little C++-ish, is there a better solution? (I do not want to hold all possible lists in a variable) EDIT: I didn't state this but the lists size isn't necessarily 3. It can be of any size. EDIT 2: It seems there's another misunderstanding: if I have a list of N, then I want N lists of size N-1, each missing an element from the original list. EDIT 3: A list with 4 items, should give this result: 1, 2, 3 1, 3, 4 1, 2, 4 2, 3, 4
[ "Although upvoted like crazy, my first solution wasn't what the OP wanted, which is\nN lists, each missing exactly one of the N original elements:\n>>> from itertools import combinations\n>>> L = [\"one\", \"two\", \"three\", \"four\"]\n>>> for R in combinations(L, len(L) - 1):\n... print \" and \".join(R)\n...\none and two and three\none and two and four\none and three and four\ntwo and three and four\n\nSee the revision history for the source of the discussion below.\n", "[items[:i]+items[i+1:] for i in range(len(items))]\n\nin py2.x use xrange. obviously, slicing all the time on a big sequence is not very efficient, but it's fine for short ones. Better option would be using itertools.combinations:\n>>> for a in itertools.combinations(items, len(items)-1):\n print(a)\n\n('one', 'two')\n('one', 'three')\n('two', 'three')\n\n", "As roger predicted, an answer which doesn't really improve the existing code :)\na = [\"one\", \"two\", \"three\"]\nfor i in range(0, len(a)):\n print [val[1] for val in enumerate(a) if val[0] != i]\n\n" ]
[ 17, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002042363_python.txt
Q: How can I fix ImportError: No module named numpy? I am trying to run a python script which has the following statements: import random as RD import pylab as PL import scipy as SP import networkx as NX Where can I download these packages? I have installed these packages and I get the following error when I run my code I am getting the following error when I run the code Traceback (most recent call last): File "C:\Documents and Settings\hplabs\Desktop\Dushyant\networkdemo.py", line 7, in <module> import pylab as PL File "C:\Python26\lib\site-packages\pylab.py", line 1, in <module> from matplotlib.pylab import * File "C:\Python26\lib\site-packages\matplotlib\__init__.py", line 129, in <module> from rcsetup import defaultParams, validate_backend, validate_toolbar File "C:\Python26\lib\site-packages\matplotlib\rcsetup.py", line 19, in <module> from matplotlib.colors import is_color_like File "C:\Python26\lib\site-packages\matplotlib\colors.py", line 52, in <module> import numpy as np ImportError: No module named numpy A: 'random' is shipped with the standard library pylab and scipy are part of SciPy Networkx is available here A: Here's a link to the non standard libraries. random is part of the standard library. matplotlib scipy networkX numpy (reuired by scipy) A: random is a standard python library module, no need to install that. pylab and scipy can be found on the SciPy site networkx also has a site BTW: These are all easily found using google.com A: When installing Scipy, you also need to install numpy which it depends on. See here. You are getting the error because numpy is not installed on your system.
How can I fix ImportError: No module named numpy?
I am trying to run a python script which has the following statements: import random as RD import pylab as PL import scipy as SP import networkx as NX Where can I download these packages? I have installed these packages and I get the following error when I run my code I am getting the following error when I run the code Traceback (most recent call last): File "C:\Documents and Settings\hplabs\Desktop\Dushyant\networkdemo.py", line 7, in <module> import pylab as PL File "C:\Python26\lib\site-packages\pylab.py", line 1, in <module> from matplotlib.pylab import * File "C:\Python26\lib\site-packages\matplotlib\__init__.py", line 129, in <module> from rcsetup import defaultParams, validate_backend, validate_toolbar File "C:\Python26\lib\site-packages\matplotlib\rcsetup.py", line 19, in <module> from matplotlib.colors import is_color_like File "C:\Python26\lib\site-packages\matplotlib\colors.py", line 52, in <module> import numpy as np ImportError: No module named numpy
[ "\n'random' is shipped with the standard library\npylab and scipy are part of SciPy\nNetworkx is available here\n\n", "Here's a link to the non standard libraries. random is part of the standard library.\nmatplotlib\nscipy\nnetworkX\nnumpy (reuired by scipy)\n", "random is a standard python library module, no need to install that.\npylab and scipy can be found on the SciPy site\nnetworkx also has a site\nBTW: These are all easily found using google.com\n", "When installing Scipy, you also need to install numpy which it depends on. See here. You are getting the error because numpy is not installed on your system.\n" ]
[ 2, 2, 2, 1 ]
[]
[]
[ "matplotlib", "networkx", "python", "random", "scipy" ]
stackoverflow_0002040531_matplotlib_networkx_python_random_scipy.txt
Q: Python Sockets - Creating a message format I have built a Python server to which various clients can connect, and I need to set a predefined series of messages from clients to the server - For example the client passes in a name to the server when it first connects. I was wondering what the best way to approach this is? How should I build a simple protocol for their communication? Should the messages start with a specific set of bytes to mark them out as part of this protocol, then contain some sort of message id? Any suggestions or further reading appreciated. A: Depending on the requirements, you might want to consider using JSON: use "newline" terminated strings with JSON encoding. The transport protocol could be HTTP: with this, you could have access to all the "connection related" facilities (e.g. status codes) and have JSON encoded payload. The advantages of using JSON over HTTP: human readable (debugging etc.) libraries available for all languages/platforms cross-platform browser debuggable (to some extent) Of course, there are many other ways to skin this cat but the time to working prototype using this approach is very low. This is worth considering if your requirements (which aren't very detailed here) can be met. A: First, you need to decide whether you want your protocol to be human readable (much more overhead) or binary. If the first, you probably want to use regular expressions to decode the messages. For this, use the python module re. If the latter, the module struct is your friend. Second, if you are building a protocol that is somehow stateful (e.g. first we do a handshake, then we transfer data, then we check checksums and say goodbye) you probably want to create a some sort of FSM to track the state. Third, if protocol design is not a familiar subject, read some simple protocol specifications, for example by IETF If this is not a learning excercise, you might want to build up from something else, like Python Twisted A: Read some protocols, and try to find one that looks like what you need. Does it need to be message-oriented or stream-oriented? Does it need request order to be preserved, does it need requests to be paired with responses? Do you need message identifiers? Retries, back-off? Is it an RPC protocol, a message queue protocol? A: See http://www.faqs.org/docs/artu/ch05s02.html and http://www.faqs.org/docs/artu/ch05s03.html for a good overview and discussion on data file formats and protocols.
Python Sockets - Creating a message format
I have built a Python server to which various clients can connect, and I need to set a predefined series of messages from clients to the server - For example the client passes in a name to the server when it first connects. I was wondering what the best way to approach this is? How should I build a simple protocol for their communication? Should the messages start with a specific set of bytes to mark them out as part of this protocol, then contain some sort of message id? Any suggestions or further reading appreciated.
[ "Depending on the requirements, you might want to consider using JSON: use \"newline\" terminated strings with JSON encoding. The transport protocol could be HTTP: with this, you could have access to all the \"connection related\" facilities (e.g. status codes) and have JSON encoded payload.\nThe advantages of using JSON over HTTP:\n\nhuman readable (debugging etc.)\nlibraries available for all languages/platforms\ncross-platform\nbrowser debuggable (to some extent)\n\nOf course, there are many other ways to skin this cat but the time to working prototype using this approach is very low. This is worth considering if your requirements (which aren't very detailed here) can be met.\n", "First, you need to decide whether you want your protocol to be human readable (much more overhead) or binary. If the first, you probably want to use regular expressions to decode the messages. For this, use the python module re. If the latter, the module struct is your friend.\nSecond, if you are building a protocol that is somehow stateful (e.g. first we do a handshake, then we transfer data, then we check checksums and say goodbye) you probably want to create a some sort of FSM to track the state.\nThird, if protocol design is not a familiar subject, read some simple protocol specifications, for example by IETF\nIf this is not a learning excercise, you might want to build up from something else, like Python Twisted\n", "Read some protocols, and try to find one that looks like what you need. Does it need to be message-oriented or stream-oriented? Does it need request order to be preserved, does it need requests to be paired with responses? Do you need message identifiers? Retries, back-off? Is it an RPC protocol, a message queue protocol?\n", "See http://www.faqs.org/docs/artu/ch05s02.html and http://www.faqs.org/docs/artu/ch05s03.html for a good overview and discussion on data file formats and protocols.\n" ]
[ 2, 2, 1, 0 ]
[]
[]
[ "protocols", "python", "sockets" ]
stackoverflow_0002042133_protocols_python_sockets.txt
Q: What to write into log file? My question is simple: what to write into a log. Are there any conventions? What do I have to put in? Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is. I already have some ideas, like a timestamp, a unique identifier for each function/method, etc.. I'd like to have several log levels, like tracing/debugging, informations, errors/warnings. Do you use some pre-formatted log resources? Thank you A: It's quite pleasant, and already implemented. Read this: http://docs.python.org/library/logging.html Edit "easy to parse, read," are generally contradictory features. English -- easy to read, hard to parse. XML -- easy to parse, hard to read. There is no format that achieves easy-to-read and easy-to-parse. Some log formats are "not horrible to read and not impossible to parse". Some folks create multiple handlers so that one log has several formats: a summary for people to read and an XML version for automated parsing. A: Here are some suggestions for content: timestamp message log message type (such as error, warning, trace, debug) thread id ( so you can make sense of the log file from a multi threaded application) Best practices for implementation: Put a mutex around the write method so that you can be sure that each write is thread safe and will make sense. Send 1 message at at a time to the log file, and specify the type of log message each time. Then you can set what type of logging you want to take on program startup. Use no buffering on the file, or flush often in case there is a program crash. Edit: I just noticed the question was tagged with Python, so please see S. Lott's answer before mine. It may be enough for your needs. A: Since you tagged your question python, I refer you to this question as well. As for the content, Brian proposal is good. Remember however to add the program name if you are using a shared log. The important thing about a logfile is "greppability". Try to provide all your info in a single line, with proper string identifiers that are unique (also in radix) for a particular condition. As for the timestamp, use the ISO-8601 standard which sorts nicely. A: A good idea is to look at log analysis software. Unless you plan to write your own, you will probably want to exploit an existing log analysis package such as Analog. If that is the case, you will probably want to generate a log output that is similar enough to the formats that it accepts. It will allow you to create nice charts and graphs with minimal effort! A: In my opinion, best approach is to use existing logging libraries such as log4j (or it's variations for other languages). It gives you control on how your messages are formatted and you can change it without ever touching your code. It follows best practices, robust and used by millions of users. Of course, you can write you own logging framework, but that would be very odd thing to do, unless you need something very specific. In any case, walk though their documentation and see how log statements are presented there. Check out log4py - Python ported version of log4j, I think there are several implementations for Python out there.. A: Python's logging library are thread-safe for single process threads.
What to write into log file?
My question is simple: what to write into a log. Are there any conventions? What do I have to put in? Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is. I already have some ideas, like a timestamp, a unique identifier for each function/method, etc.. I'd like to have several log levels, like tracing/debugging, informations, errors/warnings. Do you use some pre-formatted log resources? Thank you
[ "It's quite pleasant, and already implemented.\nRead this: http://docs.python.org/library/logging.html\n\nEdit\n\"easy to parse, read,\" are generally contradictory features. English -- easy to read, hard to parse. XML -- easy to parse, hard to read. There is no format that achieves easy-to-read and easy-to-parse. Some log formats are \"not horrible to read and not impossible to parse\".\nSome folks create multiple handlers so that one log has several formats: a summary for people to read and an XML version for automated parsing.\n", "Here are some suggestions for content:\n\ntimestamp\nmessage\nlog message type (such as error, warning, trace, debug)\nthread id ( so you can make sense of the log file from a multi threaded application)\n\nBest practices for implementation:\n\nPut a mutex around the write method so that you can be sure that each write is thread safe and will make sense.\nSend 1 message at at a time to the log file, and specify the type of log message each time. Then you can set what type of logging you want to take on program startup.\nUse no buffering on the file, or flush often in case there is a program crash.\n\nEdit: I just noticed the question was tagged with Python, so please see S. Lott's answer before mine. It may be enough for your needs.\n", "Since you tagged your question python, I refer you to this question as well.\nAs for the content, Brian proposal is good. Remember however to add the program name if you are using a shared log.\nThe important thing about a logfile is \"greppability\". Try to provide all your info in a single line, with proper string identifiers that are unique (also in radix) for a particular condition. As for the timestamp, use the ISO-8601 standard which sorts nicely.\n", "A good idea is to look at log analysis software. Unless you plan to write your own, you will probably want to exploit an existing log analysis package such as Analog. If that is the case, you will probably want to generate a log output that is similar enough to the formats that it accepts. It will allow you to create nice charts and graphs with minimal effort!\n", "In my opinion, best approach is to use existing logging libraries such as log4j (or it's variations for other languages). It gives you control on how your messages are formatted and you can change it without ever touching your code. It follows best practices, robust and used by millions of users. Of course, you can write you own logging framework, but that would be very odd thing to do, unless you need something very specific. In any case, walk though their documentation and see how log statements are presented there.\nCheck out log4py - Python ported version of log4j, I think there are several implementations for Python out there..\n", "Python's logging library are thread-safe for single process threads.\n" ]
[ 18, 9, 1, 1, 1, 0 ]
[ "timeStamp i.e. DateTime YYYY/MM/DD:HH:mm:ss:ms\nUser\nThread ID\nFunction Name\nMessage/Error Message/Success Message/Function Trace\nHave this in XML format and you can then easily write a parser for it.\n<log>\n <logEntry DebugLevel=\"0|1|2|3|4|5....\">\n <TimeStamp format=\"YYYY/MM/DD:HH:mm:ss:ms\" value=\"2009/04/22:14:12:33:120\" />\n <ThreadId value=\"\" />\n <FunctionName value=\"\" />\n <Message type=\"Error|Success|Failure|Status|Trace\">\n Your message goes here\n </Message> \n </logEntry>\n</log>\n\n" ]
[ -1 ]
[ "logging", "methodology", "python" ]
stackoverflow_0000779989_logging_methodology_python.txt
Q: Py2App Can't find standard modules I've created an app using py2app, which works fine, but if I zip/unzip it, the newly unzipped version can't access standard python modules like traceback, or os. The manpage for zip claims that it preserves resource forks, and I've seen other applications packaged this way (I need to be able to put this in a .zip file). How do I fix this? A: This is caused by building a semi-standalone version that contains symlinks to the natively installed files and as you say, the links are lost when zipping/unzipping unless the "-y" option is used. An alternate solution is to build for standalone instead, which puts (public domain) files inside the application and so survives zipping/unzipping etc. better. It also means the app is more resilient to changes in the underlying OS. The downside is that it is bigger, of course, and is more complicated to get it set up. To build a stand alone version, you need to install the python.org version which can be repackaged. An explanation of how to do this is here, but read the comments as there have been some changes since the blog post was written. A: use zip -y ... to create the file whilst preserving symlinks. A: You probably need to give it your full PYTHONPATH. Depends on your os. Here's how to find out: import os [or any other std module] os.file()
Py2App Can't find standard modules
I've created an app using py2app, which works fine, but if I zip/unzip it, the newly unzipped version can't access standard python modules like traceback, or os. The manpage for zip claims that it preserves resource forks, and I've seen other applications packaged this way (I need to be able to put this in a .zip file). How do I fix this?
[ "This is caused by building a semi-standalone version that contains symlinks to the natively installed files and as you say, the links are lost when zipping/unzipping unless the \"-y\" option is used.\nAn alternate solution is to build for standalone instead, which puts (public domain) files inside the application and so survives zipping/unzipping etc. better. It also means the app is more resilient to changes in the underlying OS. The downside is that it is bigger, of course, and is more complicated to get it set up.\nTo build a stand alone version, you need to install the python.org version which can be repackaged.\nAn explanation of how to do this is here, but read the comments as there have been some changes since the blog post was written.\n", "use zip -y ... to create the file whilst preserving symlinks.\n", "You probably need to give it your full PYTHONPATH.\nDepends on your os. Here's how to find out:\nimport os [or any other std module]\nos.file()\n" ]
[ 5, 0, 0 ]
[]
[]
[ "macos", "py2app", "python" ]
stackoverflow_0001346297_macos_py2app_python.txt
Q: Could not get cookie from another (parent) domain in Django I need to remove a cookie that was previously set for parent domain while browsing host at subdomain of the parent. I.e., a cookie "xyz" was set for example.com, and I am trying to remove it on subdomain.example.com, using Django backend. The request.COOKIES given to the view does not contain any cookies except those from subdomain.example.com, so I can't write just response.delete_cookie(...) in order to delete it. It is possible to perform such deletion either in Python or Javascript? A: The cookie was probably set with 'domain' parameter. Set the cookie to be accessible from all the subdomains of the domain the cookie is being set in. I'm not the python guy, but my knowledge of http protocol shows that this might be the problem. A: You can attempt to call delete_cookie even for a cookie you haven't been able to read. Django will output the relevant Set-Cookie headers to delete the cookie regardless. Naturally the domain and path you pass to delete_cookie must match the cookie you intend to delete. However, if you haven't been able to read the cookie, it is likely there is another problem, which might prevent you deleting it. Are you sure the cookie from the parent domain was set with a domain=parentdomain.tld parameter? If not then it wouldn't be visible or deletable from the subdomain, except in IE due to that browser's bad handling of no-domain-specified cookies.
Could not get cookie from another (parent) domain in Django
I need to remove a cookie that was previously set for parent domain while browsing host at subdomain of the parent. I.e., a cookie "xyz" was set for example.com, and I am trying to remove it on subdomain.example.com, using Django backend. The request.COOKIES given to the view does not contain any cookies except those from subdomain.example.com, so I can't write just response.delete_cookie(...) in order to delete it. It is possible to perform such deletion either in Python or Javascript?
[ "The cookie was probably set with 'domain' parameter. Set the cookie to be accessible from all the subdomains of the domain the cookie is being set in.\nI'm not the python guy, but my knowledge of http protocol shows that this might be the problem.\n", "You can attempt to call delete_cookie even for a cookie you haven't been able to read. Django will output the relevant Set-Cookie headers to delete the cookie regardless. Naturally the domain and path you pass to delete_cookie must match the cookie you intend to delete.\nHowever, if you haven't been able to read the cookie, it is likely there is another problem, which might prevent you deleting it. Are you sure the cookie from the parent domain was set with a domain=parentdomain.tld parameter? If not then it wouldn't be visible or deletable from the subdomain, except in IE due to that browser's bad handling of no-domain-specified cookies.\n" ]
[ 1, 0 ]
[]
[]
[ "cookies", "django", "javascript", "python" ]
stackoverflow_0002043138_cookies_django_javascript_python.txt
Q: Is there a better library than urlgrabber for fetching remote urls in python? I'm writing a spider that needs a load_url function that performs the following for me: Retry the URL if there is a temporary error, without leaking exceptions. Not leak memory or file handles Use HTTP-KeepAlive for speed (optional) URLGrabber looks great on the surface, but it has trouble. The first I hit a problem with too many files open, but I was able to workaround this by turning keep-alive off. Then, the function started raising a socket.error: [Errno 104] Connection reset by peer. That error should have been caught and possibly a URLGrabberError should be raised in it's place. I'm running python 2.6.4. Does anyone know of a way to fix these issues with URLGrabber or know of another way to accomplish what I need with a different library? A: If you are writing a web-crawler / screen-scraper, you may be interested to look at a dedicated framework such as scrapy. You can write really quite sophisticated web crawlers with very little code: it takes care of all the gory details of scheduling the requests and calling you back with the results for you to process in whatever way you need (it's based on twisted but it hides all the implementation details away from you nicely). A: Screen-scraping? Check out BeautifulSoup A: Also for screen scraping in Python there is Scrapy though I don't know if this will fulfil your requirements. A: Scrapy sounds great, and I will consider using it in the future. For this project however, I'm really looking for a simple function as described above. I have created one that seems to be getting the job done. import urllib2 class HttpLoadError(RuntimeError): pass class Http404(HttpLoadError): pass class HttpFailedRepeatedly(HttpLoadError): pass def safeurlopen(url): import time i = 0 while True: i += 1 try: return urllib2.urlopen(url) except (urllib2.HTTPError, socket.error), e: if getattr(e, 'code', '') == 404: raise Http404 if i >= 10: raise HttpFailedRepeatedly(e) time.sleep(30) def safeurlopenandread(url): rh = safeurlopen(url) res = rh.read() rh.close() return res A: The methods employed by the Harvestman crawler might be worth studying.
Is there a better library than urlgrabber for fetching remote urls in python?
I'm writing a spider that needs a load_url function that performs the following for me: Retry the URL if there is a temporary error, without leaking exceptions. Not leak memory or file handles Use HTTP-KeepAlive for speed (optional) URLGrabber looks great on the surface, but it has trouble. The first I hit a problem with too many files open, but I was able to workaround this by turning keep-alive off. Then, the function started raising a socket.error: [Errno 104] Connection reset by peer. That error should have been caught and possibly a URLGrabberError should be raised in it's place. I'm running python 2.6.4. Does anyone know of a way to fix these issues with URLGrabber or know of another way to accomplish what I need with a different library?
[ "If you are writing a web-crawler / screen-scraper, you may be interested to look at a dedicated framework such as scrapy. \nYou can write really quite sophisticated web crawlers with very little code: it takes care of all the gory details of scheduling the requests and calling you back with the results for you to process in whatever way you need (it's based on twisted but it hides all the implementation details away from you nicely).\n", "Screen-scraping? Check out BeautifulSoup\n", "Also for screen scraping in Python there is Scrapy though I don't know if this will fulfil your requirements.\n", "Scrapy sounds great, and I will consider using it in the future. For this project however, I'm really looking for a simple function as described above. I have created one that seems to be getting the job done.\nimport urllib2\n\nclass HttpLoadError(RuntimeError):\n pass\n\nclass Http404(HttpLoadError):\n pass\n\nclass HttpFailedRepeatedly(HttpLoadError):\n pass\n\ndef safeurlopen(url):\n import time\n i = 0\n while True:\n i += 1\n try:\n return urllib2.urlopen(url)\n except (urllib2.HTTPError, socket.error), e:\n if getattr(e, 'code', '') == 404:\n raise Http404\n if i >= 10:\n raise HttpFailedRepeatedly(e)\n time.sleep(30)\n\ndef safeurlopenandread(url):\n rh = safeurlopen(url)\n res = rh.read()\n rh.close()\n return res\n\n", "The methods employed by the Harvestman crawler might be worth studying.\n" ]
[ 4, 0, 0, 0, 0 ]
[]
[]
[ "python", "screen_scraping" ]
stackoverflow_0002040628_python_screen_scraping.txt
Q: Traversing an unusual tree in Python I have an unusual tree array like this: [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6], [0, 7], [7, 6], [8, 9], [9, 6]] Each element of the array is a pair, which means second one is a follower of the first, e.g.: [0, 1] - 0 is followed by 1 [1, 2] - 1 is followed by 2 I am trying to extract array like this: 0 1 2 3 6 0 1 2 4 6 0 1 2 5 6 0 7 6 8 9 6 I couldn't code a robust traversal to extract all possible paths like this. How can I do it with Python? A: You could do it using a recursive generator function. I assume that the root node in the tree always comes before all its children in the original list. tree = [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6], [0, 7], [7, 6], [8, 9], [9, 6]] paths = {} for t in tree: if t[0] not in paths: paths[t[0]] = [] paths[t[0]].append(tuple(t)) used = set() def get_paths(node): if node[1] in paths: for next_node in paths[node[1]]: used.add(next_node) for path in get_paths(next_node): yield [node[0]] + path else: yield [node[0], node[1]] for node in tree: if tuple(node) in used: continue for path in get_paths(node): print path Output: [0, 1, 2, 3, 6] [0, 1, 2, 4, 6] [0, 1, 2, 5, 6] [0, 7, 6] [8, 9, 6] Explanation: First I construct a list of all possible paths from each node. Then for each node that I haven't used yet I assume it is a root node and recursively find which paths lead from it. If no paths are found from any node, it is a leaf node and I stop the recursion and return the path found. If the assumption about the order of the nodes does not hold then you would first have to find the set of all root nodes. This can be done by finding all nodes that do not appear as the second node in any connection. A: From what I understand of your question, it looks like you have a set of parent-child relationships as a list of pairs that describes a tree. You seem to be running into trouble by thinking that it has a structure like a linked list. Unlike a linked list, a tree is a more general form, it can have multiple nodes that 'follow' a given node that are called its children. The easiest way is to simply build the tree first and then traverse it from the root. Define a Node class that has two fields, one for the value of the node and the other a list of children. Then you iterate over the items of your list adding the second element of each pair to the children list of node corresponding to the first element of the pair. After the tree is built, you use a recursive print function that prints the current node and calls itself on its children (if there are any). Calling the function on the root node should print the whole tree. I would post some code, but this looks a lot like homework. The above explanation should be enough for a start. A: The easiest way I can think of, would be to construct a dictionary that contains all possible children for a given parent, like so: d = {} for parent, child in tree: try: d[parent].append(child) except KeyError: d[parent] = [child] with tree = [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6], [0, 7], [7, 6], [8, 9], [9, 6]], this would produce: {0: [1, 7], 1: [2], 2: [3, 4, 5], 3: [6], 4: [6], 5: [6], 7: [6], 8: [9], 9: [6]} Now it's possible to recursively traverse the tree like this: def printPaths(d, currentPath): if currentPath[-1] not in d: print currentPath # last node can't possibly be a parent, so stop else: for child in d[currentPath[-1]]: printPaths(d, currentPath + [child]) for root in d: printPaths(d, [root]) I haven't tested the recursion, but it should give you an idea :) A: Here you go. Not the nicest code on earth but it works: inputValues = [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6], [0, 7], [7, 6], [8, 9], [9, 6]] tree = {} numberOfChildren = {} for (f, t) in inputValues: if not tree.has_key(f): tree[f] = [] tree[f].append(t) if not numberOfChildren.has_key(t): numberOfChildren[t] = 0 numberOfChildren[t] += 1 roots = [c for c in tree if c not in numberOfChildren] permutations = [] def findPermutations(node, currentList): global tree global permutations if not tree.has_key(node): permutations.append(currentList) return for child in tree[node]: l = list() l.extend(currentList) l.append(child) findPermutations(child, l) for r in roots: findPermutations(r, [r]) print permutations A: Looking at the problem, it seems the best approach might be to build the arrays backwards over several iterations. My idea is this, but note we have to assume that this is a tree and so the leaves can only be used once: Let arrays = list of pairs Until every array in arrays are leaf: If an array is a leaf (last element isn't the first element in any array in arrays): For each array in arrays see if the leaf can be attached on to the end of it After attaching to all possible arrays, delete the leaf Obviously you'll have to do some work to turn that into code, but that's a rough idea. A: You could use the find_all_paths function from the following page: http://www.python.org/doc/essays/graphs/ In order to use this you need to make two minor tweeks to your graph. First, loop through your list of edges and create a new representation of the graph like: graph = {0: [1, 7], 1: [2], 2: [3, 4, 5], ...} Secondly create a supersink (in your example case you could call it 10) and attach all vertices with no edges leading from them to this new node. Then you can call the function find_all_paths(graph, 0, 10) to find all such paths. A: Produce all longest pathes from all possible starting nodes: tree = [[0, 1], [1, 2], [2, 3], ...] dtree = {} for (k, v) in tree: dtree.setdefault(k, []).append(v) parts = [[root] for root in range(10)] while parts: path = parts.pop(0) if path[-1] in dtree: for n in dtree[path[-1]]: parts.append(path + [n]) else: print path If it should only produce paths that are not part of a different, longer path starting at some other node, parts would need to be initialized to all nodes not contained in [p[1] for p in tree]. And if you want all paths instead, not just the longest ones, there should be a print in every iteration of the while-loop. A: The following works - generate the trees starting from root. The roots are considered the nodes that do not have a parent. import operator def genpaths(data): # Initialize dictionary ddata = {} for item in data: ddata.setdefault(item[0], []).append(item[1]) def genpath(root): "Generate paths starting with root" if root not in ddata: yield (root, ) else: for child in ddata[root]: for path in genpath(child): yield (root, ) + path for root in set(ddata.keys()) - set(reduce(operator.add, ddata.values())): for path in genpath(root): print path
Traversing an unusual tree in Python
I have an unusual tree array like this: [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6], [0, 7], [7, 6], [8, 9], [9, 6]] Each element of the array is a pair, which means second one is a follower of the first, e.g.: [0, 1] - 0 is followed by 1 [1, 2] - 1 is followed by 2 I am trying to extract array like this: 0 1 2 3 6 0 1 2 4 6 0 1 2 5 6 0 7 6 8 9 6 I couldn't code a robust traversal to extract all possible paths like this. How can I do it with Python?
[ "You could do it using a recursive generator function. I assume that the root node in the tree always comes before all its children in the original list.\ntree = [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6],\n [0, 7], [7, 6], [8, 9], [9, 6]]\n\npaths = {}\nfor t in tree:\n if t[0] not in paths: paths[t[0]] = []\n paths[t[0]].append(tuple(t))\n\nused = set()\n\ndef get_paths(node):\n if node[1] in paths:\n for next_node in paths[node[1]]:\n used.add(next_node)\n for path in get_paths(next_node):\n yield [node[0]] + path\n else:\n yield [node[0], node[1]]\n\nfor node in tree:\n if tuple(node) in used: continue\n for path in get_paths(node):\n print path\n\nOutput:\n[0, 1, 2, 3, 6]\n[0, 1, 2, 4, 6]\n[0, 1, 2, 5, 6]\n[0, 7, 6]\n[8, 9, 6]\n\nExplanation: First I construct a list of all possible paths from each node. Then for each node that I haven't used yet I assume it is a root node and recursively find which paths lead from it. If no paths are found from any node, it is a leaf node and I stop the recursion and return the path found.\nIf the assumption about the order of the nodes does not hold then you would first have to find the set of all root nodes. This can be done by finding all nodes that do not appear as the second node in any connection.\n", "From what I understand of your question, it looks like you have a set of parent-child relationships as a list of pairs that describes a tree. You seem to be running into trouble by thinking that it has a structure like a linked list. Unlike a linked list, a tree is a more general form, it can have multiple nodes that 'follow' a given node that are called its children.\nThe easiest way is to simply build the tree first and then traverse it from the root. Define a Node class that has two fields, one for the value of the node and the other a list of children. Then you iterate over the items of your list adding the second element of each pair to the children list of node corresponding to the first element of the pair.\nAfter the tree is built, you use a recursive print function that prints the current node and calls itself on its children (if there are any). Calling the function on the root node should print the whole tree.\nI would post some code, but this looks a lot like homework. The above explanation should be enough for a start. \n", "The easiest way I can think of, would be to construct a dictionary that contains all possible children for a given parent, like so:\nd = {}\n\nfor parent, child in tree:\n try:\n d[parent].append(child)\n except KeyError:\n d[parent] = [child]\n\nwith tree = [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6], [0, 7], [7, 6], [8, 9], [9, 6]],\nthis would produce:\n{0: [1, 7],\n 1: [2],\n 2: [3, 4, 5],\n 3: [6],\n 4: [6],\n 5: [6],\n 7: [6],\n 8: [9],\n 9: [6]}\n\nNow it's possible to recursively traverse the tree like this:\ndef printPaths(d, currentPath):\n if currentPath[-1] not in d:\n print currentPath # last node can't possibly be a parent, so stop\n else:\n for child in d[currentPath[-1]]:\n printPaths(d, currentPath + [child])\n\n\nfor root in d:\n printPaths(d, [root])\n\nI haven't tested the recursion, but it should give you an idea :)\n", "Here you go. Not the nicest code on earth but it works:\ninputValues = [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6], [0, 7], [7, 6], [8, 9], [9, 6]]\n\ntree = {}\nnumberOfChildren = {}\nfor (f, t) in inputValues:\n if not tree.has_key(f):\n tree[f] = []\n tree[f].append(t)\n if not numberOfChildren.has_key(t):\n numberOfChildren[t] = 0\n numberOfChildren[t] += 1\n\nroots = [c for c in tree if c not in numberOfChildren]\npermutations = []\n\ndef findPermutations(node, currentList):\n global tree\n global permutations\n if not tree.has_key(node):\n permutations.append(currentList)\n return\n for child in tree[node]:\n l = list()\n l.extend(currentList)\n l.append(child)\n findPermutations(child, l)\n\nfor r in roots:\n findPermutations(r, [r])\n\nprint permutations\n\n", "Looking at the problem, it seems the best approach might be to build the arrays backwards over several iterations. My idea is this, but note we have to assume that this is a tree and so the leaves can only be used once:\n\nLet arrays = list of pairs\nUntil every array in arrays are leaf:\n\n\nIf an array is a leaf (last element isn't the first element in any array in arrays):\n\n\nFor each array in arrays see if the leaf can be attached on to the end of it\nAfter attaching to all possible arrays, delete the leaf\n\n\n\nObviously you'll have to do some work to turn that into code, but that's a rough idea.\n", "You could use the find_all_paths function from the following page:\nhttp://www.python.org/doc/essays/graphs/\nIn order to use this you need to make two minor tweeks to your graph. First, loop through your list of edges and create a new representation of the graph like:\n graph = {0: [1, 7],\n 1: [2],\n 2: [3, 4, 5],\n ...}\n\nSecondly create a supersink (in your example case you could call it 10) and attach all vertices with no edges leading from them to this new node.\nThen you can call the function find_all_paths(graph, 0, 10) to find all such paths.\n", "Produce all longest pathes from all possible starting nodes:\ntree = [[0, 1], [1, 2], [2, 3], ...]\n\ndtree = {}\nfor (k, v) in tree:\n dtree.setdefault(k, []).append(v)\n\nparts = [[root] for root in range(10)]\n\nwhile parts:\n path = parts.pop(0)\n if path[-1] in dtree:\n for n in dtree[path[-1]]:\n parts.append(path + [n])\n else:\n print path\n\nIf it should only produce paths that are not part of a different, longer path starting at some other node, parts would need to be initialized to all nodes not contained in [p[1] for p in tree]. And if you want all paths instead, not just the longest ones, there should be a print in every iteration of the while-loop.\n", "The following works - generate the trees starting from root.\nThe roots are considered the nodes that do not have a parent.\nimport operator\ndef genpaths(data):\n # Initialize dictionary\n ddata = {}\n for item in data:\n ddata.setdefault(item[0], []).append(item[1])\n def genpath(root):\n \"Generate paths starting with root\"\n if root not in ddata:\n yield (root, )\n else:\n for child in ddata[root]:\n for path in genpath(child):\n yield (root, ) + path\n\n for root in set(ddata.keys()) - set(reduce(operator.add, ddata.values())):\n for path in genpath(root):\n print path\n\n" ]
[ 4, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "traversal", "tree" ]
stackoverflow_0002042918_python_traversal_tree.txt
Q: How can I support * in user-defined search strings in python? This question is related to this stack overflow question: How can I support wildcards in user-defined search strings in Python? But I need to only support the wildcards and not the ? or the [seq] functionality that you get with fnmatch. Since there is no way to remove that functionality from fnmatch, is there another way of doing this? I need a user defined string like this: site.*.com/sub/ to match this: site.hostname.com/sub/ Without all the added functionality of ? and [] A: You could compile a regexp from your search string using split, re.escape, and '^$'. import re regex = re.compile('^' + '.*'.join(re.escape(foo) for foo in pattern.split('*')) + '$') A: If its just one asterisk and you require the search string to be representing the whole matched string, this works: searchstring = "site.*.com/sub/" to_match = "site.hostname.com/sub/" prefix, suffix = searchstring.split("*", 1) if to_match.startswith(prefix) and to_match.endswith(suffix): print "Found a match!" Otherwise, building a regex like Tobu suggests is probably best.
How can I support * in user-defined search strings in python?
This question is related to this stack overflow question: How can I support wildcards in user-defined search strings in Python? But I need to only support the wildcards and not the ? or the [seq] functionality that you get with fnmatch. Since there is no way to remove that functionality from fnmatch, is there another way of doing this? I need a user defined string like this: site.*.com/sub/ to match this: site.hostname.com/sub/ Without all the added functionality of ? and []
[ "You could compile a regexp from your search string using split, re.escape, and '^$'.\nimport re\nregex = re.compile('^' + '.*'.join(re.escape(foo) for foo in pattern.split('*')) + '$')\n\n", "If its just one asterisk and you require the search string to be representing the whole matched string, this works:\nsearchstring = \"site.*.com/sub/\"\nto_match = \"site.hostname.com/sub/\"\n\nprefix, suffix = searchstring.split(\"*\", 1)\n\nif to_match.startswith(prefix) and to_match.endswith(suffix):\n print \"Found a match!\"\n\nOtherwise, building a regex like Tobu suggests is probably best.\n" ]
[ 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002043449_python_regex.txt
Q: Compiling a py2app working build for both Leopard and Snow Leopard? I currently am making my PyObjC application work for Snow Leopard and I successfully compiled a standalone app. My question would be, how do I make the build to be also Leopard-compatible, given these errors? dyld: lazy symbol binding failed: Symbol not found: _fopen$UNIX2003 Referenced from: /Applications/MyApp.app/Contents/MacOS/MyApp Expected in: /usr/lib/libSystem.B.dylib dyld: Symbol not found: _fopen$UNIX2003 Referenced from: /Applications/MyApp.app/Contents/MacOS/MyApp Expected in: /usr/lib/libSystem.B.dylib This is a Snow Leopard-compiled py2app application. Also, when I compile on Leopard, on the other hand, this error occurs: Traceback (most recent call last): File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/__boot__.py", line 31, in <module> _run('main.py') File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/__boot__.py", line 28, in _run execfile(path, globals(), globals()) File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/main.py", line 17, in <module> from AppKit import * File "AppKit/__init__.pyc", line 10, in <module> File "Foundation/__init__.pyc", line 10, in <module> File "CoreFoundation/__init__.pyc", line 17, in <module> File "objc/_bridgesupport.pyc", line 129, in initFrameworkWrapper File "objc/_bridgesupport.pyc", line 53, in _parseBridgeSupport ValueError: Unknown typestr 2009-08-29 19:30:14.530 MyApp[445:903] MyApp Error 2009-08-29 19:30:14.534 MyApp[445:903] MyApp Error An unexpected error has occurred during execution of the main script Any help would be appreciated. Thanks in advance. A: I've done this recently and the trick was to build a standalone version on a Leopard installation. By default, unless you have an open source version of Python installed, py2app creates a semi-standalone application that has symlinks to the OS files. If instead, you create a standalone version of the application, then the interpreter and supporting files are embedded within your application and are therefore consistent on all machines running your application. Instructions on creating a fully standalone application are available here, but pay attention to the blog's comments as some things did change after the blog post was written. If you have specific libs that you need you can reference them in the setup.py file or alternatively you can always add them manually to the dylib directory (which was easier for me as I needed to change the startup scripts and didn't want to regenerate), but make sure you use the 32-bit libs (which it will be on Leopard). A: Since both are on distinct architecture (respectively 32 bits and 64 bits) I think you have to create 2 distinct compilations. A: Try the following: http://groups.google.com/group/wxpython-users/browse_thread/thread/916fa0569bfa3efd/9d16f540a89cc4c3?lnk=gst&q=py2app#9d16f540a89cc4c3
Compiling a py2app working build for both Leopard and Snow Leopard?
I currently am making my PyObjC application work for Snow Leopard and I successfully compiled a standalone app. My question would be, how do I make the build to be also Leopard-compatible, given these errors? dyld: lazy symbol binding failed: Symbol not found: _fopen$UNIX2003 Referenced from: /Applications/MyApp.app/Contents/MacOS/MyApp Expected in: /usr/lib/libSystem.B.dylib dyld: Symbol not found: _fopen$UNIX2003 Referenced from: /Applications/MyApp.app/Contents/MacOS/MyApp Expected in: /usr/lib/libSystem.B.dylib This is a Snow Leopard-compiled py2app application. Also, when I compile on Leopard, on the other hand, this error occurs: Traceback (most recent call last): File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/__boot__.py", line 31, in <module> _run('main.py') File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/__boot__.py", line 28, in _run execfile(path, globals(), globals()) File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/main.py", line 17, in <module> from AppKit import * File "AppKit/__init__.pyc", line 10, in <module> File "Foundation/__init__.pyc", line 10, in <module> File "CoreFoundation/__init__.pyc", line 17, in <module> File "objc/_bridgesupport.pyc", line 129, in initFrameworkWrapper File "objc/_bridgesupport.pyc", line 53, in _parseBridgeSupport ValueError: Unknown typestr 2009-08-29 19:30:14.530 MyApp[445:903] MyApp Error 2009-08-29 19:30:14.534 MyApp[445:903] MyApp Error An unexpected error has occurred during execution of the main script Any help would be appreciated. Thanks in advance.
[ "I've done this recently and the trick was to build a standalone version on a Leopard installation.\nBy default, unless you have an open source version of Python installed, py2app creates a semi-standalone application that has symlinks to the OS files.\nIf instead, you create a standalone version of the application, then the interpreter and supporting files are embedded within your application and are therefore consistent on all machines running your application. Instructions on creating a fully standalone application are available here, but pay attention to the blog's comments as some things did change after the blog post was written.\nIf you have specific libs that you need you can reference them in the setup.py file or alternatively you can always add them manually to the dylib directory (which was easier for me as I needed to change the startup scripts and didn't want to regenerate), but make sure you use the 32-bit libs (which it will be on Leopard).\n", "Since both are on distinct architecture (respectively 32 bits and 64 bits) I think you have to create 2 distinct compilations.\n", "Try the following:\nhttp://groups.google.com/group/wxpython-users/browse_thread/thread/916fa0569bfa3efd/9d16f540a89cc4c3?lnk=gst&q=py2app#9d16f540a89cc4c3\n" ]
[ 3, 0, 0 ]
[]
[]
[ "osx_leopard", "osx_snow_leopard", "py2app", "python" ]
stackoverflow_0001351209_osx_leopard_osx_snow_leopard_py2app_python.txt
Q: How to change global variables in Python I am trying to change a variable further down the program. I have a global variable declared at the start of the program and I want to change the variable in different functions down the program. I can do this by declaring the variable inside the function again but I would like to know is there a better way of doing this. Some test code is below to explain what I mean. ID = 'No' project = ("Yep"+ID) # ID added with 'No' value which I later want to change def pro(): ID = "YES" print ID def pro1(ID): # I could declare project again to get this to work, but I would like to avoid this print project # I want this to print with the new ID number. if __name__ == '__main__': pro() pro1(ID) Has anyone any ideas, thanks I have tried the global variable but when I do this the project variable still prints out YepNo instead of YepYES. I want the new variable from the function proto change the variable in the project variable. A: To update global variables you could use global ID ID="Yes" before assigning variable to ID = "YES" But changing ID will be no effect on project variable, project = ("Yep"+ID), because project is already a string you need to make a function like def getprojectname(ID): return project+ID The whole program may be like this UPDATE: ... removed A: Beware, you're doing it wrong multiple times. Even though you could use the global statement to change a global (it is discouraged since it's better to use function parameters and return values), that would NOT change other already assigned values. E.g. even though you reassign ID, you would NOT reassign project. Also: your functions return nothing, there's no point in assigning a name to their return value, and it's a BAD habit using an all-uppercase name (ID) for a variable since it's a convention to use them for constants. This should clarify you the way global works: myid = '' project = ("Yep"+myid) #ID added with no value which I later want to change def mutate_id(): global myid myid = "YES" def mutate_project(): global project project = ("YEP" + myid) if __name__ == '__main__': print "myid", myid print "project ", project print mutate_id() print "myid", myid print "project ", project print mutate_project() print "myid", myid print "project ", project print But the best way is to do WITHOUT globals: def get_new_id(old): return "YES" def get_new_project(old): return ("YEP" + myid) if __name__ == '__main__': myid = '' project = ("Yep"+myid) print "myid", myid print "project ", project print myid = get_new_id(myid) print "myid", myid print "project ", project print project = get_new_project(project) print "myid", myid print "project ", project print This will make all code interaction clear, and prevent issues related to global state change. A: Use the global statement. The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. Example: http://www.rexx.com/~dkuhlman/python_101/python_101.html#SECTION004340000000000000000 P.S. But don't use global too often, see http://www.youtube.com/watch?v=E_kZDvwofHY#t=10m45 A: In your code you have two problems. The first about changing ID variable, which could be solved by using global. The second that your code calculate project string and after that project don't know about ID. To avoid code duplication you can define function to calc project. So we have: ID = 'No' def GetProject(): return "Yep"+ID def pro(): global ID ID = "YES" print ID print GetProject() pro() print GetProject()
How to change global variables in Python
I am trying to change a variable further down the program. I have a global variable declared at the start of the program and I want to change the variable in different functions down the program. I can do this by declaring the variable inside the function again but I would like to know is there a better way of doing this. Some test code is below to explain what I mean. ID = 'No' project = ("Yep"+ID) # ID added with 'No' value which I later want to change def pro(): ID = "YES" print ID def pro1(ID): # I could declare project again to get this to work, but I would like to avoid this print project # I want this to print with the new ID number. if __name__ == '__main__': pro() pro1(ID) Has anyone any ideas, thanks I have tried the global variable but when I do this the project variable still prints out YepNo instead of YepYES. I want the new variable from the function proto change the variable in the project variable.
[ "To update global variables you could use\nglobal ID\nID=\"Yes\"\n\nbefore assigning variable to ID = \"YES\"\nBut changing ID will be no effect on project variable, project = (\"Yep\"+ID), because project is already a string\nyou need to make a function like\ndef getprojectname(ID):\n return project+ID\n\nThe whole program may be like this\nUPDATE:\n... removed\n", "Beware, you're doing it wrong multiple times.\nEven though you could use the global statement to change a global (it is discouraged since it's better to use function parameters and return values), that would NOT change other already assigned values. E.g. even though you reassign ID, you would NOT reassign project. Also: your functions return nothing, there's no point in assigning a name to their return value, and it's a BAD habit using an all-uppercase name (ID) for a variable since it's a convention to use them for constants.\nThis should clarify you the way global works:\nmyid = ''\nproject = (\"Yep\"+myid) #ID added with no value which I later want to change\n\ndef mutate_id():\n global myid\n myid = \"YES\"\n\ndef mutate_project():\n global project\n project = (\"YEP\" + myid)\n\nif __name__ == '__main__': \n print \"myid\", myid\n print \"project \", project\n print\n\n mutate_id()\n\n print \"myid\", myid\n print \"project \", project\n print\n\n mutate_project()\n\n print \"myid\", myid\n print \"project \", project\n print\n\nBut the best way is to do WITHOUT globals:\ndef get_new_id(old):\n return \"YES\"\n\ndef get_new_project(old):\n return (\"YEP\" + myid)\n\nif __name__ == '__main__': \n myid = ''\n project = (\"Yep\"+myid) \n\n print \"myid\", myid\n print \"project \", project\n print\n\n myid = get_new_id(myid)\n\n print \"myid\", myid\n print \"project \", project\n print\n\n project = get_new_project(project)\n\n print \"myid\", myid\n print \"project \", project\n print\n\nThis will make all code interaction clear, and prevent issues related to global state change.\n", "Use the global statement.\n\nThe global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals.\n\nExample: http://www.rexx.com/~dkuhlman/python_101/python_101.html#SECTION004340000000000000000\nP.S.\nBut don't use global too often, see http://www.youtube.com/watch?v=E_kZDvwofHY#t=10m45\n", "In your code you have two problems. The first about changing ID variable, which could be solved by using global. \nThe second that your code calculate project string and after that project don't know about ID.\nTo avoid code duplication you can define function to calc project.\nSo we have:\nID = 'No'\ndef GetProject():\n return \"Yep\"+ID\n\ndef pro():\n global ID\n ID = \"YES\"\n print ID\n\nprint GetProject()\n\npro()\n\nprint GetProject()\n\n" ]
[ 11, 7, 2, 1 ]
[ "You can mutate without reassigning:\nvariables = {}\ndef pro():\n if variables['ID'] == '':\n variables['ID'] = 'default'\n\n", "Why not use a dictionary?\n>>> attr = {'start':'XXX', 'myid':'No'}\n>>> \n>>> def update_and_show(D, value = None):\n... if value: D['myid'] = value\n... print D['start'] + ' ' + D['myid']\n... \n>>> update_and_show(attr)\nXXX No\n>>> update_and_show(attr, 'Yes')\nXXX Yes\n>>> update_and_show(attr, 'No')\nXXX No\n>>>\n\n" ]
[ -1, -1 ]
[ "python" ]
stackoverflow_0002040998_python.txt
Q: Tracking system and real time stats analysis in Python This question is related to an older question: MySQL tracking system. In short: I have to implement a tracking system that will have high loads using Python. For the database part I've settled on mongoDB (which sounds like the right tool for this job). The development language will be Python. I was thinking of using several instances of a CherryPy application behind nginx. The reasoning behind this is that I don't want to handle all the wsgi part myself, but on the other hand I don't need a full blown web framework since the app will be simple and there's no need for ORM. My questions are: Should I use the CherryPy builtin server or should I use Apache with modwsgi (or another server altogether)? Does this sound like a reasonable approach (nginx, mongoDB)? If not what would you recommend? Thank you in advance. A: Have you checked out Graphite? It sounds like exactly the kind of thing that you need (looking at your other question) and was designed for application and server monitoring by the Orbitz team. It's extremely robust and easy to use for this sort of thing. Here's the project site: http://graphite.wikidot.com/ With some screenshots: http://graphite.wikidot.com/screen-shots A: Sounds like MongoDB will be a good fit for this - fast updates with advanced operators, and M/R for batch offline processing. I think CherryPy behind Nginx should work well too. If you go the mod_wsgi route just watch out for this issue.
Tracking system and real time stats analysis in Python
This question is related to an older question: MySQL tracking system. In short: I have to implement a tracking system that will have high loads using Python. For the database part I've settled on mongoDB (which sounds like the right tool for this job). The development language will be Python. I was thinking of using several instances of a CherryPy application behind nginx. The reasoning behind this is that I don't want to handle all the wsgi part myself, but on the other hand I don't need a full blown web framework since the app will be simple and there's no need for ORM. My questions are: Should I use the CherryPy builtin server or should I use Apache with modwsgi (or another server altogether)? Does this sound like a reasonable approach (nginx, mongoDB)? If not what would you recommend? Thank you in advance.
[ "Have you checked out Graphite? It sounds like exactly the kind of thing that you need (looking at your other question) and was designed for application and server monitoring by the Orbitz team. It's extremely robust and easy to use for this sort of thing.\n\nHere's the project site: http://graphite.wikidot.com/\nWith some screenshots: http://graphite.wikidot.com/screen-shots\n\n", "Sounds like MongoDB will be a good fit for this - fast updates with advanced operators, and M/R for batch offline processing. I think CherryPy behind Nginx should work well too. If you go the mod_wsgi route just watch out for this issue.\n" ]
[ 3, 1 ]
[]
[]
[ "cherrypy", "mod_wsgi", "mongodb", "nginx", "python" ]
stackoverflow_0002043879_cherrypy_mod_wsgi_mongodb_nginx_python.txt
Q: NetBeans and Python When I run some python code in NetBeans, which raises an error, the output in NetBeans just gives an error message and no further information, such as line number. Is there any way to fix that? A: If you can, I would run your script outside of NetBeans either with the built-in editor (IDLE) or just run it from the command line. That should give you a traceback with the error and lineno NetBeans has issues with debugging, as other posts suggest. A: added solution is debugging if don't have any compiling error
NetBeans and Python
When I run some python code in NetBeans, which raises an error, the output in NetBeans just gives an error message and no further information, such as line number. Is there any way to fix that?
[ "If you can, I would run your script outside of NetBeans either with the built-in editor (IDLE) or just run it from the command line. That should give you a traceback with the error and lineno\nNetBeans has issues with debugging, as other posts suggest.\n", "added solution is debugging if don't have any compiling error \n" ]
[ 1, 0 ]
[]
[]
[ "netbeans", "python" ]
stackoverflow_0002044364_netbeans_python.txt
Q: SymPy: How to return an expression in terms of other expression(s)? I'm fairly new to SymPy and have what might be a basic question. Or I might simply be misinterpreting how SymPy is supposed to be used. Is there a way to create an expression that is not represented by atoms, but by a combination of other expressions? Example: >>> from sympy.physics.units import * >>> expr1 = m/s >>> expr2 = mile/hour >>> expr1 m/s >>> expr2 1397*m/(3125*s) >>> expr1.in_terms_of([mile,hour]) #in my dreams? 3125*mile/(1397*hour) >>> On a side note: Can I find an 'official' PDF (or other printable) version of the complete SymPy documentation? (I'm under draconian Internet usage restrictions at work and am tired of doing work at home on the weekend.) Update: This is what I ended up with following Prelude's suggestion, however it's not likely to get much use like this as it feels dirty. Comments and WTF's welcome. def in_terms_of(self, terms): expr2 = eval(str(self), physics.units.__dict__) converter = {} for term in terms: term_expr = physics.units.__dict__[term] coeff = term_expr.as_coeff_terms()[0] unit = physics.units.Unit('my_'+term, term) converter[term_expr/coeff] = unit/coeff return str(expr2.subs(converter)) Usage: >>> x = in_terms_of('J',['gram','mile','hour']) >>> x '9765625000*mile**2*gram/(1951609*hour**2)' >>> in_terms_of(x,['J']) 'J' A: Checking the source for sympy.physics.units you can see that all units are defined in terms of meters, kilograms, seconds, amperes, kelvins, moles and candelas. These are the base units. Then a mile is defined as 5280 feet, and a foot is defined as 0.3048 meters. So all expressions using non-base units will have the non-base units replaced with the base units. You can define your own units which you can subsitute into an expression when you need an expression to use particular units: import sympy.physics.units as units from sympy import Rational my_mile = units.Unit('my_mile', 'mile') my_hour = units.Unit('my_hour', 'hour') Then define a dictionary which will substitute the base units for your new units. converter = {units.m: my_mile/Rational('1609.344'), units.s: my_hour/Rational('3600')} Perform all your calculations using the base units. Then if you want a value using miles and hours, you can substitute your new units into the expression. v = 10*units.miles/units.hour print v # = 2794*m/(625*s) print v.subs(converter) # = 10*mile/hour Use ars answer for getting the docs. Sympy's repository is here: https://github.com/sympy/sympy There is a README file in the docs folder which describes how to create html docs. A: there's also quantities: In [1]: from quantities import * In [2]: v = 1397*m / (3125*s) In [3]: v Out[3]: array(0.44704) * m/s In [8]: v.units = mile/hour In [9]: v Out[9]: array(1.0) * mi/h A: In sympy units you convert from expr1 to expr2 by dividing: In [120]: import sympy.physics.units as units In [121]: expr1 = units.m / units.s In [122]: expr2 = units.miles / units.hour In [123]: a = (1397/3125) * expr1 / expr2 In [124]: a Out[124]: 1 The only issue is that you end up with a dimensionless quantity. You might also consider the Quantities package for this type of thing: In [125]: import quantities as pq In [126]: a = pq.Quantity(1397/3125, 'm/s') In [127]: a Out[127]: array(0.44703999999999999) * m/s In [128]: a.units = pq.mile / pq.hour In [129]: a Out[129]: array(1.0) * mi/h There's also Unum. I don't know of a PDF version of the sympy docs, but you might be able to check the distribution out from their repository and use Sphinx to generate a PDF for yourself.
SymPy: How to return an expression in terms of other expression(s)?
I'm fairly new to SymPy and have what might be a basic question. Or I might simply be misinterpreting how SymPy is supposed to be used. Is there a way to create an expression that is not represented by atoms, but by a combination of other expressions? Example: >>> from sympy.physics.units import * >>> expr1 = m/s >>> expr2 = mile/hour >>> expr1 m/s >>> expr2 1397*m/(3125*s) >>> expr1.in_terms_of([mile,hour]) #in my dreams? 3125*mile/(1397*hour) >>> On a side note: Can I find an 'official' PDF (or other printable) version of the complete SymPy documentation? (I'm under draconian Internet usage restrictions at work and am tired of doing work at home on the weekend.) Update: This is what I ended up with following Prelude's suggestion, however it's not likely to get much use like this as it feels dirty. Comments and WTF's welcome. def in_terms_of(self, terms): expr2 = eval(str(self), physics.units.__dict__) converter = {} for term in terms: term_expr = physics.units.__dict__[term] coeff = term_expr.as_coeff_terms()[0] unit = physics.units.Unit('my_'+term, term) converter[term_expr/coeff] = unit/coeff return str(expr2.subs(converter)) Usage: >>> x = in_terms_of('J',['gram','mile','hour']) >>> x '9765625000*mile**2*gram/(1951609*hour**2)' >>> in_terms_of(x,['J']) 'J'
[ "Checking the source for sympy.physics.units you can see that all units are defined in terms of meters, kilograms, seconds, amperes, kelvins, moles and candelas. These are the base units.\nThen a mile is defined as 5280 feet, and a foot is defined as 0.3048 meters.\nSo all expressions using non-base units will have the non-base units replaced with the base units.\nYou can define your own units which you can subsitute into an expression when you need an expression to use particular units:\nimport sympy.physics.units as units\nfrom sympy import Rational\n\nmy_mile = units.Unit('my_mile', 'mile')\nmy_hour = units.Unit('my_hour', 'hour')\n\nThen define a dictionary which will substitute the base units for your new units.\nconverter = {units.m: my_mile/Rational('1609.344'),\n units.s: my_hour/Rational('3600')}\n\nPerform all your calculations using the base units. Then if you want a value using miles and hours, you can substitute your new units into the expression.\nv = 10*units.miles/units.hour\nprint v # = 2794*m/(625*s)\n\nprint v.subs(converter) # = 10*mile/hour\n\nUse ars answer for getting the docs. Sympy's repository is here: https://github.com/sympy/sympy\nThere is a README file in the docs folder which describes how to create html docs.\n", "there's also quantities:\nIn [1]: from quantities import *\nIn [2]: v = 1397*m / (3125*s)\nIn [3]: v\nOut[3]: array(0.44704) * m/s\nIn [8]: v.units = mile/hour\nIn [9]: v\nOut[9]: array(1.0) * mi/h\n\n", "In sympy units you convert from expr1 to expr2 by dividing:\nIn [120]: import sympy.physics.units as units\n\nIn [121]: expr1 = units.m / units.s\n\nIn [122]: expr2 = units.miles / units.hour\n\nIn [123]: a = (1397/3125) * expr1 / expr2\n\nIn [124]: a\nOut[124]: 1\n\nThe only issue is that you end up with a dimensionless quantity. You might also consider the Quantities package for this type of thing:\nIn [125]: import quantities as pq\n\nIn [126]: a = pq.Quantity(1397/3125, 'm/s')\n\nIn [127]: a\nOut[127]: array(0.44703999999999999) * m/s\n\nIn [128]: a.units = pq.mile / pq.hour\n\nIn [129]: a\nOut[129]: array(1.0) * mi/h\n\nThere's also Unum.\nI don't know of a PDF version of the sympy docs, but you might be able to check the distribution out from their repository and use Sphinx to generate a PDF for yourself. \n" ]
[ 2, 2, 1 ]
[]
[]
[ "python", "sympy" ]
stackoverflow_0002038100_python_sympy.txt
Q: DateTimeProperty has error being set to a datetime in Google App Engine I'm having a weird error with some Google App Engine code I'm writing. My program contains some code like this: import datetime ... class Action(db.Model): visibleDate = db.DateTimeProperty() ... getActionQuery = Action.gql("WHERE user = :user AND __key__ = :key", user = user, key = self.request.get("key")) theAction = getActionQuery.get() .... theAction.visibleDate = datetime.datetime.strptime(self.request.get("visibleDate"), "%Y/%m/%d") Yet this produces the following 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 509, in __call__ handler.post(*groups) File "/Users/redbird/Developer/betterdo-it/main.py", line 132, in post theAction.visibleDate = datetime.datetime.strptime(self.request.get("visibleDate"), "%Y/%m/%d"), File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/__init__.py", line 472, in __set__ value = self.validate(value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/__init__.py", line 2308, in validate (self.name, self.data_type.__name__)) BadValueError: Property visibleDate must be a datetime Any ideas on why this is happening? I've tested it and I know that my time is coming in, is getting converted correctly, but then hits this error. A: I think there's something you missed in your traceback. I'm seeing:datetime.datetime.strptime(self.request.get("visibleDate"), "%Y/%m/%d"), Notice the comma at the end of the line. That comma makes that line return a tuple with your date inside it. I'm assuming you accidentally added the comma, so just remove it and you should be correctly assigning a datetime. To review: from datetime import datetime a = (datetime(2000,1,1),) assert isinstance(a, tuple) a = (datetime(2000,1,1)) assert isinstance(a, datetime)
DateTimeProperty has error being set to a datetime in Google App Engine
I'm having a weird error with some Google App Engine code I'm writing. My program contains some code like this: import datetime ... class Action(db.Model): visibleDate = db.DateTimeProperty() ... getActionQuery = Action.gql("WHERE user = :user AND __key__ = :key", user = user, key = self.request.get("key")) theAction = getActionQuery.get() .... theAction.visibleDate = datetime.datetime.strptime(self.request.get("visibleDate"), "%Y/%m/%d") Yet this produces the following 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 509, in __call__ handler.post(*groups) File "/Users/redbird/Developer/betterdo-it/main.py", line 132, in post theAction.visibleDate = datetime.datetime.strptime(self.request.get("visibleDate"), "%Y/%m/%d"), File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/__init__.py", line 472, in __set__ value = self.validate(value) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/db/__init__.py", line 2308, in validate (self.name, self.data_type.__name__)) BadValueError: Property visibleDate must be a datetime Any ideas on why this is happening? I've tested it and I know that my time is coming in, is getting converted correctly, but then hits this error.
[ "I think there's something you missed in your traceback.\nI'm seeing:datetime.datetime.strptime(self.request.get(\"visibleDate\"), \"%Y/%m/%d\"),\nNotice the comma at the end of the line.\nThat comma makes that line return a tuple with your date inside it. I'm assuming you accidentally added the comma, so just remove it and you should be correctly assigning a datetime.\nTo review:\nfrom datetime import datetime\na = (datetime(2000,1,1),)\nassert isinstance(a, tuple)\na = (datetime(2000,1,1))\nassert isinstance(a, datetime)\n\n" ]
[ 5 ]
[]
[]
[ "datetime", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002042913_datetime_google_app_engine_google_cloud_datastore_python.txt
Q: How do I add content before in extended page? (KID templates) I've got master.kid (simplified): <html> <head py:match="item.tag == 'head'"> <title>My Site</title> </head> <body py:match="item.tag == 'body'"> <h1>My Site</h1> <div py:replace="item[:]"></div> <p id="footer">Copyright Blixt 2010</p> </body> </html> And mypage.kid: <html> <head></head> <body> <p>Hello World!</p> </body> </html> Now I want it to be possible to add more content before the </body> tag in the resulting HTML, specific to mypage.kid. Basically the result should be something this: <html> <head> <title>My Site</title> </head> <body> <h1>My Site</h1> <p>Hello World!</p> <p id="footer">Copyright Blixt 2010</p> <script type="text/javascript">alert('Hello World!');</script> </body> </html> The <script> tag should be specified in mypage.kid. It's okay if I have to modify master.kid to optionally support additional content before the </body> tag, but what the content is has to be specified in mypage.kid. At first I figured adding an element before the </body> tag in master.kid with py:match="item.tag == 'bodyend'" would work. The problem is that it uses the position of the element in mypage.kid, and not the position of the element doing py:match. So if I put the <bodyend> tag before </body> in mypage.kid, it is imported before <p id="footer">, and if I put it below </body> it will stay there. How do I set up master.kid and mypage.kid to support adding content immediately before the </body> tag? A: The best solution I've found is the following: master.kid: <html> <head py:match="item.tag == 'head'"> <title>My Site</title> </head> <body py:match="item.tag == 'body'"> <h1>My Site</h1> <div py:replace="item[:]"></div> <p id="footer">Copyright Blixt 2010</p> <div py:if="defined('body_end')" py:replace="body_end()"></div> </body> </html> mypage.kid: <html> <head></head> <body> <p>Hello World!</p> <div py:def="body_end()" py:strip="True"> <script type="text/javascript">alert('Hello World!');</script> </div> </body> </html> The master.kid page checks for a variable defined as body_end, and if there is such a variable, it will call it, replacing the contents of the element before </body> (otherwise it will output nothing). Any page that needs to output content before </body> will define the body_end function using py:def="body_end()". The py:strip="True" is there to remove the wrapping <div>.
How do I add content before in extended page? (KID templates)
I've got master.kid (simplified): <html> <head py:match="item.tag == 'head'"> <title>My Site</title> </head> <body py:match="item.tag == 'body'"> <h1>My Site</h1> <div py:replace="item[:]"></div> <p id="footer">Copyright Blixt 2010</p> </body> </html> And mypage.kid: <html> <head></head> <body> <p>Hello World!</p> </body> </html> Now I want it to be possible to add more content before the </body> tag in the resulting HTML, specific to mypage.kid. Basically the result should be something this: <html> <head> <title>My Site</title> </head> <body> <h1>My Site</h1> <p>Hello World!</p> <p id="footer">Copyright Blixt 2010</p> <script type="text/javascript">alert('Hello World!');</script> </body> </html> The <script> tag should be specified in mypage.kid. It's okay if I have to modify master.kid to optionally support additional content before the </body> tag, but what the content is has to be specified in mypage.kid. At first I figured adding an element before the </body> tag in master.kid with py:match="item.tag == 'bodyend'" would work. The problem is that it uses the position of the element in mypage.kid, and not the position of the element doing py:match. So if I put the <bodyend> tag before </body> in mypage.kid, it is imported before <p id="footer">, and if I put it below </body> it will stay there. How do I set up master.kid and mypage.kid to support adding content immediately before the </body> tag?
[ "The best solution I've found is the following:\nmaster.kid:\n<html>\n<head py:match=\"item.tag == 'head'\">\n <title>My Site</title>\n</head>\n<body py:match=\"item.tag == 'body'\">\n <h1>My Site</h1>\n <div py:replace=\"item[:]\"></div>\n <p id=\"footer\">Copyright Blixt 2010</p>\n <div py:if=\"defined('body_end')\" py:replace=\"body_end()\"></div>\n</body>\n</html>\n\nmypage.kid:\n<html>\n<head></head>\n<body>\n <p>Hello World!</p>\n <div py:def=\"body_end()\" py:strip=\"True\">\n <script type=\"text/javascript\">alert('Hello World!');</script>\n </div>\n</body>\n</html>\n\nThe master.kid page checks for a variable defined as body_end, and if there is such a variable, it will call it, replacing the contents of the element before </body> (otherwise it will output nothing).\nAny page that needs to output content before </body> will define the body_end function using py:def=\"body_end()\". The py:strip=\"True\" is there to remove the wrapping <div>.\n" ]
[ 1 ]
[]
[]
[ "python", "turbogears" ]
stackoverflow_0001999300_python_turbogears.txt
Q: Django: Increment blog entry view count by one. Is this efficient? I have the following code in my index view. latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10] for entry in latest_entry_list: entry.views = entry.views + 1 entry.save() If there are ten (the limit) rows returned from the initial query, will the save issue 10 seperate updated calls to the database, or is Django "smart" enough to issue just one update call? Is there a more efficient method to achieve this result? A: You can use F() objects for this. Here is how you import F: from django.db.models import F New in Django 1.1. Calls to update can also use F() objects to update one field based on the value of another field in the model. This is especially useful for incrementing counters based upon their current value. Entry.objects.filter(is_published=True).update(views=F('views')+1) Although you can't do an update on a sliced query set... edit: actually you can... This can be done completely in django ORM. You need two SQL queries: Do your filter and collect a list of primary keys Do an update on a non-sliced query set of items matching any of those primary keys. Getting the non-sliced query set is the hard bit. I wondered about using in_bulk but that returns a dictionary, not a query set. One would usually use Q objects to do complex OR type queries and that will work, but pk__in does the job much more simply. latest_entry_ids = Entry.objects.filter(is_published=True)\ .order_by('-date_published') .values_list('id', flat=True)[:10] non_sliced_query_set = Entry.objects.filter(pk__in=latest_entry_ids) n = non_sliced_query_set.update(views=F('views')+1) print n or 0, 'items updated' Due to the way that django executes queries lazily, this results in just 2 database hits, no matter how many items are updated. A: You could handle the updates in a single transaction, which could improve performance significantly. Use a separate function, decorated with @transaction.commit_manually. @transaction.commit_manually def update_latest_entries(latest_entry_list): for entry in latest_entry_list: entry.views += 1 entry.save() transaction.commit() A: If you really need the efficiency, at the moment you'd have to drop down into SQL and run the update yourself. That's not worth the added complexity in this case, though. By Django 1.1 you'll be able to do this in a single SQL call via the ORM using F() objects to reference fields in the update value. A: Revised You're updating 10 separate, individual, distinct objects. The 10 separate, individual, distinct updates can't easily be collapsed into one magical update that somehow touches 10 objects. A: A performance improvement to the previous entry. This results in one database hit, with a subquery. latest_entry_query_set = Entry.objects.filter(is_published=True) .order_by('-date_published')[:10] non_sliced_query_set = Entry.objects.filter(pk__in=latest_entry_query_set.values('id')) n = non_sliced_query_set.update(views=F('views')+1) print n or 0, 'items updated'
Django: Increment blog entry view count by one. Is this efficient?
I have the following code in my index view. latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10] for entry in latest_entry_list: entry.views = entry.views + 1 entry.save() If there are ten (the limit) rows returned from the initial query, will the save issue 10 seperate updated calls to the database, or is Django "smart" enough to issue just one update call? Is there a more efficient method to achieve this result?
[ "You can use F() objects for this. \nHere is how you import F: from django.db.models import F\nNew in Django 1.1.\nCalls to update can also use F() objects to update one field based on the value of another field in the model. This is especially useful for incrementing counters based upon their current value.\nEntry.objects.filter(is_published=True).update(views=F('views')+1)\n\nAlthough you can't do an update on a sliced query set... edit: actually you can...\nThis can be done completely in django ORM. You need two SQL queries:\n\nDo your filter and collect a list of primary keys\nDo an update on a non-sliced query set of items matching any of those primary keys.\n\nGetting the non-sliced query set is the hard bit. I wondered about using in_bulk but that returns a dictionary, not a query set. One would usually use Q objects to do complex OR type queries and that will work, but pk__in does the job much more simply.\nlatest_entry_ids = Entry.objects.filter(is_published=True)\\\n .order_by('-date_published')\n .values_list('id', flat=True)[:10] \nnon_sliced_query_set = Entry.objects.filter(pk__in=latest_entry_ids) \nn = non_sliced_query_set.update(views=F('views')+1) \nprint n or 0, 'items updated'\n\nDue to the way that django executes queries lazily, this results in just 2 database hits, no matter how many items are updated. \n", "You could handle the updates in a single transaction, which could improve performance significantly. Use a separate function, decorated with @transaction.commit_manually.\n@transaction.commit_manually\ndef update_latest_entries(latest_entry_list):\n for entry in latest_entry_list:\n entry.views += 1\n entry.save()\n transaction.commit()\n\n", "If you really need the efficiency, at the moment you'd have to drop down into SQL and run the update yourself. That's not worth the added complexity in this case, though.\nBy Django 1.1 you'll be able to do this in a single SQL call via the ORM using F() objects to reference fields in the update value.\n", "Revised\nYou're updating 10 separate, individual, distinct objects.\nThe 10 separate, individual, distinct updates can't easily be collapsed into one magical update that somehow touches 10 objects.\n", "A performance improvement to the previous entry. This results in one database hit, with a subquery.\nlatest_entry_query_set = Entry.objects.filter(is_published=True)\n .order_by('-date_published')[:10] \nnon_sliced_query_set = Entry.objects.filter(pk__in=latest_entry_query_set.values('id')) \nn = non_sliced_query_set.update(views=F('views')+1) \nprint n or 0, 'items updated'\n\n" ]
[ 69, 13, 3, 2, 2 ]
[]
[]
[ "database", "django", "performance", "python" ]
stackoverflow_0000447117_database_django_performance_python.txt
Q: exposing std::vector with boost.python I have written some C++ code that generates a std::vector. I also have a python script that manipulates some data that, for now, I am declaring like this (below). import numpy x = numpy.random.randn(1000) y = numpy.random.randn(1000) I can run the script fine. From my C++ code: using namespace boost::python; try{ Py_Initialize(); object main = import("__main__"); object global(main.attr("__dict__")); object result = exec_file("scatterPlot.py", global, global); Py_Finalize(); } catch(error_already_set){ PyErr_Print(); } return; I have no idea how to get my C++ data to python. I've around quite a bit, but there doesn't seem to be anything definitive. I have in my C++ BOOST_PYTHON_MODULE(vector_indexing_suite_ext){ boost::python::class_<std::vector<double> >("PyVec") .def(boost::python::vector_indexing_suite<std::vector<double> >()); } This seems to work, but as I understand, it only provides a class "PyVec" for my python script but not the data I need. Am I wrong? I've also seen some other people use boost::shared_ptr in a python mailing list. I also found this example but found it confusing. I can think of a few approaches Pass something to the boost::python::exec_file method Using the boost_indexing_suite_ext Uinsg boost::shared_ptr Which approach is easiest to get going? No approach seems clear to me. Here are some more links I've looked at: from the boost website from the python website another mailing list thread UPDATE: This works for passing an int to my python code like below int main(){ int five_squared=0; int a =3; try { Py_Initialize(); object main_module = import("__main__"); object main_namespace = main_module.attr("__dict__"); main_namespace["var"]=a; object ignored = exec("result = 5 ** var", main_namespace); five_squared = extract<int>(main_namespace["result"]); } catch( error_already_set ) { PyErr_Print(); } std::cout << five_squared << std::endl; return 0; } But I want to pass a vector, when I try to do that in a similar fashion as above I get this error TypeError: No to_python (by-value) converter found for C++ type: std::vector > So, obviously I need to tell python how to deal with std::vector. I think this code could help with that. BOOST_PYTHON_MODULE(vector_indexing_suite_ext){ boost::python::class_<std::vector<double> >("PyVec") .def(boost::python::vector_indexing_suite<std::vector<double> >()); } But since std::vector is pretty common, there must be a defined way to do this... right? A: The following code works for me (Python 2.6, Boost 1.39). This is almost the same as your code, except without the BOOST_PYTHON_MODULE line itself (but with the class_ definition for the vector). BOOST_PYTHON_MODULE only needs to be used when creating extension modules. #include <iostream> #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> using namespace boost::python; using namespace std; int main() { vector<double> vec; vec.push_back(1.2); vec.push_back(3.4); try { Py_Initialize(); boost::python::class_<std::vector<double> >("PyVec") .def(boost::python::vector_indexing_suite<std::vector<double> >()); object main_module = import("__main__"); object globals = main_module.attr("__dict__"); globals["var"]=vec; object ignored = exec("result = sum(var)", globals, globals); double result = extract<double>(globals["result"]); std::cout << result << std::endl; } catch( error_already_set ) { PyErr_Print(); } return 0; } A: I'm not sure if I understand correctly. After exporting your class "PyVec" which can hold std::vector<double>, you can export any c++ function taking vector as input or return type. So of course you can populate your vector within c++ and access this data in Python with the interfaced type "PyVec".
exposing std::vector with boost.python
I have written some C++ code that generates a std::vector. I also have a python script that manipulates some data that, for now, I am declaring like this (below). import numpy x = numpy.random.randn(1000) y = numpy.random.randn(1000) I can run the script fine. From my C++ code: using namespace boost::python; try{ Py_Initialize(); object main = import("__main__"); object global(main.attr("__dict__")); object result = exec_file("scatterPlot.py", global, global); Py_Finalize(); } catch(error_already_set){ PyErr_Print(); } return; I have no idea how to get my C++ data to python. I've around quite a bit, but there doesn't seem to be anything definitive. I have in my C++ BOOST_PYTHON_MODULE(vector_indexing_suite_ext){ boost::python::class_<std::vector<double> >("PyVec") .def(boost::python::vector_indexing_suite<std::vector<double> >()); } This seems to work, but as I understand, it only provides a class "PyVec" for my python script but not the data I need. Am I wrong? I've also seen some other people use boost::shared_ptr in a python mailing list. I also found this example but found it confusing. I can think of a few approaches Pass something to the boost::python::exec_file method Using the boost_indexing_suite_ext Uinsg boost::shared_ptr Which approach is easiest to get going? No approach seems clear to me. Here are some more links I've looked at: from the boost website from the python website another mailing list thread UPDATE: This works for passing an int to my python code like below int main(){ int five_squared=0; int a =3; try { Py_Initialize(); object main_module = import("__main__"); object main_namespace = main_module.attr("__dict__"); main_namespace["var"]=a; object ignored = exec("result = 5 ** var", main_namespace); five_squared = extract<int>(main_namespace["result"]); } catch( error_already_set ) { PyErr_Print(); } std::cout << five_squared << std::endl; return 0; } But I want to pass a vector, when I try to do that in a similar fashion as above I get this error TypeError: No to_python (by-value) converter found for C++ type: std::vector > So, obviously I need to tell python how to deal with std::vector. I think this code could help with that. BOOST_PYTHON_MODULE(vector_indexing_suite_ext){ boost::python::class_<std::vector<double> >("PyVec") .def(boost::python::vector_indexing_suite<std::vector<double> >()); } But since std::vector is pretty common, there must be a defined way to do this... right?
[ "The following code works for me (Python 2.6, Boost 1.39). This is almost the same as your code, except without the BOOST_PYTHON_MODULE line itself (but with the class_ definition for the vector). BOOST_PYTHON_MODULE only needs to be used when creating extension modules.\n#include <iostream>\n#include <boost/python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\nusing namespace boost::python;\nusing namespace std;\n\nint main()\n{\n vector<double> vec;\n vec.push_back(1.2);\n vec.push_back(3.4);\n try { \n Py_Initialize();\n\n boost::python::class_<std::vector<double> >(\"PyVec\")\n .def(boost::python::vector_indexing_suite<std::vector<double> >());\n\n object main_module = import(\"__main__\");\n object globals = main_module.attr(\"__dict__\");\n globals[\"var\"]=vec;\n object ignored = exec(\"result = sum(var)\", globals, globals);\n double result = extract<double>(globals[\"result\"]);\n std::cout << result << std::endl;\n } catch( error_already_set ) {\n PyErr_Print();\n }\n return 0;\n}\n\n", "I'm not sure if I understand correctly. After exporting your class \"PyVec\" which can hold std::vector<double>, you can export any c++ function taking vector as input or return type. So of course you can populate your vector within c++ and access this data in Python with the interfaced type \"PyVec\".\n" ]
[ 12, 3 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0001937135_boost_python_c++_python.txt
Q: Pythonize Me: how to manage caller context variables in Python? (Python/Django) I'm trying to refactor a fairly hefty view function in Django. There are too many variables floating around and it's a huge function. Ideally, I want to modularize the view into logical functions. However, I have to pass the function context around to get easy access to the variables. For example: def complex_view(request, slug): some complex logic which creates variable abc ... ... some more complex logic which uses variable abc ... ... etc. Should become something like: def complex_view(request, slug): process_X() ...somehow pass variables and context to next function... process_Y() ... etc. def process_X(): ... def process Y(): ... I can think of a few ways to do this, some of which were pointed out in this page: http://mail.python.org/pipermail/tutor/2009-February/067506.html a. Subfunctions defined in the master view. This seems kludgey since it's hard to tell which variables are shared and which aren't. b. Passing locals() in as a dictionary. This is also kludgey because there are now two separate ways of accessing a variables: xyz and contextDict['xyz']. AND you have to use one in call N, and the next in call N+1 on the stack. c. Brute force pass in all variables to each function call and return relevant vars. This gets very tedious when there's a lot of vars involved. d. In C++/C#, I would simply create a class MyComplexViewContext, define all the shared variables, and create member functions to carry out the work. Then you can use self.xyz for everything inside that class. I suppose I could use this method in Python as well. Not sure if this is the best way though. What's your take on the preferred way to do this in Python/Django? A: I like (d) - Create a class for it, and use member functions to do the work. In Django, a view is just a 'callable' that accepts an HTTPRequest object, and whatever other paramaters your URL routing passes to it. Python classes can be callable just like functions, if you define a __call__ method on them, like this: class MyView(object): def __call__(self, request, slug) # do stuff here def helper_method(self): # etc. Then you can name the class in your urls.py file, and it will be called like any other python function. Doing this also lets you turn similar views into object instances: class MyView(object): def __init__(self, parameters): # initialize instance def __call__(self, request, slug): # main view code goes here first_view = MyView("some parameter") second_view = MyView("some other parameter") # creates second object instance and in urls.py, reference the objects (rather than the class) -- the objects can be called like functions as well. Other tricks are to use inheritance to define similar views, or to provide some general functionality for a number of similar views in a base class, which specialized view classes then inherit from. You can see this slideshow by Simon Willison for more details, or this snippet for a concrete example A: May I suggest to use something similar to d), like so: class ComplexView_SharedVariables: # Shared variables (to be used as instance variables, not class variables!) a = "somevalue" b = ... c = ... class ComplexView_Methods1: ... some functionality ... class ComplexView_Methods2: ... some more functionality ... class ComplexView_All(ComplexView_SharedVariables, ComplexView_Methods1, ComplexView_Methods2): # This class puts together all functionality and shared variables pass With this procedure, you can even split the classes into different files (if that's possible with Django, I don't have experience with it).
Pythonize Me: how to manage caller context variables in Python? (Python/Django)
I'm trying to refactor a fairly hefty view function in Django. There are too many variables floating around and it's a huge function. Ideally, I want to modularize the view into logical functions. However, I have to pass the function context around to get easy access to the variables. For example: def complex_view(request, slug): some complex logic which creates variable abc ... ... some more complex logic which uses variable abc ... ... etc. Should become something like: def complex_view(request, slug): process_X() ...somehow pass variables and context to next function... process_Y() ... etc. def process_X(): ... def process Y(): ... I can think of a few ways to do this, some of which were pointed out in this page: http://mail.python.org/pipermail/tutor/2009-February/067506.html a. Subfunctions defined in the master view. This seems kludgey since it's hard to tell which variables are shared and which aren't. b. Passing locals() in as a dictionary. This is also kludgey because there are now two separate ways of accessing a variables: xyz and contextDict['xyz']. AND you have to use one in call N, and the next in call N+1 on the stack. c. Brute force pass in all variables to each function call and return relevant vars. This gets very tedious when there's a lot of vars involved. d. In C++/C#, I would simply create a class MyComplexViewContext, define all the shared variables, and create member functions to carry out the work. Then you can use self.xyz for everything inside that class. I suppose I could use this method in Python as well. Not sure if this is the best way though. What's your take on the preferred way to do this in Python/Django?
[ "I like (d) - Create a class for it, and use member functions to do the work.\nIn Django, a view is just a 'callable' that accepts an HTTPRequest object, and whatever other paramaters your URL routing passes to it.\nPython classes can be callable just like functions, if you define a __call__ method on them, like this:\nclass MyView(object):\n def __call__(self, request, slug)\n # do stuff here\n\n def helper_method(self):\n # etc.\n\nThen you can name the class in your urls.py file, and it will be called like any other python function.\nDoing this also lets you turn similar views into object instances:\nclass MyView(object):\n def __init__(self, parameters):\n # initialize instance\n\n def __call__(self, request, slug):\n # main view code goes here\n\nfirst_view = MyView(\"some parameter\")\nsecond_view = MyView(\"some other parameter\") # creates second object instance\n\nand in urls.py, reference the objects (rather than the class) -- the objects can be called like functions as well.\nOther tricks are to use inheritance to define similar views, or to provide some general functionality for a number of similar views in a base class, which specialized view classes then inherit from.\nYou can see this slideshow by Simon Willison for more details, or this snippet for a concrete example\n", "May I suggest to use something similar to d), like so:\nclass ComplexView_SharedVariables:\n # Shared variables (to be used as instance variables, not class variables!)\n a = \"somevalue\"\n b = ...\n c = ...\n\nclass ComplexView_Methods1:\n ... some functionality ...\n\nclass ComplexView_Methods2:\n ... some more functionality ...\n\nclass ComplexView_All(ComplexView_SharedVariables, ComplexView_Methods1, ComplexView_Methods2):\n # This class puts together all functionality and shared variables\n pass\n\nWith this procedure, you can even split the classes into different files (if that's possible with Django, I don't have experience with it).\n" ]
[ 10, 0 ]
[]
[]
[ "django", "django_context", "python" ]
stackoverflow_0002044941_django_django_context_python.txt
Q: Scripting HTTP more effeciently Often times I want to automate http queries. I currently use Java(and commons http client), but would probably prefer a scripting based approach. Something really quick and simple. Where I can set a header, go to a page and not worry about setting up the entire OO lifecycle, setting each header, calling up an html parser... I am looking for a solution in ANY language, preferable scripting A: Mechanize for Python seems easy to use: http://wwwsearch.sourceforge.net/mechanize/ A: Have a look at Selenium. It generates code for C#, Java, Perl, PHP, Python, and Ruby if you need to customize the script. A: Watir sounds close to what you want although it (like Selenium linked to in another answer) actually opens up a browser to do stuff. You can see some examples here. Another browser based record + playback approach system is sahi. If your application is uses WSGI, then paste is a nice option. Mechanize linked to in another answer is a "browser in a library" and there are clones in perl, Ruby and Python. The Perl one is the original one and this seems to be the way to go if you don't want a browser. The problem with this approach is that all the front end code (which might rely on JavaScript), won't be exercised. A: My turn : wget or perl with lwp. You'll find example on the linked page. A: If you have simple needs (fetch a page and then parse it), it is hard to beat LWP::Simple and HTML::TreeBuilder. use strict; use warnings; use LWP::Simple; use HTML::TreeBuilder; my $url = 'http://www.example.com'; my $content = get( $url) or die "Couldn't get $url"; my $t = HTML::TreeBuilder->new_from_content( $content ); $t->eof; $t->elementify; # Get first match: my $thing = $t->look_down( _tag => 'p', id => qr/match_this_regex/ ); print $thing ? $thing->as_text : "No match found\n"; # Get all matches: my @things = $t->look_down( _tag => 'p', id => qr/match_this_regex/ ); print $_ ? $_->as_text : "No match found" for @things; A: I'm testing ReST APIs at the moment and found the ReST Client very nice. It's a GUI program, but nonetheless you can save and restore queries as XML files (or let them be generated), embed, write test scripts, and so on. And it's Java based (which is not an ad-hoc advantage, but you mentioned it). Minus points for recording sessions. The ReST Client is good for stateless "one-shots". If it doesn't suit your needs, I'd go for the already mentioned Mechanize (or WWW-Mechanize, as it is called at CPAN). A: Depending on exactly what you're doing the easiest solution looks to be bash + curl. The man page for the latter is available here: http://curl.haxx.se/docs/manpage.html You can do posts as well as gets, HTTPS, show headers, work with cookies, basic and digest HTTP authentication, tunnel through all sorts of proxies, including NTLM on *nix amongst other things. curl is also available as shared library with C and PHP support. HTH C. A: Python urllib may be what you're looking for. Alternatively powershell exposes the full .NET http library in a scripting environment. A: Twill is pretty good and made for testing. It can be used as script, in an interactive session or within a Python program. A: Perl and WWW::Mechanize can make web scraping etc simple and easy, including easy handling of forms (let's say you want to go to a login page, fill in a username and password and submit the form, handling cookies / hidden session identifiers just as a browser would...) Similarly, finding or extracting links from the fetched page is trivial. If you need to parse stuff out of the resulting pages that WWW::Mechanize can't easily help with, then feed the result to HTML::TreeBuilder to make parsing easy. A: What about using PHP+Curl, or just bash? A: Some ruby libraries: httparty: really interesting, the philosophy is interesting. mechanize: classic good-quality web automatization library. scrubYt: puzzling at first glance but fun to use.
Scripting HTTP more effeciently
Often times I want to automate http queries. I currently use Java(and commons http client), but would probably prefer a scripting based approach. Something really quick and simple. Where I can set a header, go to a page and not worry about setting up the entire OO lifecycle, setting each header, calling up an html parser... I am looking for a solution in ANY language, preferable scripting
[ "Mechanize for Python seems easy to use: http://wwwsearch.sourceforge.net/mechanize/\n", "Have a look at Selenium. It generates code for C#, Java, Perl, PHP, Python, and Ruby if you need to customize the script.\n", "Watir sounds close to what you want although it (like Selenium linked to in another answer) actually opens up a browser to do stuff. You can see some examples here. Another browser based record + playback approach system is sahi.\nIf your application is uses WSGI, then paste is a nice option. \nMechanize linked to in another answer is a \"browser in a library\" and there are clones in perl, Ruby and Python. The Perl one is the original one and this seems to be the way to go if you don't want a browser. The problem with this approach is that all the front end code (which might rely on JavaScript), won't be exercised. \n", "My turn : wget or perl with lwp. You'll find example on the linked page.\n", "If you have simple needs (fetch a page and then parse it), it is hard to beat LWP::Simple and HTML::TreeBuilder.\nuse strict;\nuse warnings;\n\nuse LWP::Simple;\nuse HTML::TreeBuilder;\n\nmy $url = 'http://www.example.com';\nmy $content = get( $url) or die \"Couldn't get $url\";\n\nmy $t = HTML::TreeBuilder->new_from_content( $content );\n$t->eof;\n$t->elementify;\n\n# Get first match:\nmy $thing = $t->look_down( _tag => 'p', id => qr/match_this_regex/ );\n\nprint $thing ? $thing->as_text : \"No match found\\n\";\n\n# Get all matches:\nmy @things = $t->look_down( _tag => 'p', id => qr/match_this_regex/ );\n\nprint $_ ? $_->as_text : \"No match found\" for @things;\n\n", "I'm testing ReST APIs at the moment and found the ReST Client very nice. It's a GUI program, but nonetheless you can save and restore queries as XML files (or let them be generated), embed, write test scripts, and so on. And it's Java based (which is not an ad-hoc advantage, but you mentioned it).\nMinus points for recording sessions. The ReST Client is good for stateless \"one-shots\".\nIf it doesn't suit your needs, I'd go for the already mentioned Mechanize (or WWW-Mechanize, as it is called at CPAN).\n", "Depending on exactly what you're doing the easiest solution looks to be bash + curl.\nThe man page for the latter is available here:\nhttp://curl.haxx.se/docs/manpage.html\nYou can do posts as well as gets, HTTPS, show headers, work with cookies, basic and digest HTTP authentication, tunnel through all sorts of proxies, including NTLM on *nix amongst other things.\ncurl is also available as shared library with C and PHP support.\nHTH\nC.\n", "Python urllib may be what you're looking for.\nAlternatively powershell exposes the full .NET http library in a scripting environment.\n", "Twill is pretty good and made for testing. It can be used as script, in an interactive session or within a Python program.\n", "Perl and WWW::Mechanize can make web scraping etc simple and easy, including easy handling of forms (let's say you want to go to a login page, fill in a username and password and submit the form, handling cookies / hidden session identifiers just as a browser would...)\nSimilarly, finding or extracting links from the fetched page is trivial.\nIf you need to parse stuff out of the resulting pages that WWW::Mechanize can't easily help with, then feed the result to HTML::TreeBuilder to make parsing easy.\n", "What about using PHP+Curl, or just bash?\n", "Some ruby libraries:\n\nhttparty: really interesting, the philosophy is interesting.\nmechanize: classic good-quality web automatization library.\nscrubYt: puzzling at first glance but fun to use.\n\n" ]
[ 6, 6, 6, 6, 6, 4, 3, 2, 2, 2, 0, 0 ]
[]
[]
[ "http", "perl", "python", "ruby", "scripting" ]
stackoverflow_0002043058_http_perl_python_ruby_scripting.txt
Q: Pass session information from php to python securely? (in agile) I have a sign up process that is in a legacy framework and we are trying to switch to a new framework...in fact a different language. So let's say that there are 3 steps in the sign up process and each of those 3 steps has it's own file(step1.php, step2.php, step3.php). Now if I want to change page2.php to a python file I will still need the session information from page1.php. How can I transfer this information between the two pages while maintaining a valid session and obviously security. We want to integrate this language switch in the same repository as the original one and doing releases of the new changes. So that's the agile part. (I'm still not sold that this is the best way to do it but I'm more curious) A: In PHP, store the session information in a database, encoded in JSON. In Python, pull the session ID from the cookie and look up the session information in the database.
Pass session information from php to python securely? (in agile)
I have a sign up process that is in a legacy framework and we are trying to switch to a new framework...in fact a different language. So let's say that there are 3 steps in the sign up process and each of those 3 steps has it's own file(step1.php, step2.php, step3.php). Now if I want to change page2.php to a python file I will still need the session information from page1.php. How can I transfer this information between the two pages while maintaining a valid session and obviously security. We want to integrate this language switch in the same repository as the original one and doing releases of the new changes. So that's the agile part. (I'm still not sold that this is the best way to do it but I'm more curious)
[ "In PHP, store the session information in a database, encoded in JSON. In Python, pull the session ID from the cookie and look up the session information in the database.\n" ]
[ 2 ]
[]
[]
[ "php", "python", "session" ]
stackoverflow_0002045131_php_python_session.txt
Q: Good backend for downloading nzb files to seperate directories I'm laying out a download management that will segregate each users downloads, separate watched directories each download to their own folders, can't see each others queues, etc. I wanted to use Hellanzb with xml-rpc, however it does not seem to allow me to set separate download directories for each file. I want to avoid trying to guess where it goes from the file names, but if that is the best option then so be it. Could you suggest any applicable libraries or programs I could tie to? Thanks, Chance A: I'd check out http://github.com/maddox/pyrot. It may do what you need.
Good backend for downloading nzb files to seperate directories
I'm laying out a download management that will segregate each users downloads, separate watched directories each download to their own folders, can't see each others queues, etc. I wanted to use Hellanzb with xml-rpc, however it does not seem to allow me to set separate download directories for each file. I want to avoid trying to guess where it goes from the file names, but if that is the best option then so be it. Could you suggest any applicable libraries or programs I could tie to? Thanks, Chance
[ "I'd check out http://github.com/maddox/pyrot. It may do what you need.\n" ]
[ 0 ]
[]
[]
[ "network_programming", "nntp", "python", "usenet", "xml_rpc" ]
stackoverflow_0002045215_network_programming_nntp_python_usenet_xml_rpc.txt
Q: Python XMLRPC: Handling arbitrary exceptions on client-side I'm trying to pass arbitrary exceptions from a XMLRPC server to a client (both Python scripts, exception types are defined on both sides). There's an exemplary client-side implementation at ActiveState Recipes which parses the returned "faultString", compares it with a list of known exceptions and, if found, raises that exception (instead of wrapping it in a xmlrpclib.Fault). Example of an XMLRPC exception response: <?xml version='1.0'?> <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value> <int>1</int> </value> </member> <member> <name>faultString</name> <value> <string>ValueError:</string> </value> </member> </struct> </value> </fault> </methodResponse> The ActiveState recipe splits the "ValueError:" string and compares "ValueError" with ValueError.__name__ (which is in allowed_errors = [ValueError, TypeError], cf. link above). Is it possible to pass all exceptions like this, i.e. automatically raise any exception (derived from Exception or some other base class) on the client side (after it was raised on the server)? The ActiveState script works, but I don't want to register every single exception that could be thrown (must be in allowed_errors). (Bonus question: Is there another technology apart from XMLRPC that could handle this problem properly? Pyro?) A: You could populate the allowed_errors list from __builtins__: [exc for exc in __builtins__ if isinstance(exc, BaseException)] This would handle the common case, for built-in exceptions like ValueError, TypeError, OSError, etc. You could probably do something more advanced like PyYAML and pickle, where they automatically hunt down whatever referenced exception gets sent, but this opens yourself up to malicious attacks. If you want the kind of client/server transparency that automatically raising exceptions from the server on the client implies, Pyro would probably be a better choice than XML-RPC.
Python XMLRPC: Handling arbitrary exceptions on client-side
I'm trying to pass arbitrary exceptions from a XMLRPC server to a client (both Python scripts, exception types are defined on both sides). There's an exemplary client-side implementation at ActiveState Recipes which parses the returned "faultString", compares it with a list of known exceptions and, if found, raises that exception (instead of wrapping it in a xmlrpclib.Fault). Example of an XMLRPC exception response: <?xml version='1.0'?> <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value> <int>1</int> </value> </member> <member> <name>faultString</name> <value> <string>ValueError:</string> </value> </member> </struct> </value> </fault> </methodResponse> The ActiveState recipe splits the "ValueError:" string and compares "ValueError" with ValueError.__name__ (which is in allowed_errors = [ValueError, TypeError], cf. link above). Is it possible to pass all exceptions like this, i.e. automatically raise any exception (derived from Exception or some other base class) on the client side (after it was raised on the server)? The ActiveState script works, but I don't want to register every single exception that could be thrown (must be in allowed_errors). (Bonus question: Is there another technology apart from XMLRPC that could handle this problem properly? Pyro?)
[ "You could populate the allowed_errors list from __builtins__:\n[exc for exc in __builtins__ if isinstance(exc, BaseException)]\n\nThis would handle the common case, for built-in exceptions like ValueError, TypeError, OSError, etc. You could probably do something more advanced like PyYAML and pickle, where they automatically hunt down whatever referenced exception gets sent, but this opens yourself up to malicious attacks.\nIf you want the kind of client/server transparency that automatically raising exceptions from the server on the client implies, Pyro would probably be a better choice than XML-RPC.\n" ]
[ 2 ]
[]
[]
[ "python", "xml_rpc", "xmlrpclib" ]
stackoverflow_0002044904_python_xml_rpc_xmlrpclib.txt
Q: What is the proper way to use str.decode and unicode.encode? What is the proper way to use str.decode and unicode.encode? Eg. print str.decode print unicode.encode A: Ignacio's example is correct but depends on your console being able to display Unicode characters, which on Windows it usually can't. Here's the same thing with only safe string escapes (reprs): >>> '\xe3\x81\x82'.decode('utf-8') # three top-bit-set bytes, representing one character u'\u3042' # Hiragana letter A >>> u'\u3042'.encode('shift-jis') '\x82\xa0' # only requires two bytes in the Shift-JIS encoding >>> unicode('\x82\xa0', 'shift-jis') # alternative way of doing a decode u'\u3042' when you're writing to eg. a file or via a web server, or you're on another operating system where the console supports UTF-8, it's a bit easier. A: print 'あ'.decode('utf-8') print repr(u'あ'.encode('shift-jis')) A: >>> unicode.encode(u"abcd","utf8") 'abcd' #unicode string u"abcd" got encoded to UTF-8 encoded string "abcd" >>> str.decode("abcd","utf8") u'abcd' #UTF-8 string "abcd" got decoded to python's unicode object u"abcd" >>>
What is the proper way to use str.decode and unicode.encode?
What is the proper way to use str.decode and unicode.encode? Eg. print str.decode print unicode.encode
[ "Ignacio's example is correct but depends on your console being able to display Unicode characters, which on Windows it usually can't. Here's the same thing with only safe string escapes (reprs):\n>>> '\\xe3\\x81\\x82'.decode('utf-8') # three top-bit-set bytes, representing one character\nu'\\u3042' # Hiragana letter A\n\n>>> u'\\u3042'.encode('shift-jis')\n'\\x82\\xa0' # only requires two bytes in the Shift-JIS encoding\n\n>>> unicode('\\x82\\xa0', 'shift-jis') # alternative way of doing a decode\nu'\\u3042'\n\nwhen you're writing to eg. a file or via a web server, or you're on another operating system where the console supports UTF-8, it's a bit easier.\n", "print 'あ'.decode('utf-8')\nprint repr(u'あ'.encode('shift-jis'))\n\n", ">>> unicode.encode(u\"abcd\",\"utf8\")\n'abcd' #unicode string u\"abcd\" got encoded to UTF-8 encoded string \"abcd\"\n\n>>> str.decode(\"abcd\",\"utf8\")\nu'abcd' #UTF-8 string \"abcd\" got decoded to python's unicode object u\"abcd\"\n>>>\n\n" ]
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002025969_python.txt
Q: How can I make Python see sqlite? I cannot use sqlite3 (build python package), for the reason that _sqlite3.so file is missing. I found that people had the same problem and they resolved it here. To solve my problem I have to "install sqlite3 and recompile Python". I also found out that the problem can be solved by "building from source and moving the library to /usr/lib/python2.5/lib-dynload/". As I have been told to here, I have to install sqlite from the source and copy newly compiled files to my Python directory (nothing was said about "recompile Python"). Well, I have installed sqlite and now I have to copy something to my /lib-dynload/ directory. I am not sure what exactly I should copy. In my /lib-dynload/ directory I have only .so files. And in my sqlite-3.6.18 I do not have any *.so files (it makes me suspicious). I had this problem since I did not have _sqlite3.so file in /lib-dynload/. By compilation of sqlite I got some new files (for example sqlite3.o and sqlite3.lo) but not _sqlite3.so. P.S. Some details: 1. I use Python 2.6.2 (which I installed locally). 2. I do not have root permissions. 3. I had already sqlite installed globally on the machine by root. 4. I just installed sqlite locally. 5. My OS is CentOS release 5.3 (Final). 6. When I type in Python command line import sqlite3 I get: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/loctopu/opt/lib/python2.6/sqlite3/__init__.py", line 24, in <module> from dbapi2 import * File "/home/loctopu/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: No module named _sqlite3 A: I don't have exact answer, but few hints here To install python from source, you don't need to be root, you can always install at /home/USERNAME/usr, for example when you do configure, do like ./configure --prefix=/home/USERNAME/usr Installing sqlite binaries does not mean its included python extension (instead, sqlite dev files are needed when you compile python) proper import usage of sqlite3 is import sqlite3
How can I make Python see sqlite?
I cannot use sqlite3 (build python package), for the reason that _sqlite3.so file is missing. I found that people had the same problem and they resolved it here. To solve my problem I have to "install sqlite3 and recompile Python". I also found out that the problem can be solved by "building from source and moving the library to /usr/lib/python2.5/lib-dynload/". As I have been told to here, I have to install sqlite from the source and copy newly compiled files to my Python directory (nothing was said about "recompile Python"). Well, I have installed sqlite and now I have to copy something to my /lib-dynload/ directory. I am not sure what exactly I should copy. In my /lib-dynload/ directory I have only .so files. And in my sqlite-3.6.18 I do not have any *.so files (it makes me suspicious). I had this problem since I did not have _sqlite3.so file in /lib-dynload/. By compilation of sqlite I got some new files (for example sqlite3.o and sqlite3.lo) but not _sqlite3.so. P.S. Some details: 1. I use Python 2.6.2 (which I installed locally). 2. I do not have root permissions. 3. I had already sqlite installed globally on the machine by root. 4. I just installed sqlite locally. 5. My OS is CentOS release 5.3 (Final). 6. When I type in Python command line import sqlite3 I get: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/loctopu/opt/lib/python2.6/sqlite3/__init__.py", line 24, in <module> from dbapi2 import * File "/home/loctopu/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ImportError: No module named _sqlite3
[ "I don't have exact answer, but few hints here\n\nTo install python from source, you don't need to be root, you can always install at /home/USERNAME/usr, for example when you do configure, do like ./configure --prefix=/home/USERNAME/usr\nInstalling sqlite binaries does not mean its included python extension (instead, sqlite dev files are needed when you compile python)\nproper import usage of sqlite3 is import sqlite3\n\n" ]
[ 0 ]
[]
[]
[ "pysqlite", "python", "sqlite" ]
stackoverflow_0001481237_pysqlite_python_sqlite.txt
Q: i have '__contains__' ,why error class a(object): def a(self): return True __contains__=a b=a() print 2 in b#why error A: __contains__ is meant to take an argument. a doesn't accept an argument. The following is your example with a working __contains__: >>> class a(object): ... def a(self, item): ... return True ... __contains__=a ... >>> b=a() >>> print 2 in b True A: The signature of __contains__ is: object.__contains__(self, item) as per documentation. You need to extend your "a" method: def a(self, item) class a(object): def a(self, item): return True __contains__=a
i have '__contains__' ,why error
class a(object): def a(self): return True __contains__=a b=a() print 2 in b#why error
[ "__contains__ is meant to take an argument. a doesn't accept an argument.\nThe following is your example with a working __contains__:\n>>> class a(object):\n... def a(self, item):\n... return True\n... __contains__=a\n...\n>>> b=a()\n>>> print 2 in b\nTrue\n\n", "The signature of __contains__ is:\nobject.__contains__(self, item)\nas per documentation. You need to extend your \"a\" method:\ndef a(self, item)\nclass a(object):\n def a(self, item):\n return True\n __contains__=a\n\n" ]
[ 7, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002046209_python.txt
Q: Getting String from A TextCtrl Box How to get the strings from a TextCtrl box? Here is the practice code: import wx class citPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) wx.StaticText(self, -1, "Choose put you would like:", (45, 15)) self.quote = wx.StaticText(self, -1, "1:", wx.Point(275, 180), wx.Size(200, -1)) self.quote = wx.StaticText(self, -1, "2:", wx.Point(275, 230), wx.Size(200, -1)) self.quote = wx.StaticText(self, -1, "3:", wx.Point(275, 280), wx.Size(200, -1)) class nextButton(wx.Button): def __init__(self, parent, id, label, pos): wx.Button.__init__(self, parent, id, label, pos) class cancelButton(wx.Button): def __init__(self, parent, id, label, pos): wx.Button.__init__(self, parent, id, label, pos) class searchBox(wx.TextCtrl): def __init__(self, parent, id, name, pos): wx.TextCtrl.__init__(self, parent, id, name, pos) class minBox(wx.TextCtrl): def __init__(self, parent, id, name, pos): wx.TextCtrl.__init__(self, parent, id, name, pos) class maxBox(wx.TextCtrl): def __init__(self, parent, id, name, pos): wx.TextCtrl.__init__(self, parent, id, name, pos) class checkList(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(600, 600)) self.panel = citPanel(self, -1) self.searchCtrl = searchBox(self.panel, -1, '', (275, 200)) self.Bind(wx.EVT_TEXT, self.EvtText) self.minCtrl = minBox(self.panel, -1, '', (275, 250)) self.Bind(wx.EVT_TEXT, self.EvtText1) self.maxCtrl = maxBox(self.panel, -1, '', (275, 300)) self.Bind(wx.EVT_TEXT, self.EvtText2) nextButton(self.panel, 30, 'Ok', (275, 50)) cancelButton(self.panel, -1, 'Exit', (275, 75)) self.Bind(wx.EVT_BUTTON, self.Clicked) self.Centre() self.Show(True) def EvtText(self, event): num1 = event.GetString() def EvtText1(self, event): num2 = event.GetString() def EvtText2(self, event): num3 = event.GetString() def Clicked(self, event): combo = num1 + num2 + num3 print combo event.Skip() app = wx.App() checkList(None, -1, 'Charlie') app.MainLoop() A: TextCtrlInstance.GetValue() A: Use GetValue(), not GetString() Look at the API: http://docs.wxwidgets.org/stable/wx_wxtextctrl.html
Getting String from A TextCtrl Box
How to get the strings from a TextCtrl box? Here is the practice code: import wx class citPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) wx.StaticText(self, -1, "Choose put you would like:", (45, 15)) self.quote = wx.StaticText(self, -1, "1:", wx.Point(275, 180), wx.Size(200, -1)) self.quote = wx.StaticText(self, -1, "2:", wx.Point(275, 230), wx.Size(200, -1)) self.quote = wx.StaticText(self, -1, "3:", wx.Point(275, 280), wx.Size(200, -1)) class nextButton(wx.Button): def __init__(self, parent, id, label, pos): wx.Button.__init__(self, parent, id, label, pos) class cancelButton(wx.Button): def __init__(self, parent, id, label, pos): wx.Button.__init__(self, parent, id, label, pos) class searchBox(wx.TextCtrl): def __init__(self, parent, id, name, pos): wx.TextCtrl.__init__(self, parent, id, name, pos) class minBox(wx.TextCtrl): def __init__(self, parent, id, name, pos): wx.TextCtrl.__init__(self, parent, id, name, pos) class maxBox(wx.TextCtrl): def __init__(self, parent, id, name, pos): wx.TextCtrl.__init__(self, parent, id, name, pos) class checkList(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(600, 600)) self.panel = citPanel(self, -1) self.searchCtrl = searchBox(self.panel, -1, '', (275, 200)) self.Bind(wx.EVT_TEXT, self.EvtText) self.minCtrl = minBox(self.panel, -1, '', (275, 250)) self.Bind(wx.EVT_TEXT, self.EvtText1) self.maxCtrl = maxBox(self.panel, -1, '', (275, 300)) self.Bind(wx.EVT_TEXT, self.EvtText2) nextButton(self.panel, 30, 'Ok', (275, 50)) cancelButton(self.panel, -1, 'Exit', (275, 75)) self.Bind(wx.EVT_BUTTON, self.Clicked) self.Centre() self.Show(True) def EvtText(self, event): num1 = event.GetString() def EvtText1(self, event): num2 = event.GetString() def EvtText2(self, event): num3 = event.GetString() def Clicked(self, event): combo = num1 + num2 + num3 print combo event.Skip() app = wx.App() checkList(None, -1, 'Charlie') app.MainLoop()
[ "TextCtrlInstance.GetValue()\n\n", "Use GetValue(), not GetString()\nLook at the API:\nhttp://docs.wxwidgets.org/stable/wx_wxtextctrl.html\n" ]
[ 27, 3 ]
[]
[]
[ "python", "textctrl", "wxpython" ]
stackoverflow_0002046338_python_textctrl_wxpython.txt
Q: Compare attributes of a Django Queryset in a template using the `in` Operator I'm trying to use the in operator to determine if a template variable on the current page is also a foreign key in another model. The model is like so: class WishlistItem(models.Model): user = models.ForeignKey(User, related_name='wishlist_items') issue = models.ForeignKey(Issue) On the "Issue" page template, I'm trying to do this: {% if issue in user.wishlist_items %} {% else %} {# A button to add the issue to the user's wishlist #} {% endif %} What I need to do is to get at the issue attribute of the wishlist_items QuerySet for the currently logged-in user and compare it to the issue object of the current page. I'm at a loss for how to do this. Do I need to write a templatetag to do this? A: I ended up solving this by writing a template filter: @register.filter def in_list(obj, arg): "Is the issue in the list?" return obj in (item.issue for item in arg) Then I could do something like this in a template: {% if issue|in_list:user.wishlist_items.all %} I got the idea from the answer on this Stack Overflow question. A: It seems that there's a relationship between User and wishlist issues that you ought to express as a ManyToManyField on the User. If there is extra metadata about the relationship that you need to record in a WishlistItem, then use through=WishlistItem. If the User model is from the auth app, you'll need to extend the User model to achieve this (see this blog post for some help). For example: class MyUser(User): wishlist_issues = models.ManyToManyField(Issue, through=WishlistItem) # ... Then, in your template use: {% if issue not in user.wishlist_issues %} {# A button to add the issue to the user's wishlist #} {% endif %} A: I think what you are refering to should go into the view, more than the template. Of course, you could create some templatetag, however Django's approach to templates is to maintain them as dumb as possible, and move all logic to the view. On the other hand, moving the logic in the view, and then passing the additional information to the template should be quite straightforward, and I would definitely go for that solution. A: wishlist_items is not a queryset - it's a manager. wishlist_items.all IS a queryset, but obviously it is a queryset of WishlistItem objects, not Issue objects. What I would do is handle this logic in the view... something like: user_has_issue = issue in (wl.issue for wl in request.user.wishlist_items.all()) A: If I understood correctly, instead of writing a templatetag for it you can pass that as a parameter of the view. def myView(request): return render_to_response('template.html', {'query': queryToCheckIfIssueInWishList}, RequestContext(request))
Compare attributes of a Django Queryset in a template using the `in` Operator
I'm trying to use the in operator to determine if a template variable on the current page is also a foreign key in another model. The model is like so: class WishlistItem(models.Model): user = models.ForeignKey(User, related_name='wishlist_items') issue = models.ForeignKey(Issue) On the "Issue" page template, I'm trying to do this: {% if issue in user.wishlist_items %} {% else %} {# A button to add the issue to the user's wishlist #} {% endif %} What I need to do is to get at the issue attribute of the wishlist_items QuerySet for the currently logged-in user and compare it to the issue object of the current page. I'm at a loss for how to do this. Do I need to write a templatetag to do this?
[ "I ended up solving this by writing a template filter:\n@register.filter\ndef in_list(obj, arg):\n \"Is the issue in the list?\"\n return obj in (item.issue for item in arg)\n\nThen I could do something like this in a template:\n{% if issue|in_list:user.wishlist_items.all %}\n\nI got the idea from the answer on this Stack Overflow question.\n", "It seems that there's a relationship between User and wishlist issues that you ought to express as a ManyToManyField on the User. If there is extra metadata about the relationship that you need to record in a WishlistItem, then use through=WishlistItem.\nIf the User model is from the auth app, you'll need to extend the User model to achieve this (see this blog post for some help). For example:\nclass MyUser(User):\n wishlist_issues = models.ManyToManyField(Issue, through=WishlistItem)\n # ...\n\nThen, in your template use:\n{% if issue not in user.wishlist_issues %}\n {# A button to add the issue to the user's wishlist #}\n{% endif %}\n\n", "I think what you are refering to should go into the view, more than the template.\nOf course, you could create some templatetag, however Django's approach to templates is to maintain them as dumb as possible, and move all logic to the view. \nOn the other hand, moving the logic in the view, and then passing the additional information to the template should be quite straightforward, and I would definitely go for that solution.\n", "wishlist_items is not a queryset - it's a manager. wishlist_items.all IS a queryset, but obviously it is a queryset of WishlistItem objects, not Issue objects. What I would do is handle this logic in the view... something like:\nuser_has_issue = issue in (wl.issue for wl in request.user.wishlist_items.all())\n\n", "If I understood correctly, instead of writing a templatetag for it you can pass that as a parameter of the view.\ndef myView(request):\n return render_to_response('template.html', \n {'query': queryToCheckIfIssueInWishList}, \n RequestContext(request))\n\n" ]
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001993064_django_python.txt
Q: Find sequences of digits in long integers efficiently Is it possible to find a defined sequence in an integer without converting it to a string? That is, is it possible to do some form of pattern matching directly on integers. I have not thought of one but I keeping thinking there should be a mathematical way of doing this. That's not to say it is more efficient. (edit) I actually what numbers that don't contain the sequences of digits I am looking for. The integers will be large, at least 289 digits. The sequences to find could be anything, "123", "5"(there is a five), "66666" I am interested in a general solution but if you would like to help with the acutal problem I am trying to sovle keep reading. More specifically I am looking for repeating digits of length 4 ie 1324322223313 "2222". I am staring with integers because I will be incrementing though consecutive integers unless I get to an integer with 4 length repeat then I would skip to the the next integer without the repeat. Also I don't what integers with digit larger that 4 ie 12322135 (it has a 5) would be excluded. The problem might also be stated as. Find all integers in the z = range(x,y) such that z[a] does not contain any repeating digits of length 4 and a digit larger than 4. The range(x,y) may be very large (Edit) in response to the comment, Yes I would actually like to generate a list, the problem I have is that I am not sure how I could make a generator that satisfies all the conditions I have. Maybe I should think about this more, I agree it would be simpler, but it might be similar to a generator for prime numbers, there is no such generator. A: You can use this class to have your generator of digits :-) import math class DecimalIndexing: def __init__(self, n): self.n = n def __len__(self): return int(math.floor(math.log10(self.n)+1)) def __getitem__(self, i): if isinstance(i, slice): return [self[x] for x in range(i.start, i.stop, i.step or 1)] else: return (self.n/(10**i))%10 def __iter__(self): for i in xrange(len(self)): yield self[i] you can use it like this: di = DecimalIndexing(31415927) for i in xrange(len(di)): if di[i:i+4] == [9,5,1,4]: print "found" or like this: for i in xrange(len(di)): if di[i:i+3] == [di[i]]*3: print "group of three equal digits at," i or like this: if 5 in di: print "has a five" or like this: if any(x > 5 in di): print "some digit was greater than five" etc. Keep in mind that the digits indices are "reversed", i.e. read from right to left. A: A list of digits is pretty simple. # given n, a long integer digits = [] while n != 0: digits.append( n%10 ) n //= 10 digits.reverse() You can then do your pattern matching on this list of digits. Is that what you're looking for? A: You can make an iterator with the digits ordered from left to right this way >>> import math >>> number = int(123456789012345678901) >>> #Get the maximum power of 10 using a logarithm >>> max_digit = int(math.log10(number)) >>> range_pow = xrange(max_digit, 0, -1) >>> # pot is an iterator with 1000, 100, 10, 1... >>> pot = ( 10**x for x in range_pow) >>> #Get the digits one by one on an iterator >>> digits = ( (number/x)%10 for x in pot ) >>> l = list(digits) >>> print l [1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L] Then you can check if the sequence is present... I'm looking for a easy way to do that through the iterator, something like a state machine to parse the result, but I'm not sure if there's a built-in way to do it without making a list or making the finite state machine by yourself... You can go with something like this, but I think it will kill the performance (compared with a finite state parsing done on low level over the iterator) as you need to build the list, not working directly with iterator: >>> print l [1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L] >>> find = [1,2,3] >>> lf = len(find) >>> for i in xrange(len(l)): ... if find == l[i:i+lf]: ... print 'Found!', i Found! 1 Found! 11 Edited: I've come with a more iterative way to do things... The digits parameter could be refined to create a list from a number, if necessary. import math from itertools import count def find_digits_in_number(digits, number): #Get the maximum power of 10 using a logarithm max_digit = int(math.log10(number)) range_pow = xrange(max_digit, -1, -1) # pot is an iterator with 1000, 100, 10, 1... pot = (10 ** x for x in range_pow) #Get the digits one by one on an iterator dig = ((number / x) % 10 for x in pot) #Current will store a moving windows with the #size of the digits length to check if present current = [] for i in digits: current.append(next(dig)) digits = list(digits) founds = [] #The basic loop is this... #for digit, i in zip(dig, count()): # if current == digits: # founds.append(i) # current.pop(0) # current.append(digit) #But it can also be optimized like this list comprehension, #while it's much less readable [ (founds.append(i) if current == digits else None,\ current.pop(0), current.append(digit)) \ for digit, i in zip(dig, count()) ] #Check last posibility, with the last values if current == digits: founds.append(i + 1) return founds if __name__ == '__main__': assert find_digits_in_number((3, 4, 5), 123456789012345678901) == [2, 12] assert find_digits_in_number((3, 4), 123456789034) == [2, 10] A: Maybe you want to take a look here: Cyclic Numbers; they also have an algorithm to build a cyclic number. This can be useful too: Cycle detection A: @Fortran gives a great solution, it is very versatile. I asked a modified version of this question on mathoverflow.net, They didn't seem to like the question, but I got a great answer. It answers a slightly different question but useful for my application. To test if the digits 4444 are in 35344442345321456754 and assuming I know where I what to look for them then this is a nice solution and obvious once you see it. (35344442345321456754 / 10**13) % 10**4 == 4444
Find sequences of digits in long integers efficiently
Is it possible to find a defined sequence in an integer without converting it to a string? That is, is it possible to do some form of pattern matching directly on integers. I have not thought of one but I keeping thinking there should be a mathematical way of doing this. That's not to say it is more efficient. (edit) I actually what numbers that don't contain the sequences of digits I am looking for. The integers will be large, at least 289 digits. The sequences to find could be anything, "123", "5"(there is a five), "66666" I am interested in a general solution but if you would like to help with the acutal problem I am trying to sovle keep reading. More specifically I am looking for repeating digits of length 4 ie 1324322223313 "2222". I am staring with integers because I will be incrementing though consecutive integers unless I get to an integer with 4 length repeat then I would skip to the the next integer without the repeat. Also I don't what integers with digit larger that 4 ie 12322135 (it has a 5) would be excluded. The problem might also be stated as. Find all integers in the z = range(x,y) such that z[a] does not contain any repeating digits of length 4 and a digit larger than 4. The range(x,y) may be very large (Edit) in response to the comment, Yes I would actually like to generate a list, the problem I have is that I am not sure how I could make a generator that satisfies all the conditions I have. Maybe I should think about this more, I agree it would be simpler, but it might be similar to a generator for prime numbers, there is no such generator.
[ "You can use this class to have your generator of digits :-)\nimport math\n\nclass DecimalIndexing:\n def __init__(self, n):\n self.n = n\n def __len__(self):\n return int(math.floor(math.log10(self.n)+1))\n def __getitem__(self, i):\n if isinstance(i, slice):\n return [self[x] for x in range(i.start, i.stop, i.step or 1)]\n else:\n return (self.n/(10**i))%10\n def __iter__(self):\n for i in xrange(len(self)):\n yield self[i]\n\nyou can use it like this:\ndi = DecimalIndexing(31415927)\nfor i in xrange(len(di)):\n if di[i:i+4] == [9,5,1,4]:\n print \"found\"\n\nor like this:\nfor i in xrange(len(di)):\n if di[i:i+3] == [di[i]]*3:\n print \"group of three equal digits at,\" i\n\nor like this:\nif 5 in di:\n print \"has a five\"\n\nor like this:\nif any(x > 5 in di):\n print \"some digit was greater than five\"\n\netc.\nKeep in mind that the digits indices are \"reversed\", i.e. read from right to left.\n", "A list of digits is pretty simple.\n# given n, a long integer\ndigits = [] \nwhile n != 0:\n digits.append( n%10 )\n n //= 10\ndigits.reverse()\n\nYou can then do your pattern matching on this list of digits. Is that what you're looking for?\n", "You can make an iterator with the digits ordered from left to right this way\n>>> import math\n>>> number = int(123456789012345678901)\n>>> #Get the maximum power of 10 using a logarithm\n>>> max_digit = int(math.log10(number))\n>>> range_pow = xrange(max_digit, 0, -1)\n>>> # pot is an iterator with 1000, 100, 10, 1...\n>>> pot = ( 10**x for x in range_pow)\n>>> #Get the digits one by one on an iterator\n>>> digits = ( (number/x)%10 for x in pot )\n>>> l = list(digits)\n>>> print l\n[1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L]\n\nThen you can check if the sequence is present... I'm looking for a easy way to do that through the iterator, something like a state machine to parse the result, but I'm not sure if there's a built-in way to do it without making a list or making the finite state machine by yourself... \nYou can go with something like this, but I think it will kill the performance (compared with a finite state parsing done on low level over the iterator) as you need to build the list, not working directly with iterator:\n>>> print l\n[1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 0L]\n>>> find = [1,2,3]\n>>> lf = len(find)\n>>> for i in xrange(len(l)):\n... if find == l[i:i+lf]:\n... print 'Found!', i\nFound! 1\nFound! 11\n\nEdited:\nI've come with a more iterative way to do things... The digits parameter could be\nrefined to create a list from a number, if necessary.\nimport math\nfrom itertools import count\n\ndef find_digits_in_number(digits, number):\n #Get the maximum power of 10 using a logarithm\n max_digit = int(math.log10(number))\n range_pow = xrange(max_digit, -1, -1)\n # pot is an iterator with 1000, 100, 10, 1...\n pot = (10 ** x for x in range_pow)\n #Get the digits one by one on an iterator\n dig = ((number / x) % 10 for x in pot)\n\n #Current will store a moving windows with the \n #size of the digits length to check if present\n current = []\n for i in digits:\n current.append(next(dig))\n\n digits = list(digits) \n\n founds = []\n #The basic loop is this...\n #for digit, i in zip(dig, count()):\n # if current == digits:\n # founds.append(i)\n # current.pop(0)\n # current.append(digit)\n\n #But it can also be optimized like this list comprehension, \n #while it's much less readable \n [ (founds.append(i) if current == digits else None,\\\n current.pop(0), current.append(digit)) \\\n for digit, i in zip(dig, count()) ]\n\n #Check last posibility, with the last values\n if current == digits:\n founds.append(i + 1)\n\n return founds\n\n\nif __name__ == '__main__':\n assert find_digits_in_number((3, 4, 5), 123456789012345678901) == [2, 12]\n assert find_digits_in_number((3, 4), 123456789034) == [2, 10]\n\n", "Maybe you want to take a look here: Cyclic Numbers; they also have an algorithm to build a cyclic number.\nThis can be useful too: Cycle detection\n", "@Fortran gives a great solution, it is very versatile.\nI asked a modified version of this question on mathoverflow.net, They didn't seem to like the question, but I got a great answer. It answers a slightly different question but useful for my application.\nTo test if the digits 4444 are in 35344442345321456754 and assuming I know where I what to look for them then this is a nice solution and obvious once you see it.\n(35344442345321456754 / 10**13) % 10**4 == 4444\n\n" ]
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "integer", "pattern_matching", "performance", "python", "sequence" ]
stackoverflow_0002042916_integer_pattern_matching_performance_python_sequence.txt
Q: Creating waitable objects in Python I more or less know how to use select() to take a list of sockets, and only return the ones that are ready to read/write something. The project I'm working on now has a class called 'user'. Each 'user' object contains its own socket. What I would like to do is pass a list of users to a select(), and get back a list of only the users where user.socket is ready to read/write. Any thoughts on where to start on this? Edit: Changed switch() to select(). I need to proofread better. A: You should have your User class implement a fileno(self) method which returns self.thesocket.fileno() -- that's the way to make select work on your own classes (sockets only on windows, arbitrary files on Unix-like systems). Not sure what switch is supposed to me -- don't recognize it as a standard library (or built-in) Python concept...?
Creating waitable objects in Python
I more or less know how to use select() to take a list of sockets, and only return the ones that are ready to read/write something. The project I'm working on now has a class called 'user'. Each 'user' object contains its own socket. What I would like to do is pass a list of users to a select(), and get back a list of only the users where user.socket is ready to read/write. Any thoughts on where to start on this? Edit: Changed switch() to select(). I need to proofread better.
[ "You should have your User class implement a fileno(self) method which returns self.thesocket.fileno() -- that's the way to make select work on your own classes (sockets only on windows, arbitrary files on Unix-like systems). Not sure what switch is supposed to me -- don't recognize it as a standard library (or built-in) Python concept...?\n" ]
[ 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002046727_python_sockets.txt
Q: Tab Completion in Python Command Line Interface - how to catch Tab events I'm writing a little CLI in Python (as an extension to Mercurial) and would like to support tab-completion. Specifically, I would like catch tabs in the prompt and show a list of matching options (just like bash). Example: Enter section name: ext*TAB* extensions extras The problem is I'm not sure how to catch the Tab events. I'm using the ui.prompt() API of Mercurial, which is just calling raw_input() under the hood. As far as I know, raw_input() only returns on 'enter' and if a user enters a tab, the string returned simply includes a "\t". A: For that you use the readline module. Simplest code I can think: import readline COMMANDS = ['extra', 'extension', 'stuff', 'errors', 'email', 'foobar', 'foo'] def complete(text, state): for cmd in COMMANDS: if cmd.startswith(text): if not state: return cmd else: state -= 1 readline.parse_and_bind("tab: complete") readline.set_completer(complete) raw_input('Enter section name: ') Example usage: Enter section name: <tab> email errors extension extra foo foobar stuff Enter section name: e<tab> email errors extension extra Enter section name: ext<tab> extension extra Besides completion, readline provides you with: Line editing Keybinding configuration (emacs and vi modes included) History (up arrow to recall previous values) History searching, saving and loading A: An excellent example of how to do tab-completion in cooperation with readline is supplied in the standard library as the rlcompleter module — you can't use it as-is (it completes based on names currently defined in the Python's main and builtin), but it shows how to do the general task and how to hook it up to readline. A: You should almost certainly be using the cmd module, which already implements tab completion and so on, and probably other parts of what you're trying to do, using the readline module and so on. There's no point reinventing the wheel.
Tab Completion in Python Command Line Interface - how to catch Tab events
I'm writing a little CLI in Python (as an extension to Mercurial) and would like to support tab-completion. Specifically, I would like catch tabs in the prompt and show a list of matching options (just like bash). Example: Enter section name: ext*TAB* extensions extras The problem is I'm not sure how to catch the Tab events. I'm using the ui.prompt() API of Mercurial, which is just calling raw_input() under the hood. As far as I know, raw_input() only returns on 'enter' and if a user enters a tab, the string returned simply includes a "\t".
[ "For that you use the readline module.\nSimplest code I can think:\nimport readline\nCOMMANDS = ['extra', 'extension', 'stuff', 'errors',\n 'email', 'foobar', 'foo']\n\ndef complete(text, state):\n for cmd in COMMANDS:\n if cmd.startswith(text):\n if not state:\n return cmd\n else:\n state -= 1\n\nreadline.parse_and_bind(\"tab: complete\")\nreadline.set_completer(complete)\nraw_input('Enter section name: ')\n\nExample usage:\nEnter section name: <tab>\nemail errors extension extra foo foobar stuff\nEnter section name: e<tab>\nemail errors extension extra \nEnter section name: ext<tab>\nextension extra \n\nBesides completion, readline provides you with:\n\nLine editing\nKeybinding configuration (emacs and vi modes included)\nHistory (up arrow to recall previous values)\nHistory searching, saving and loading\n\n", "An excellent example of how to do tab-completion in cooperation with readline is supplied in the standard library as the rlcompleter module — you can't use it as-is (it completes based on names currently defined in the Python's main and builtin), but it shows how to do the general task and how to hook it up to readline.\n", "You should almost certainly be using the cmd module, which already implements tab completion and so on, and probably other parts of what you're trying to do, using the readline module and so on. There's no point reinventing the wheel.\n" ]
[ 17, 2, 1 ]
[]
[]
[ "mercurial", "python", "raw_input", "tab_completion" ]
stackoverflow_0002046050_mercurial_python_raw_input_tab_completion.txt
Q: Pylons "global name 'c' is not defined" i had setup Pylons v0.9.7, and created a project using genshi. I tried to code an easy test case, but it is not working. code: member.py coding: utf-8 import logging import foo.model from foo.lib.base import * log = logging.getLogger(__name__) class MemberController(BaseController): def index(self): c.title="title" c.mes="message" return render('test.html') code: test.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns:py="http://genshi.edgewall.org/" lang="ja"> <head> <title>${c.title}</title> </head> <body> <p>${c.mes}</p> </body> </html> and Error message(on log) Error - <type 'exceptions.NameError'>: global name 'c' is not defined Please help me find the error. A: c.title="title" requires name c to be defined (globally or locally). You never define anything named c. So, define a suitable name c (one where attribute title can be set!) before you assign anything to c.title! Next hint: from pylons import tmpl_context as c -- you didn't do that from ... import ... as, did you now?-)
Pylons "global name 'c' is not defined"
i had setup Pylons v0.9.7, and created a project using genshi. I tried to code an easy test case, but it is not working. code: member.py coding: utf-8 import logging import foo.model from foo.lib.base import * log = logging.getLogger(__name__) class MemberController(BaseController): def index(self): c.title="title" c.mes="message" return render('test.html') code: test.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns:py="http://genshi.edgewall.org/" lang="ja"> <head> <title>${c.title}</title> </head> <body> <p>${c.mes}</p> </body> </html> and Error message(on log) Error - <type 'exceptions.NameError'>: global name 'c' is not defined Please help me find the error.
[ " c.title=\"title\"\n\nrequires name c to be defined (globally or locally). You never define anything named c.\nSo, define a suitable name c (one where attribute title can be set!) before you assign anything to c.title!\nNext hint: from pylons import tmpl_context as c -- you didn't do that from ... import ... as, did you now?-)\n" ]
[ 2 ]
[]
[]
[ "genshi", "pylons", "python" ]
stackoverflow_0002046789_genshi_pylons_python.txt
Q: File open: Is this bad Python style? To read contents of a file: data = open(filename, "r").read() The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing. EDIT: This has actually bitten me in a project I wrote - it prompted me to ask this question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions. A: Just for the record: This is only slightly longer, and closes the file immediately: from __future__ import with_statement with open(filename, "r") as f: data = f.read() A: It is true that it will close eventually, but eventually might not be soon enough. Especially if you're using this inside a loop, the system might run out of file handles before the GC gets to the file objects. A: The code works exactly as you say it does, but it's bad style nevertheless. Your code relies on assumptions which may be true now, but won't always be true. It's not impossible that your code will be run in a situation where the file being opened and not close does matter. Is it really worth that risk just to save 1 or 2 lines of code? I don't think so. A: No, it's perfectly reasonable Python style IMO, as per your reasoning. Update: There are a lot of comments here about whether file objects get tidied up straight away or not. Rather than speculate, I did some digging. Here's what I see: From a comment in Python's object.h: The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement reference counts. Py_DECREF calls the object's deallocator function when the refcount falls to 0 Looking in Python's fileobject.c: The function table for file objects points to function file_dealloc. This function calls close_the_file, which in turn closes the file. So it seems reasonable to state that at the moment, on CPython, when there are no more references to a file object, it's closed without any delay. If you think this interpretation is wrong, please post a comment indicating why you feel that way. A: Even though it works as expected, I think it fails in two counts: Your code will not scale up seamlessly, because you are reading the entire file into memory, and this may or may not be necessarily what you want. According to the Zen of Python (try import this in the Python prompt to retrieve it) "explicit is better than implicit" and, by failing to explicitly close the file, you could confuse someone who, down the road, will be left with your code for maintenance. It really helps being explicit! Python encourages explicit style. Other than that, for a throwaway script, your style makes sense. Maybe you will benefit from this answer. A: looks fine to me.. I read files like that often.
File open: Is this bad Python style?
To read contents of a file: data = open(filename, "r").read() The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing. EDIT: This has actually bitten me in a project I wrote - it prompted me to ask this question. File objects are cleaned up only when you run out of memory, not when you run out of file handles. So if you do this too often, you could end up running out of file descriptors and causing your IO attempts at opening files to throw exceptions.
[ "Just for the record:\nThis is only slightly longer, and closes the file immediately:\nfrom __future__ import with_statement\n\nwith open(filename, \"r\") as f:\n data = f.read()\n\n", "It is true that it will close eventually, but eventually might not be soon enough. Especially if you're using this inside a loop, the system might run out of file handles before the GC gets to the file objects.\n", "The code works exactly as you say it does, but it's bad style nevertheless. Your code relies on assumptions which may be true now, but won't always be true. It's not impossible that your code will be run in a situation where the file being opened and not close does matter. Is it really worth that risk just to save 1 or 2 lines of code? I don't think so.\n", "No, it's perfectly reasonable Python style IMO, as per your reasoning.\nUpdate: There are a lot of comments here about whether file objects get tidied up straight away or not. Rather than speculate, I did some digging. Here's what I see:\n\nFrom a comment in Python's object.h:\n\nThe macros Py_INCREF(op) and\n Py_DECREF(op) are used to increment or\n decrement reference counts. Py_DECREF\n calls the object's deallocator\n function when the refcount falls to 0\n\nLooking in Python's fileobject.c:\nThe function table for file objects points to function file_dealloc. This function\ncalls close_the_file, which in turn closes the file.\n\nSo it seems reasonable to state that at the moment, on CPython, when there are no\nmore references to a file object, it's closed without any delay. If you think this interpretation is wrong, please post a comment indicating why you feel that way.\n", "Even though it works as expected, I think it fails in two counts:\n\nYour code will not scale up seamlessly, because you are reading the entire file into memory, and this may or may not be necessarily what you want.\nAccording to the Zen of Python (try import this in the Python prompt to retrieve it) \"explicit is better than implicit\" and, by failing to explicitly close the file, you could confuse someone who, down the road, will be left with your code for maintenance.\n\nIt really helps being explicit! Python encourages explicit style.\nOther than that, for a throwaway script, your style makes sense.\nMaybe you will benefit from this answer.\n", "looks fine to me.. I read files like that often.\n" ]
[ 30, 7, 4, 3, 2, 1 ]
[]
[]
[ "coding_style", "file", "file_io", "python" ]
stackoverflow_0001373660_coding_style_file_file_io_python.txt
Q: Stackless Python and PyQt What experiences do you have with Stackless Python and PyQt? Issues i would be happy if people address: Compilation of PyQt for Stackless: does PyQt need to be compiled especially for Stackless? is the compilation smooth? problems with bindings etc. Stability: any unexpected crashes, freezes, pauses and other weirdities? Memory Management: any hints of memory leaks. comparison of RAM needed for a Stackless/Plain Vanilla PyQt applications Software Engineering Empowerment: very short outline of flow-of-control models for Stackless-powered PyQt applications Lessons learned: any painful lesson learned, traps to be avoided, problems to tackle you might have experienced Be Happy A: If you're interested in all that because of speed optimization: You may want to check out Unladen Swallow ( Wikipedia here ). Google (because of YouTube being 100% Python) is working on a JIT compiler for Python that will increase its speed by 5-10x (bringing it much closer to Java speeds than the current virtual machine). The best part is that it will work with all existing Python code which means you don't have to fret with all the problems associated with other Python optimization projects. I expect that if you're developing a large enough project to warrant the need for optimization at a low level, you'd be OK with developing in normal Python and then changing out of the current VM when Unladen Swallow comes out in production. A: I tried to go down this path several months ago and decided it was not worth the effort. I was able to run a binary install of PyQt (on Windows) against a stackless version of Python, but I found that I had to manually go in and change some of the files. I was getting an error message (sorry, I forget what it was), and google search led to a solution from several years ago. Newer code did not include the old fix, so the change was not too difficult and (if I remember correctly) it was in python, so no recompile was necessary. But that was a deal breaker for me. Qt updates come out regularly, as do updates to PyQt, and I didn't want to be continually fixing the code. Stackless and PyQt are simply not used enough together to be checked out thoroughly. I found the risk of difficult to debug issues pretty high. This is especially true given the author of stackless has moved on to PyPy. Let me apologize in advance - I wish I had the references I found for the author stopping development on stackless python and more detail on the errors I had to fix - I wasn't expecting to regurgitate the details on Stack Overflow. So I chose to run PyQt on a vanilla Python instead of stackless. BTW, I also thought that mixing signals/slots with stackless code would be confusing, as they are completely different methods of solving multi-threading problems. Good luck!
Stackless Python and PyQt
What experiences do you have with Stackless Python and PyQt? Issues i would be happy if people address: Compilation of PyQt for Stackless: does PyQt need to be compiled especially for Stackless? is the compilation smooth? problems with bindings etc. Stability: any unexpected crashes, freezes, pauses and other weirdities? Memory Management: any hints of memory leaks. comparison of RAM needed for a Stackless/Plain Vanilla PyQt applications Software Engineering Empowerment: very short outline of flow-of-control models for Stackless-powered PyQt applications Lessons learned: any painful lesson learned, traps to be avoided, problems to tackle you might have experienced Be Happy
[ "If you're interested in all that because of speed optimization:\nYou may want to check out Unladen Swallow ( Wikipedia here ). Google (because of YouTube being 100% Python) is working on a JIT compiler for Python that will increase its speed by 5-10x (bringing it much closer to Java speeds than the current virtual machine). The best part is that it will work with all existing Python code which means you don't have to fret with all the problems associated with other Python optimization projects.\nI expect that if you're developing a large enough project to warrant the need for optimization at a low level, you'd be OK with developing in normal Python and then changing out of the current VM when Unladen Swallow comes out in production.\n", "I tried to go down this path several months ago and decided it was not worth the effort.\nI was able to run a binary install of PyQt (on Windows) against a stackless version of Python, but I found that I had to manually go in and change some of the files. I was getting an error message (sorry, I forget what it was), and google search led to a solution from several years ago. Newer code did not include the old fix, so the change was not too difficult and (if I remember correctly) it was in python, so no recompile was necessary.\nBut that was a deal breaker for me. Qt updates come out regularly, as do updates to PyQt, and I didn't want to be continually fixing the code. Stackless and PyQt are simply not used enough together to be checked out thoroughly. I found the risk of difficult to debug issues pretty high. This is especially true given the author of stackless has moved on to PyPy. Let me apologize in advance - I wish I had the references I found for the author stopping development on stackless python and more detail on the errors I had to fix - I wasn't expecting to regurgitate the details on Stack Overflow.\nSo I chose to run PyQt on a vanilla Python instead of stackless.\nBTW, I also thought that mixing signals/slots with stackless code would be confusing, as they are completely different methods of solving multi-threading problems.\nGood luck!\n" ]
[ 0, 0 ]
[]
[]
[ "pyqt", "pyqt4", "python", "python_stackless", "stackless" ]
stackoverflow_0001749818_pyqt_pyqt4_python_python_stackless_stackless.txt
Q: What is/are the Python equivalent(s) to the Java Collections Framework? The Java Collections Framework is like the C++ Standard Template Library: "a unified architecture for representing and manipulating collections (objects that group multiple elements into a single unit)." http://java.sun.com/docs/books/tutorial/collections/intro/index.html A: As it turns out, the equivalent to the Java Collections Framework in Python is... Python. All of the core collections featured in the Java Collections Framework are already present in core Python. Give it a try! Sequences provide lists, queues, stacks, etc. Dictionaries are your hash-tables and maps. Sets are present, etc. One might consider Python a "higher" language than Java, because it natively provides all of these higher order abstract data types intrinsically. (It also supports Object Oriented, procedural, and functional programming methodologies.) A: Other than the built-ins you might what to check out collections. >>> import collections >>> dir(collections) ['Callable', 'Container', 'Hashable', 'ItemsView', 'Iterable', 'Iterator', 'KeysView', 'Mapping', 'MappingView', 'MutableMapping', 'MutableSequence', 'MutableSet', 'Sequence', 'Set', 'Sized', 'ValuesView', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_abcoll', '_iskeyword', '_itemgetter', '_sys', 'defaultdict', 'deque', 'namedtuple'] >>>
What is/are the Python equivalent(s) to the Java Collections Framework?
The Java Collections Framework is like the C++ Standard Template Library: "a unified architecture for representing and manipulating collections (objects that group multiple elements into a single unit)." http://java.sun.com/docs/books/tutorial/collections/intro/index.html
[ "As it turns out, the equivalent to the Java Collections Framework in Python is... Python. All of the core collections featured in the Java Collections Framework are already present in core Python.\nGive it a try! Sequences provide lists, queues, stacks, etc. Dictionaries are your hash-tables and maps. Sets are present, etc.\nOne might consider Python a \"higher\" language than Java, because it natively provides all of these higher order abstract data types intrinsically. (It also supports Object Oriented, procedural, and functional programming methodologies.)\n", "Other than the built-ins you might what to check out collections.\n>>> import collections\n>>> dir(collections)\n['Callable', 'Container', 'Hashable', 'ItemsView', 'Iterable', 'Iterator', 'KeysView', 'Mapping', 'MappingView', 'MutableMapping', 'MutableSequence', 'MutableSet', 'Sequence', 'Set', 'Sized', 'ValuesView', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_abcoll', '_iskeyword', '_itemgetter', '_sys', 'defaultdict', 'deque', 'namedtuple']\n>>>\n\n" ]
[ 15, 12 ]
[]
[]
[ "c++", "collections", "java", "python" ]
stackoverflow_0002047220_c++_collections_java_python.txt
Q: Unit testing file write in Python I am writing a wrapper for the ConfigParser in Python to provide an easy interface for storing and retrieving application settings. The wrapper has two methods, read and write, and a set of properties for the different application settings. The write method is just a wrapper for the ConfigParser's write method with the addition of also creating the file object needed by the ConfigParser. It looks like this: def write(self): f = open(self.path, "w") try: self.config_parser.write(f) finally: f.close() I would like to write a unit test that asserts that this method raises an IOError if the file could not be written to and in the other case that the write method of the config parser was called. The second test is quite easy to handle with a mock object. But the open call makes things a little tricky. Eventually I have to create a file object to pass to the config parser. The fact that a file will actually be created when running this code doesn't make it very useful for a unit test. Is there some strategy for mocking file creation? Can this piece of code be tested in some way? Or is it just too simple to be tested? A: First, you don't actually need to unit test open(), since it's pretty reasonable to assume that the standard library is correct. Next, you don't want to do file system manipulations to get open() to generate the error you want, because then you're not unit testing, you're doing a functional/integration test by including the file system. So you could perhaps replace open() in the global namespace with a surrogate that just raises an IOError. Though, probably need to make sure you put things back if execution continues. But in the end, what value does the test have? There's so little in that code snippet that's your own system. Even replacing open() really just ends up being a test that says "does the try and finally statement in Python work?" My suggestion? Just add a statement to the docstring that records your expectation. "Raises an IOError if the file can't be written." Then move on. You can add a unit test later if this method gains some complexity (and merit for testing). A: Actually, only open could throw an exception in your code. The docs for write() doesn't say anything about exceptions. Possibly only a ValueError or something for a bad file pointer (as a result of open failing, which can't be the case here). Making an IOError for open is easy. Just create the file elsewhere and open it for writing there. Or you could change the permissions for it so you don't have access. You'd might wanna use the with statement here though, and it'll handle the closing itself. In python 2.5 you need the first line. In later versions you don't need it. from __future__ import with_statement # python 2.5 only def write(self): with open(self.path, 'w') as f: self.config_parser.write(f) The write method is guaranteed to be called if open succeeds, and won't be called if open raises an IOError. I don't know why you'd need a test to see if write was called. The code says that it does. Don't overdo your testing. ;) A: Remember you don't have to test that open() or ConfigParser work—they're not part of your code—you just have to test that you use them correctly. You can monkeypatch the module with your own open(), just as for the instance attribute, and can return a mock from it that helps you test. However, unit tests are not my only tool, and this is one function that's simple enough to analyze and "prove"† that it works. †Less rigorously than mathematicians would like, I'm sure, but good enough for me.
Unit testing file write in Python
I am writing a wrapper for the ConfigParser in Python to provide an easy interface for storing and retrieving application settings. The wrapper has two methods, read and write, and a set of properties for the different application settings. The write method is just a wrapper for the ConfigParser's write method with the addition of also creating the file object needed by the ConfigParser. It looks like this: def write(self): f = open(self.path, "w") try: self.config_parser.write(f) finally: f.close() I would like to write a unit test that asserts that this method raises an IOError if the file could not be written to and in the other case that the write method of the config parser was called. The second test is quite easy to handle with a mock object. But the open call makes things a little tricky. Eventually I have to create a file object to pass to the config parser. The fact that a file will actually be created when running this code doesn't make it very useful for a unit test. Is there some strategy for mocking file creation? Can this piece of code be tested in some way? Or is it just too simple to be tested?
[ "First, you don't actually need to unit test open(), since it's pretty reasonable to assume that the standard library is correct.\nNext, you don't want to do file system manipulations to get open() to generate the error you want, because then you're not unit testing, you're doing a functional/integration test by including the file system.\nSo you could perhaps replace open() in the global namespace with a surrogate that just raises an IOError. Though, probably need to make sure you put things back if execution continues.\nBut in the end, what value does the test have? There's so little in that code snippet that's your own system. Even replacing open() really just ends up being a test that says \"does the try and finally statement in Python work?\"\nMy suggestion? Just add a statement to the docstring that records your expectation. \"Raises an IOError if the file can't be written.\" Then move on. You can add a unit test later if this method gains some complexity (and merit for testing).\n", "Actually, only open could throw an exception in your code. The docs for write() doesn't say anything about exceptions. Possibly only a ValueError or something for a bad file pointer (as a result of open failing, which can't be the case here).\nMaking an IOError for open is easy. Just create the file elsewhere and open it for writing there. Or you could change the permissions for it so you don't have access.\nYou'd might wanna use the with statement here though, and it'll handle the closing itself.\nIn python 2.5 you need the first line. In later versions you don't need it.\nfrom __future__ import with_statement # python 2.5 only\n\ndef write(self):\n with open(self.path, 'w') as f:\n self.config_parser.write(f)\n\nThe write method is guaranteed to be called if open succeeds, and won't be called if open raises an IOError. I don't know why you'd need a test to see if write was called. The code says that it does. Don't overdo your testing. ;)\n", "Remember you don't have to test that open() or ConfigParser work—they're not part of your code—you just have to test that you use them correctly. You can monkeypatch the module with your own open(), just as for the instance attribute, and can return a mock from it that helps you test.\nHowever, unit tests are not my only tool, and this is one function that's simple enough to analyze and \"prove\"† that it works.\n†Less rigorously than mathematicians would like, I'm sure, but good enough for me.\n" ]
[ 7, 5, 2 ]
[]
[]
[ "file_io", "python", "unit_testing" ]
stackoverflow_0002047459_file_io_python_unit_testing.txt
Q: Sets module deprecated warning When I run my python script I get the following warning DeprecationWarning: the sets module is deprecated How do I fix this? A: Stop using the sets module, or switch to an older version of python where it's not deprecated. According to pep-004, sets is deprecated as of v2.6, replaced by the built-in set and frozenset types. A: History: Before Python 2.3: no set functionality Python 2.3: sets module arrived Python 2.4: set and frozenset built-ins introduced Python 2.6: sets module deprecated You should change your code to use set instead of sets.Set. If you still wish to be able to support using Python 2.3, you can do this at the start of your script: try: set except NameError: from sets import Set as set A: If you want to fix it James definitely has the right answer, but in case you want to just turn off deprecation warnings, you can run python like so: $ python -Wignore::DeprecationWarning Python 2.6.2 (r262:71600, Sep 20 2009, 20:47:22) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sets >>> (From: http://puzzling.org/logs/thoughts/2009/May/3/python26-deprecation-warning) You can also ignore it programmatically: import warnings warnings.simplefilter("ignore", DeprecationWarning) A: Use the built-in set instead of importing and using sets module. From documentation: The sets module has been deprecated; it’s better to use the built-in set and frozenset types. A: You don't need to import the sets module to use them, they're in the builtin namespace.
Sets module deprecated warning
When I run my python script I get the following warning DeprecationWarning: the sets module is deprecated How do I fix this?
[ "Stop using the sets module, or switch to an older version of python where it's not deprecated.\nAccording to pep-004, sets is deprecated as of v2.6, replaced by the built-in set and frozenset types.\n", "History:\nBefore Python 2.3: no set functionality\nPython 2.3: sets module arrived\nPython 2.4: set and frozenset built-ins introduced\nPython 2.6: sets module deprecated \nYou should change your code to use set instead of sets.Set.\nIf you still wish to be able to support using Python 2.3, you can do this at the start of your script:\ntry:\n set\nexcept NameError:\n from sets import Set as set\n\n", "If you want to fix it James definitely has the right answer, but in case you want to just turn off deprecation warnings, you can run python like so:\n$ python -Wignore::DeprecationWarning \nPython 2.6.2 (r262:71600, Sep 20 2009, 20:47:22) \n[GCC 4.2.1 (Apple Inc. build 5646)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sets\n>>> \n\n(From: http://puzzling.org/logs/thoughts/2009/May/3/python26-deprecation-warning)\nYou can also ignore it programmatically:\nimport warnings\nwarnings.simplefilter(\"ignore\", DeprecationWarning)\n\n", "Use the built-in set instead of importing and using sets module. \nFrom documentation:\n\nThe sets module has been deprecated;\n it’s better to use the built-in set\n and frozenset types.\n\n", "You don't need to import the sets module to use them, they're in the builtin namespace.\n" ]
[ 35, 27, 5, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002040616_python.txt
Q: Dithering in text using PIL and truetype fonts Consider the following code: from PIL import Image, ImageDraw, ImageFont def addText(img, lTxt): FONT_SIZE = 10 INTERLINE_DISTANCE = FONT_SIZE + 1 font = ImageFont.truetype('arial.ttf', FONT_SIZE) lTxtImageHeight = INTERLINE_DISTANCE * len(lTxt) # create text image lTxtImg = Image.new('RGBA', (img.size[1], lTxtImageHeight), 255) lTxtImgDraw = ImageDraw.Draw(lTxtImg, ) for (i, line) in enumerate(lTxt): lTxtImgDraw.text((5, i * INTERLINE_DISTANCE), line, font=font, fill='#000000') # rotate text image lTxtImg = lTxtImg.rotate(90) # create new transparent image ret ret = Image.new('RGBA', (img.size[0] + lTxtImageHeight, img.size[1]), 255) # paste the image to ret ret.paste(img, (0,0)) # paste the text to ret ret.paste(lTxtImg, (img.size[0], 0), lTxtImg) return ret img = Image.open('in.png') addText(img, ['lorem', 'ipsum', 'dolores']).save('out.png') Here are the input and the output files This is the input input http://img16.imageshack.us/img16/8229/73936270.png and this is the output output http://img94.imageshack.us/img94/531/outj.png As you may see, the output image contains a lot of reddish noise around the text. How can I eliminate this dithering? A: I suggest writing the intermediate text images to file (the text, then the rotated text), to isolate where the artefacts first appear. One other possibility could be that the png encoding is using a pallete with no grayscale values, so those reds are the closest available. I checked the encoding of the files on imageshack though, and it seemed okay, so I don't think this is the problem.
Dithering in text using PIL and truetype fonts
Consider the following code: from PIL import Image, ImageDraw, ImageFont def addText(img, lTxt): FONT_SIZE = 10 INTERLINE_DISTANCE = FONT_SIZE + 1 font = ImageFont.truetype('arial.ttf', FONT_SIZE) lTxtImageHeight = INTERLINE_DISTANCE * len(lTxt) # create text image lTxtImg = Image.new('RGBA', (img.size[1], lTxtImageHeight), 255) lTxtImgDraw = ImageDraw.Draw(lTxtImg, ) for (i, line) in enumerate(lTxt): lTxtImgDraw.text((5, i * INTERLINE_DISTANCE), line, font=font, fill='#000000') # rotate text image lTxtImg = lTxtImg.rotate(90) # create new transparent image ret ret = Image.new('RGBA', (img.size[0] + lTxtImageHeight, img.size[1]), 255) # paste the image to ret ret.paste(img, (0,0)) # paste the text to ret ret.paste(lTxtImg, (img.size[0], 0), lTxtImg) return ret img = Image.open('in.png') addText(img, ['lorem', 'ipsum', 'dolores']).save('out.png') Here are the input and the output files This is the input input http://img16.imageshack.us/img16/8229/73936270.png and this is the output output http://img94.imageshack.us/img94/531/outj.png As you may see, the output image contains a lot of reddish noise around the text. How can I eliminate this dithering?
[ "I suggest writing the intermediate text images to file (the text, then the rotated text), to isolate where the artefacts first appear.\nOne other possibility could be that the png encoding is using a pallete with no grayscale values, so those reds are the closest available. I checked the encoding of the files on imageshack though, and it seemed okay, so I don't think this is the problem.\n" ]
[ 0 ]
[]
[]
[ "dithering", "python", "python_imaging_library", "text" ]
stackoverflow_0002047534_dithering_python_python_imaging_library_text.txt
Q: How to use Python to get local admins from a computer on the Network? I need to get a list of all people in the company who have local admin rights on their computers. We have a group on each machine called "Administrators." I can get a list of all computers from active directory with: import active_directory for computer in active_directory.search ("objectCategory='Computer'"): print computer.displayName Now I think I need to take each computer name and feed it back in. I was thinking maybe reading the remote registry on each computer and looking for the SID -- supposedly the SID 'S-1-5-domain-500' will give me a list of people on the computer that are local admins. I did: import _winreg COMPUTER_NAME = "FakeComputerName" KEY_PATH = r"System\CurrentControlSet\Control\ComputerName\ComputerName" HKLM_remote = _winreg.ConnectRegistry (r"\\%s" % COMPUTER_NAME, _winreg.HKEY_LOCAL_MACHINE) hKeyRemote = _winreg.OpenKey (HKLM_remote, KEY_PATH, 0, _winreg.KEY_READ) value, type = _winreg.QueryValueEx (hKeyRemote, "ComputerName") print "Remote computer name is", value Remote computer name is FakeComputerName How do I combine these to get what I need? Will these work together? Is this the best way to go about this? Once I get this to work I can figure out writing it to a file and adding exceptions like if the computer isn't on the network it writes that and then moves onto the next PC. Perhaps use win32security? I don't know what registry key to use or even if it will work. I've spent about 5 hours on this today and I am still learning Python. I don't know VB and that is the majority of code I see on the net. Thanks! A: Is this the data from this operation going to be manipulated afterwards? If this is a manual scan that is going to be looked at by a human, then you're way overthinking it. Just use a network scanner to handle it for you, such as this one. A: I'm not sure of the details but it sounds like you may want to take a look at the WMI package. Back when I was playing with COM and the windows registry and ran across it. It looks like it's been improved a bit since when I looked at it. Here's windows reference documentation. WMI Reference
How to use Python to get local admins from a computer on the Network?
I need to get a list of all people in the company who have local admin rights on their computers. We have a group on each machine called "Administrators." I can get a list of all computers from active directory with: import active_directory for computer in active_directory.search ("objectCategory='Computer'"): print computer.displayName Now I think I need to take each computer name and feed it back in. I was thinking maybe reading the remote registry on each computer and looking for the SID -- supposedly the SID 'S-1-5-domain-500' will give me a list of people on the computer that are local admins. I did: import _winreg COMPUTER_NAME = "FakeComputerName" KEY_PATH = r"System\CurrentControlSet\Control\ComputerName\ComputerName" HKLM_remote = _winreg.ConnectRegistry (r"\\%s" % COMPUTER_NAME, _winreg.HKEY_LOCAL_MACHINE) hKeyRemote = _winreg.OpenKey (HKLM_remote, KEY_PATH, 0, _winreg.KEY_READ) value, type = _winreg.QueryValueEx (hKeyRemote, "ComputerName") print "Remote computer name is", value Remote computer name is FakeComputerName How do I combine these to get what I need? Will these work together? Is this the best way to go about this? Once I get this to work I can figure out writing it to a file and adding exceptions like if the computer isn't on the network it writes that and then moves onto the next PC. Perhaps use win32security? I don't know what registry key to use or even if it will work. I've spent about 5 hours on this today and I am still learning Python. I don't know VB and that is the majority of code I see on the net. Thanks!
[ "Is this the data from this operation going to be manipulated afterwards? If this is a manual scan that is going to be looked at by a human, then you're way overthinking it.\nJust use a network scanner to handle it for you, such as this one.\n", "I'm not sure of the details but it sounds like you may want to take a look at the WMI package.\nBack when I was playing with COM and the windows registry and ran across it. It looks like it's been improved a bit since when I looked at it.\nHere's windows reference documentation. WMI Reference\n" ]
[ 0, 0 ]
[]
[]
[ "active_directory", "python", "winreg" ]
stackoverflow_0002047355_active_directory_python_winreg.txt
Q: There's an example on how to use an API with Python and cURL. Is it feasable to just copy the code if I have IronPython installed and have it work? Here's the code in question: #!/usr/bin/python import pycurl c = pycurl.Curl() values = [ ("key", "YOUR_API_KEY"), ("image", (c.FORM_FILE, "file.png"))] # OR: ("image", "http://example.com/example.jpg"))] c.setopt(c.URL, "http://imgur.com/api/upload.xml") c.setopt(c.HTTPPOST, values) c.perform() c.close() I've tried to ask for help on how to copy this functionality in C#, but so far none of the answers really help because I need to use my API key or else it doesn't work. A: In C#, you can use the WebRequest class to accomplish the same. Take a look at the example toward the bottom of the page "How to: Send Data Using the WebRequest Class" for a code sample. A: The code itself looks straightforward. I don't know if pycurl is available as a .NET module (or whatever it's called) so that it can be used directly from ironpython. What's the problem with trying it once? A: As far as I know, you should be able to do that just fine. One of two things will happen: It will work just fine when you import your code into IronPython IronPython will throw an error at you saying that it doesn't know where to find cURL. In this case, you will have to add it to your PATH. I believe it is in the sys module (sys.path.append("C:\..path_to_cURL")). Do this at the top of your code and it should be smooth sailing from there Hope that helps A: pycurl appears to be a C-Extension for CPython. To use this with IronPython you will need to use IronClad (a 'work in progress' project to allow use of c-extensions in the .Net world).
There's an example on how to use an API with Python and cURL. Is it feasable to just copy the code if I have IronPython installed and have it work?
Here's the code in question: #!/usr/bin/python import pycurl c = pycurl.Curl() values = [ ("key", "YOUR_API_KEY"), ("image", (c.FORM_FILE, "file.png"))] # OR: ("image", "http://example.com/example.jpg"))] c.setopt(c.URL, "http://imgur.com/api/upload.xml") c.setopt(c.HTTPPOST, values) c.perform() c.close() I've tried to ask for help on how to copy this functionality in C#, but so far none of the answers really help because I need to use my API key or else it doesn't work.
[ "In C#, you can use the WebRequest class to accomplish the same. Take a look at the example toward the bottom of the page \"How to: Send Data Using the WebRequest Class\" for a code sample. \n", "The code itself looks straightforward. I don't know if pycurl is available as a .NET module (or whatever it's called) so that it can be used directly from ironpython. What's the problem with trying it once?\n", "As far as I know, you should be able to do that just fine.\nOne of two things will happen:\n\nIt will work just fine when you import your code into IronPython\nIronPython will throw an error at you saying that it doesn't know where to find cURL. In this case, you will have to add it to your PATH. I believe it is in the sys module (sys.path.append(\"C:\\..path_to_cURL\")). Do this at the top of your code and it should be smooth sailing from there\n\nHope that helps\n", "pycurl appears to be a C-Extension for CPython. \nTo use this with IronPython you will need to use IronClad (a 'work in progress' project to allow use of c-extensions in the .Net world).\n" ]
[ 1, 0, 0, 0 ]
[]
[]
[ "c#", "curl", "ironpython", "python" ]
stackoverflow_0002043848_c#_curl_ironpython_python.txt
Q: Lines do not render on an offscreen frame buffer with a completely black texture If I have a frame buffer which has a textured binded to it which is simply black with full alpha and I try to draw a line to it, even if the line has full alpha it wont render. I'm not stupid, so the lines definitely aren't black. If the texture is white instead the line suddenly render correctly as if the colour of the texture behind it effects the colour of the lines which is dumb. Only if the lines have transparency, should the colour behind them have effect. I'm using line smoothing. I use the following blend function which is apparently the one to use, glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) How do I fix this? Lots of code: For drawing lines: def draw_line(a,b,c,w,antialias): if antialias: glEnable(GL_LINE_SMOOTH) #Enable line smoothing. c = [float(sc)/255.0 for sc in c] #Divide colours by 255 because OpenGL uses 0-1 if len(c) != 4: c.append(1) #Add a value for aplha transparency if needed glMatrixMode(GL_MODELVIEW) glLoadIdentity() #Loads model matrix glColor4fv(c) glLineWidth(w) glBegin(GL_LINES) glVertex2fv(a) glVertex2fv(b) glEnd() if antialias: glDisable(GL_LINE_SMOOTH) #Disable line smoothing. Setting up framebuffer object: def setup_framebuffer(surface): #Create texture if not done already if surface.texture == None: create_texture(surface) #Render child to parent if surface.frame_buffer == None: surface.frame_buffer = glGenFramebuffersEXT(1) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0) glPushAttrib(GL_VIEWPORT_BIT) glViewport(0,0,surface.surface_size[0],surface.surface_size[1]) glMatrixMode(GL_PROJECTION) glLoadIdentity() #Load the projection matrix gluOrtho2D(0,surface.surface_size[0],0,surface.surface_size[1]) def end_framebuffer(): glPopAttrib() glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0) glMatrixMode(GL_PROJECTION) glLoadIdentity() #Load the projection matrix gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view Creation of texture: def create_texture(surface): surface.texture = glGenTextures(1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() #Loads model matrix glBindTexture(GL_TEXTURE_2D, surface.texture) #Binds the current 2D texture to the texture to be drawn glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) #Required to be set for maping the pixel data glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) #Similar as above if surface.data == None: surf = pygame.Surface((1,1),SRCALPHA) surf.fill(surface.colour[:-1]) surface.data = pygame.image.tostring(surf, "RGBA") * (surface.surface_size[0] * surface.surface_size[1]) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface.surface_size[0], surface.surface_size[1], 0, GL_RGBA,GL_UNSIGNED_BYTE, surface.data) #Put surface pixel data into texture Function to draw lots of lines to the screen or to the texture of a Surface object with a frame buffer object: def add_lines(surface, c, coordinates, w = 1, antialias = True): if surface.__class__ == Surface: #Only use a frame buffer if the line isn't being drawn to the screen. setup_framebuffer(surface) last = None for coordinate in coordinates: #Loop though the coordinates and draw the lines if last != None: draw_line(last,coordinate,c,w,antialias) last = coordinate if surface.__class__ == Surface: #Only use a frame buffer if the line isn't being drawn to the screen. end_framebuffer() That's all I can see as important. Except maybe the initialisation code: glutInit(sys.argv) glutInitWindowPosition(0,0) glutInitWindowSize(*game_size) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA) glutCreateWindow(title) glutSetIconTitle(title) glutReshapeFunc(self.reshaped) glutKeyboardFunc(self.keydown) glutKeyboardUpFunc(self.keyup) glutSpecialFunc(self.specialdown) glutSpecialUpFunc(self.specialup) glViewport(0,0,self.first_screen[0],self.first_screen[1]) #Creates the viewport which is mapped to the window glEnable(GL_BLEND) #Enable alpha blending glEnable(GL_TEXTURE_2D) #Enable 2D Textures glEnable(GL_POLYGON_SMOOTH) #Enable antialiased polygons glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST) glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glMatrixMode(GL_PROJECTION) glLoadIdentity() #Load the projection matrix gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view A: There is at least one thing that looks suspicious: you're turning on Texturing in your init code, and forgetting about it. So your lines are drawn with texturing on (and constant texture coordinates), presumably picking the texture that you're trying to write to. This is likely not what you want (I don't remember what the fbo spec has to say on this, but it's not going to work). How about you turn off texturing when rendering the lines ?
Lines do not render on an offscreen frame buffer with a completely black texture
If I have a frame buffer which has a textured binded to it which is simply black with full alpha and I try to draw a line to it, even if the line has full alpha it wont render. I'm not stupid, so the lines definitely aren't black. If the texture is white instead the line suddenly render correctly as if the colour of the texture behind it effects the colour of the lines which is dumb. Only if the lines have transparency, should the colour behind them have effect. I'm using line smoothing. I use the following blend function which is apparently the one to use, glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) How do I fix this? Lots of code: For drawing lines: def draw_line(a,b,c,w,antialias): if antialias: glEnable(GL_LINE_SMOOTH) #Enable line smoothing. c = [float(sc)/255.0 for sc in c] #Divide colours by 255 because OpenGL uses 0-1 if len(c) != 4: c.append(1) #Add a value for aplha transparency if needed glMatrixMode(GL_MODELVIEW) glLoadIdentity() #Loads model matrix glColor4fv(c) glLineWidth(w) glBegin(GL_LINES) glVertex2fv(a) glVertex2fv(b) glEnd() if antialias: glDisable(GL_LINE_SMOOTH) #Disable line smoothing. Setting up framebuffer object: def setup_framebuffer(surface): #Create texture if not done already if surface.texture == None: create_texture(surface) #Render child to parent if surface.frame_buffer == None: surface.frame_buffer = glGenFramebuffersEXT(1) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, surface.frame_buffer) glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, surface.texture, 0) glPushAttrib(GL_VIEWPORT_BIT) glViewport(0,0,surface.surface_size[0],surface.surface_size[1]) glMatrixMode(GL_PROJECTION) glLoadIdentity() #Load the projection matrix gluOrtho2D(0,surface.surface_size[0],0,surface.surface_size[1]) def end_framebuffer(): glPopAttrib() glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0) glMatrixMode(GL_PROJECTION) glLoadIdentity() #Load the projection matrix gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view Creation of texture: def create_texture(surface): surface.texture = glGenTextures(1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() #Loads model matrix glBindTexture(GL_TEXTURE_2D, surface.texture) #Binds the current 2D texture to the texture to be drawn glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) #Required to be set for maping the pixel data glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) #Similar as above if surface.data == None: surf = pygame.Surface((1,1),SRCALPHA) surf.fill(surface.colour[:-1]) surface.data = pygame.image.tostring(surf, "RGBA") * (surface.surface_size[0] * surface.surface_size[1]) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface.surface_size[0], surface.surface_size[1], 0, GL_RGBA,GL_UNSIGNED_BYTE, surface.data) #Put surface pixel data into texture Function to draw lots of lines to the screen or to the texture of a Surface object with a frame buffer object: def add_lines(surface, c, coordinates, w = 1, antialias = True): if surface.__class__ == Surface: #Only use a frame buffer if the line isn't being drawn to the screen. setup_framebuffer(surface) last = None for coordinate in coordinates: #Loop though the coordinates and draw the lines if last != None: draw_line(last,coordinate,c,w,antialias) last = coordinate if surface.__class__ == Surface: #Only use a frame buffer if the line isn't being drawn to the screen. end_framebuffer() That's all I can see as important. Except maybe the initialisation code: glutInit(sys.argv) glutInitWindowPosition(0,0) glutInitWindowSize(*game_size) glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA) glutCreateWindow(title) glutSetIconTitle(title) glutReshapeFunc(self.reshaped) glutKeyboardFunc(self.keydown) glutKeyboardUpFunc(self.keyup) glutSpecialFunc(self.specialdown) glutSpecialUpFunc(self.specialup) glViewport(0,0,self.first_screen[0],self.first_screen[1]) #Creates the viewport which is mapped to the window glEnable(GL_BLEND) #Enable alpha blending glEnable(GL_TEXTURE_2D) #Enable 2D Textures glEnable(GL_POLYGON_SMOOTH) #Enable antialiased polygons glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST) glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glMatrixMode(GL_PROJECTION) glLoadIdentity() #Load the projection matrix gluOrtho2D(0,1280,720,0) #Set an orthorgraphic view
[ "There is at least one thing that looks suspicious: you're turning on Texturing in your init code, and forgetting about it.\nSo your lines are drawn with texturing on (and constant texture coordinates), presumably picking the texture that you're trying to write to.\nThis is likely not what you want (I don't remember what the fbo spec has to say on this, but it's not going to work). How about you turn off texturing when rendering the lines ?\n" ]
[ 1 ]
[]
[]
[ "alphablending", "framebuffer", "opengl", "pyopengl", "python" ]
stackoverflow_0002034775_alphablending_framebuffer_opengl_pyopengl_python.txt
Q: Easy way of getting started programming using python Background I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run." A Python Environment (is this the right word at all?) Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface. My Failure So Far For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "IDE, "the Package Manager" and the waste module on which they depend." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope. Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package? I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager. Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal. What questions should I be asking? http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff **Sidestory* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour. A: Lots of great "Python tutorials for non-programmers" are listed here! A: I recommend biting the bullet and using the command line version to start with. Later you'll get onto writing scripts and you'll need a good editor, but not necessarily a python IDE. For learning I found the "Python Tutorial" by Guido van Rossum, the author of python, to be a good starting point. ( http://docs.python.org/tutorial/ ) And since you're on OSX you probably have python already installed so no install needed. To check just type "python --version" into the command prompt in a terminal. A: Start with the very basics: Python 2.6.4 Installer The Official Python Tutorial That's how I did it. A: I was in the same boat, two books really helped me: Python 3 for Absolute Beginners Learning Python 4th Edition Python Pocket Reference (for when you've started coding basic stuff and need a handy reference book) A: If you are a true beginner; ALWAYS keep the interactive shell handy (even if you write your code and tutorials in an editor) and use help(whatever_you_need_help_with)and dir(whatever) extensively. For example; >>> a = "foobar" >>> dir(a) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs','find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle','isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust','rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title','translate', 'upper', 'zfill'] >>> help(a.title) Help on built-in function title: title(...) S.title() -> string Return a titlecased version of S, i.e. words start with uppercase characters, all remaining cased characters have lowercase. >>> a.title() 'Foobar' A: Since you're on OSX, you don't actually need to install anything to get started. Simply open up the Terminal application, and type python. You'll go straight into the Python shell (command line) where you can type simple Python programs. When you want to write longer ones, simply do as you did with PHP - write them in a text file, save them, then in the shell just type python myprogram.py. (Note that you'll have to quit the existing Python shell first, by pressing Ctrl-D). As regards books, Dive Into Python is a fantastic guide but it's firmly aimed at people who already know how to program. There are plenty of beginners' guides at the link Alex gives. A: I wrote Building Skills in Programming for folks who are struggling, it may help. http://homepage.mac.com/s_lott/books/nonprogrammer.html A: The easiest way to start will be an online interpreter like Try Python or codepad. Type print "Hello world" after the >>> in the input field and press enter. Your first Python program should be done. There are lots of excellent python tutorials out there, you could start here. A: Buy Head First Programming Seems like a really neat book ^^
Easy way of getting started programming using python
Background I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run." A Python Environment (is this the right word at all?) Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface. My Failure So Far For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "IDE, "the Package Manager" and the waste module on which they depend." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope. Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package? I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager. Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal. What questions should I be asking? http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff **Sidestory* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour.
[ "Lots of great \"Python tutorials for non-programmers\" are listed here!\n", "I recommend biting the bullet and using the command line version to start with.\nLater you'll get onto writing scripts and you'll need a good editor, but not necessarily a python IDE.\nFor learning I found the \"Python Tutorial\" by Guido van Rossum, the author of python, to be a good starting point. ( http://docs.python.org/tutorial/ )\nAnd since you're on OSX you probably have python already installed so no install needed.\nTo check just type \"python --version\" into the command prompt in a terminal.\n", "Start with the very basics:\nPython 2.6.4 Installer\nThe Official Python Tutorial\nThat's how I did it.\n", "I was in the same boat, two books really helped me:\n\nPython 3 for Absolute Beginners\nLearning Python 4th Edition\nPython Pocket Reference (for when you've started coding basic stuff and need a handy reference book)\n\n", "If you are a true beginner; ALWAYS keep the interactive shell handy (even if you write your code and tutorials in an editor) and use help(whatever_you_need_help_with)and dir(whatever) extensively.\nFor example;\n>>> a = \"foobar\"\n>>> dir(a)\n['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__',\n '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__',\n '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', \n'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', \n'__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', \n'expandtabs','find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',\n'istitle','isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',\n'rjust','rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', \n'title','translate', 'upper', 'zfill']\n>>> help(a.title)\nHelp on built-in function title:\n\ntitle(...)\n S.title() -> string \n\n Return a titlecased version of S, i.e. words start with uppercase\n characters, all remaining cased characters have lowercase.\n\n>>> a.title()\n'Foobar'\n\n", "Since you're on OSX, you don't actually need to install anything to get started. Simply open up the Terminal application, and type python. You'll go straight into the Python shell (command line) where you can type simple Python programs.\nWhen you want to write longer ones, simply do as you did with PHP - write them in a text file, save them, then in the shell just type python myprogram.py. (Note that you'll have to quit the existing Python shell first, by pressing Ctrl-D).\nAs regards books, Dive Into Python is a fantastic guide but it's firmly aimed at people who already know how to program. There are plenty of beginners' guides at the link Alex gives.\n", "I wrote Building Skills in Programming for folks who are struggling, it may help.\nhttp://homepage.mac.com/s_lott/books/nonprogrammer.html\n", "The easiest way to start will be an online interpreter like Try Python or codepad.\nType print \"Hello world\" after the >>> in the input field and press enter. Your first Python program should be done.\nThere are lots of excellent python tutorials out there, you could start here.\n", "Buy \nHead First Programming\nSeems like a really neat book ^^\n" ]
[ 3, 2, 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002047165_python.txt
Q: Why does this Python code print nothing? class a(str): def b(self,*x,**y): print str.decode(self,*x,**y) b=a() b.b('utf-8','aaa') # This prints nothing, why? A: Try initialize your string first, with some value: # classes should have capitalized names ... class a(str): def b(self,*x,**y): print 'debugging: ', self, x, y print str.decode(self, *x,**y) if __name__ == '__main__': b=a('aaa') b.b('utf-8') b=a() b.b('utf-8') # => output # debugging: aaa ('utf-8',) {} # aaa # debugging: ('utf-8',) {} # A: because you initialize b (as an object of a) with nothing as str. A: Try printing (self,x,y). You will see ('', ('utf-8', 'aaa'), {}) Therefore, in str.decode(self,*x,**y), self is acting as the empty string. A: When you initiate b1 = a(), it's almost the same as b2 = str() except that b2 doesn't have the bound method b() of class a. Hence, when you invoke b1.b(...), it's the same as calling print str.decode(b1,...) or print str.decode(b2, ...) b1 and b2 are the same in the way that they are both empty strings. Now take a look at what docs say about str.decode. decode(...) S.decode([encoding[,errors]]) -> object Decodes S using the codec registered for encoding. encoding defaults to the default encoding. **errors** may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registerd with codecs.register_error that is able to handle UnicodeDecodeErrors. That means the third parameter (actually the second in the context of bound method) is a sort of error type which would be ignored if it doesn't match any builtin (registered) type. So when you call b1.b('utf-8', 'abc') which will be corresponding to b1.b([encoding], [error type]). Python will translate it to print str.decode(b1, [encoding], [error type]). Since b1 is empty and your "error type" which is 'abc' doesn't match any registered error type, python just prints out an empty string and ignores the given "error type." If you try b = a('hello') and b.b('utf-8', 'abc'), you will see that the output is hello and there is nothing to do with 'abc'. Moreover, if you try to provide one more parameter such as b.b('utf-8', 'abc', 'xyz'), python will raise an error since str.decode() only accepts up to two arguments in the context of bound method.
Why does this Python code print nothing?
class a(str): def b(self,*x,**y): print str.decode(self,*x,**y) b=a() b.b('utf-8','aaa') # This prints nothing, why?
[ "Try initialize your string first, with some value:\n# classes should have capitalized names ...\nclass a(str):\n def b(self,*x,**y):\n print 'debugging: ', self, x, y\n print str.decode(self, *x,**y)\n\nif __name__ == '__main__':\n b=a('aaa')\n b.b('utf-8')\n\n b=a()\n b.b('utf-8')\n\n# => output\n\n# debugging: aaa ('utf-8',) {}\n# aaa\n# debugging: ('utf-8',) {}\n#\n\n", "because you initialize b (as an object of a) with nothing as str.\n", "Try printing (self,x,y). You will see\n('', ('utf-8', 'aaa'), {})\n\nTherefore, in str.decode(self,*x,**y), self is acting as the empty string.\n", "When you initiate b1 = a(), it's almost the same as b2 = str() except that b2 doesn't have the bound method b() of class a. Hence, when you invoke b1.b(...), it's the same as calling print str.decode(b1,...) or print str.decode(b2, ...)\nb1 and b2 are the same in the way that they are both empty strings. Now take a look at what docs say about str.decode.\n\ndecode(...)\n S.decode([encoding[,errors]]) -> object\nDecodes S using the codec registered for encoding. encoding defaults\nto the default encoding. **errors** may be given to set a different error\nhandling scheme. Default is 'strict' meaning that encoding errors raise\na UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\nas well as any other name registerd with codecs.register_error that is\nable to handle UnicodeDecodeErrors.\n\n\nThat means the third parameter (actually the second in the context of bound method) is a sort of error type which would be ignored if it doesn't match any builtin (registered) type.\nSo when you call b1.b('utf-8', 'abc') which will be corresponding to b1.b([encoding], [error type]). Python will translate it to print str.decode(b1, [encoding], [error type]). Since b1 is empty and your \"error type\" which is 'abc' doesn't match any registered error type, python just prints out an empty string and ignores the given \"error type.\"\nIf you try b = a('hello') and b.b('utf-8', 'abc'), you will see that the output is hello and there is nothing to do with 'abc'. Moreover, if you try to provide one more parameter such as b.b('utf-8', 'abc', 'xyz'), python will raise an error since str.decode() only accepts up to two arguments in the context of bound method.\n" ]
[ 8, 4, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002048442_python.txt
Q: Regex match even number of letters I need to match an expression in Python with regular expressions that only matches even number of letter occurrences. For example: AAA # no match AA # match fsfaAAasdf # match sAfA # match sdAAewAsA # match AeAiA # no match An even number of As SHOULD match. A: Try this regular expression: ^[^A]*((AA)+[^A]*)*$ And if the As don’t need to be consecutive: ^[^A]*(A[^A]*A[^A]*)*$ A: This searches for a block with an odd number of A's. If you found one, the string is bad for you: (?<!A)A(AA)*(?!A) If I understand correctly, the Python code should look like: if re.search("(?<!A)A(AA)*(?!A)", "AeAAi"): print "fail" A: Why work so hard coming up with a hard to read pattern? Just search for all occurrences of the pattern and count how many you find. len(re.findall("A", "AbcAbcAbcA")) % 2 == 0 That should be instantly understandable by all experienced programmers, whereas a pattern like "(? Simple is better. A: 'A*' means match any number of A's. Even 0. Here's how to match a string with an even number of a's, upper or lower: re.compile(r''' ^ [^a]* ( ( a[^a]* ){2} # if there must be at least 2 (not just 0), change the # '*' on the following line to '+' )* $ ''',re.IGNORECASE|re.VERBOSE) You probably are using a as an example. If you want to match a specific character other than a, replace a with %s and then insert [...] $ '''%( other_char, other_char, other_char ) [...] A: '*' means 0 or more occurences 'AA' should do the trick. The question is if you want the thing to match 'AAA'. In that case you would have to do something like: r = re.compile('(^|[^A])(AA)+(?!A)',) r.search(p) That would work for match even (and only even) number of'A'. Now if you want to match 'if there is any even number of subsequent letters', this would do the trick: re.compile(r'(.)\1') However, this wouldn't exclude the 'odd' occurences. But it is not clear from your question if you really want that. Update: This works for you test cases: re.compile('^([^A]*)AA([^A]|AA)*$') A: First of all, note that /A*/ matches the empty string. Secondly, there are some things that you just can't do with regular expressions. This'll be a lot easier if you just walk through the string and count up all occurences of the letter you're looking for. A: A* means match "A" zero or more times. For an even number of "A", try: (AA)+ A: It's impossible to count arbitrarily using regular expressions. For example, making sure that you have matching parenthesis. To count you need 'memory' which requires something at least as strong as a pushdown automaton, although in this case you can use the regular expression that @Gumbo provided. The suggestion to use finditeris the best workaround for the general case.
Regex match even number of letters
I need to match an expression in Python with regular expressions that only matches even number of letter occurrences. For example: AAA # no match AA # match fsfaAAasdf # match sAfA # match sdAAewAsA # match AeAiA # no match An even number of As SHOULD match.
[ "Try this regular expression:\n^[^A]*((AA)+[^A]*)*$\n\nAnd if the As don’t need to be consecutive:\n^[^A]*(A[^A]*A[^A]*)*$\n\n", "This searches for a block with an odd number of A's. If you found one, the string is bad for you:\n(?<!A)A(AA)*(?!A)\n\nIf I understand correctly, the Python code should look like:\nif re.search(\"(?<!A)A(AA)*(?!A)\", \"AeAAi\"):\n print \"fail\"\n\n", "Why work so hard coming up with a hard to read pattern? Just search for all occurrences of the pattern and count how many you find. \nlen(re.findall(\"A\", \"AbcAbcAbcA\")) % 2 == 0\n\nThat should be instantly understandable by all experienced programmers, whereas a pattern like \"(?\n\nSimple is better.\n", "'A*' means match any number of A's. Even 0.\nHere's how to match a string with an even number of a's, upper or lower:\nre.compile(r'''\n ^\n [^a]*\n (\n (\n a[^a]*\n ){2}\n # if there must be at least 2 (not just 0), change the\n # '*' on the following line to '+'\n )* \n $\n ''',re.IGNORECASE|re.VERBOSE)\n\nYou probably are using a as an example. If you want to match a specific character other than a, replace a with %s and then insert\n[...]\n$\n'''%( other_char, other_char, other_char )\n[...]\n\n", "'*' means 0 or more occurences\n'AA' should do the trick.\nThe question is if you want the thing to match 'AAA'. In that case you would have to do something like:\nr = re.compile('(^|[^A])(AA)+(?!A)',)\nr.search(p)\n\nThat would work for match even (and only even) number of'A'.\nNow if you want to match 'if there is any even number of subsequent letters', this would do the trick:\nre.compile(r'(.)\\1')\n\nHowever, this wouldn't exclude the 'odd' occurences. But it is not clear from your question if you really want that.\nUpdate:\nThis works for you test cases:\nre.compile('^([^A]*)AA([^A]|AA)*$')\n\n", "First of all, note that /A*/ matches the empty string.\nSecondly, there are some things that you just can't do with regular expressions. This'll be a lot easier if you just walk through the string and count up all occurences of the letter you're looking for.\n", "A* means match \"A\" zero or more times.\nFor an even number of \"A\", try: (AA)+\n", "It's impossible to count arbitrarily using regular expressions. For example, making sure that you have matching parenthesis. To count you need 'memory' which requires something at least as strong as a pushdown automaton, although in this case you can use the regular expression that @Gumbo provided.\nThe suggestion to use finditeris the best workaround for the general case.\n" ]
[ 27, 3, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002045175_python_regex.txt
Q: Search and sort data from several files I have a set of 1000 text files with names in_s1.txt, in_s2.txt and so. Each file contains millions of rows and each row has 7 columns like: ccc245 1 4 5 5 3 -12.3 For me the most important is the values from the first and seventh columns; the pairs ccc245 , -12.3 What I need to do is to find between all the in_sXXXX.txt files, the 10 cases with the lowest values of the seventh column value, and I also need to get where each value is located, in which file. I need something like: FILE 1st_col 7th_col in_s540.txt ccc3456 -9000.5 in_s520.txt ccc488 -723.4 in_s12.txt ccc34 -123.5 in_s344.txt ccc56 -45.6 I was thinking about using python and bash for this purpose but at the moment I did not find a practical approach. All what I know to do is: concatenate all in_ files in IN.TXT search the lowest values there using: for i in IN.TXT ; do sort -k6n $i | head -n 10; done given the 1st_col and 7th_col values of the top ten list, use them to filter the in_s files, using grep -n VALUE in_s*, so I get for each value the name of the file It works but it is a bit tedious. I wonder about a faster approach only using bash or python or both. Or another better language for this. Thanks A: In python, use the nsmallest function in the heapq module -- it's designed for exactly this kind of task. Example (tested) for Python 2.5 and 2.6: import heapq, glob def my_iterable(): for fname in glob.glob("in_s*.txt"): f = open(fname, "r") for line in f: items = line.split() yield fname, items[0], float(items[6]) f.close() result = heapq.nsmallest(10, my_iterable(), lambda x: x[2]) print result Update after above answer accepted Looking at the source code for Python 2.6, it appears that there's a possibility that it does list(iterable) and works on that ... if so, that's not going to work with a thousand files each with millions of lines. If the first answer gives you MemoryError etc, here's an alternative which limits the size of the list to n (n == 10 in your case). Note: 2.6 only; if you need it for 2.5 use a conditional heapreplace() as explained in the docs. Uses heappush() and heappushpop() which don't have the key arg :-( so we have to fake it. import glob from heapq import heappush, heappushpop from pprint import pprint as pp def my_iterable(): for fname in glob.glob("in_s*.txt"): f = open(fname, "r") for line in f: items = line.split() yield -float(items[6]), fname, items[0] f.close() def homegrown_nlargest(n, iterable): """Ensures heap never has more than n entries""" heap = [] for item in iterable: if len(heap) < n: heappush(heap, item) else: heappushpop(heap, item) return heap result = homegrown_nlargest(10, my_iterable()) result = sorted(result, reverse=True) result = [(fname, fld0, -negfld6) for negfld6, fname, fld0 in result] pp(result) A: I would: take first 10 items, sort them and then for every line read from files insert the element into those top10: in case its value is lower than highest one from current top10, (keeping the sorting for performance) I wouldn't post the complete program here as it looks like homework. Yes, if it wasn't ten, this would be not optimal A: Try something like this in python: min_values = [] def add_to_min(file_name, one, seven): # checks to see if 7th column is a lower value than exiting values if len(min_values) == 0 or seven < max(min_values)[0]: # let's remove the biggest value min_values.sort() if len(min_values) != 0: min_values.pop() # and add the new value tuple min_values.append((seven, file_name, one)) # loop through all the files for file_name in os.listdir(<dir>): f = open(file_name) for line in file_name.readlines(): columns = line.split() add_to_min(file_name, columns[0], float(columns[6])) # print answers for (seven, file_name, one) in min_values: print file_name, one, seven Haven't tested it, but it should get you started. Version 2, just runs the sort a single time (after a prod by S. Lott): values = [] # loop through all the files and make a long list of all the rows for file_name in os.listdir(<dir>): f = open(file_name) for line in file_name.readlines(): columns = line.split() values.append((file_name, columns[0], float(columns[6])) # sort values, print the 10 smallest values.sort() for (seven, file_name, one) in values[:10] print file_name, one, seven Just re-read you question, with millions of rows, you might run out of RAM.... A: A small improvement of your shell solution: $ cat in.txt in_s1.txt in_s2.txt ... $ cat in.txt | while read i do cat $i | sed -e "s/^/$i /" # add filename as first column done | sort -n -k8 | head -10 | cut -d" " -f1,2,8 A: If your files are million lines, you might want to consider using "buffering". the below script goes through those million lines, each time comparing field 7 with those in the buffer. If a value is smaller than those in the buffer, one of them in buffer is replaced by the new lower value. for file in in_*.txt do awk -vt=$t 'NR<=10{ c=c+1 val[c]=$7 tag[c]=$1 } NR>10{ for(o=1;o<=c;o++){ if ( $7 <= val[o] ){ val[o]=$7 tag[o]=$1 break } } } END{ for(i=1;i<=c;i++){ print val[i], tag[i] | "sort" } }' $file done A: This might be close to what you're looking for: for file in *; do sort -k6n "$file" | head -n 10 | cut -f1,7 -d " " | sed "s/^/$file /" > "${file}.out"; done cat *.out | sort -k3n | head -n 10 > final_result.out
Search and sort data from several files
I have a set of 1000 text files with names in_s1.txt, in_s2.txt and so. Each file contains millions of rows and each row has 7 columns like: ccc245 1 4 5 5 3 -12.3 For me the most important is the values from the first and seventh columns; the pairs ccc245 , -12.3 What I need to do is to find between all the in_sXXXX.txt files, the 10 cases with the lowest values of the seventh column value, and I also need to get where each value is located, in which file. I need something like: FILE 1st_col 7th_col in_s540.txt ccc3456 -9000.5 in_s520.txt ccc488 -723.4 in_s12.txt ccc34 -123.5 in_s344.txt ccc56 -45.6 I was thinking about using python and bash for this purpose but at the moment I did not find a practical approach. All what I know to do is: concatenate all in_ files in IN.TXT search the lowest values there using: for i in IN.TXT ; do sort -k6n $i | head -n 10; done given the 1st_col and 7th_col values of the top ten list, use them to filter the in_s files, using grep -n VALUE in_s*, so I get for each value the name of the file It works but it is a bit tedious. I wonder about a faster approach only using bash or python or both. Or another better language for this. Thanks
[ "In python, use the nsmallest function in the heapq module -- it's designed for exactly this kind of task.\nExample (tested) for Python 2.5 and 2.6:\nimport heapq, glob\n\ndef my_iterable():\n for fname in glob.glob(\"in_s*.txt\"):\n f = open(fname, \"r\")\n for line in f:\n items = line.split()\n yield fname, items[0], float(items[6])\n f.close()\n\nresult = heapq.nsmallest(10, my_iterable(), lambda x: x[2])\nprint result\n\nUpdate after above answer accepted\nLooking at the source code for Python 2.6, it appears that there's a possibility that it does list(iterable) and works on that ... if so, that's not going to work with a thousand files each with millions of lines. If the first answer gives you MemoryError etc, here's an alternative which limits the size of the list to n (n == 10 in your case).\nNote: 2.6 only; if you need it for 2.5 use a conditional heapreplace() as explained in the docs. Uses heappush() and heappushpop() which don't have the key arg :-( so we have to fake it.\nimport glob\nfrom heapq import heappush, heappushpop\nfrom pprint import pprint as pp\n\ndef my_iterable():\n for fname in glob.glob(\"in_s*.txt\"):\n f = open(fname, \"r\")\n for line in f:\n items = line.split()\n yield -float(items[6]), fname, items[0]\n f.close()\n\ndef homegrown_nlargest(n, iterable):\n \"\"\"Ensures heap never has more than n entries\"\"\"\n heap = []\n for item in iterable:\n if len(heap) < n:\n heappush(heap, item)\n else:\n heappushpop(heap, item)\n return heap\n\nresult = homegrown_nlargest(10, my_iterable())\nresult = sorted(result, reverse=True)\nresult = [(fname, fld0, -negfld6) for negfld6, fname, fld0 in result]\npp(result)\n\n", "I would:\n\ntake first 10 items, \nsort them and then \nfor every line read from files insert the element into those top10:\n\n\nin case its value is lower than highest one from current top10, \n(keeping the sorting for performance)\n\n\nI wouldn't post the complete program here as it looks like homework.\nYes, if it wasn't ten, this would be not optimal\n", "Try something like this in python:\nmin_values = []\n\ndef add_to_min(file_name, one, seven):\n # checks to see if 7th column is a lower value than exiting values\n if len(min_values) == 0 or seven < max(min_values)[0]:\n # let's remove the biggest value\n min_values.sort()\n if len(min_values) != 0:\n min_values.pop()\n # and add the new value tuple\n min_values.append((seven, file_name, one))\n\n# loop through all the files\nfor file_name in os.listdir(<dir>):\n f = open(file_name)\n for line in file_name.readlines():\n columns = line.split()\n add_to_min(file_name, columns[0], float(columns[6]))\n\n# print answers\nfor (seven, file_name, one) in min_values:\n print file_name, one, seven\n\nHaven't tested it, but it should get you started.\nVersion 2, just runs the sort a single time (after a prod by S. Lott):\nvalues = []\n# loop through all the files and make a long list of all the rows\nfor file_name in os.listdir(<dir>):\n f = open(file_name)\n for line in file_name.readlines():\n columns = line.split()\n values.append((file_name, columns[0], float(columns[6]))\n\n# sort values, print the 10 smallest\nvalues.sort()\nfor (seven, file_name, one) in values[:10]\n print file_name, one, seven\n\nJust re-read you question, with millions of rows, you might run out of RAM....\n", "A small improvement of your shell solution:\n$ cat in.txt\nin_s1.txt\nin_s2.txt\n...\n$ cat in.txt | while read i\ndo\n cat $i | sed -e \"s/^/$i /\" # add filename as first column\ndone |\nsort -n -k8 | head -10 | cut -d\" \" -f1,2,8\n\n", "If your files are million lines, you might want to consider using \"buffering\". the below script goes through those million lines, each time comparing field 7 with those in the buffer. If a value is smaller than those in the buffer, one of them in buffer is replaced by the new lower value. \n for file in in_*.txt\n do\n awk -vt=$t 'NR<=10{\n c=c+1\n val[c]=$7\n tag[c]=$1\n }\n NR>10{\n for(o=1;o<=c;o++){\n if ( $7 <= val[o] ){\n val[o]=$7\n tag[o]=$1\n break\n }\n }\n }\n END{\n for(i=1;i<=c;i++){\n print val[i], tag[i] | \"sort\"\n }\n\n }' $file\n done\n\n", "This might be close to what you're looking for:\nfor file in *; do sort -k6n \"$file\" | head -n 10 | cut -f1,7 -d \" \" | sed \"s/^/$file /\" > \"${file}.out\"; done\n\ncat *.out | sort -k3n | head -n 10 > final_result.out\n\n" ]
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002048779_bash_python.txt
Q: Writing copyright information in python code What is the standard way of writing "copyright information" in python code? Should it be inside docstring or in block comments? I could not find it in PEPs. A: Some projects use module variables like __license__, as in: __author__ = "Software Authors Name" __copyright__ = "Copyright (C) 2004 Author Name" __license__ = "Public Domain" __version__ = "1.0" Seems like a pretty clean solution to me (unless you overdo it and dump epic texts into these variables), but only __version__ seems to be in widespread use, as it is mentioned in PEP 8. A: # Comment in the beginning of the file At least python built-in modules do this. (found out by doing grep 'Copyright' /usr/lib64/python2.4/*.py) A: We follow the recommendations found (somewhere) on the Software Freedom Law Center's site. Here is an example of a simple GPL'ed file. A: As I know, there is currently no standard way. Each company/organization will have their own template to doc the copyright information. If this is your personal project, then just feel free to doc it in the way you feel most comforable. Adding a LICENSE file is a very common way for projects with many source files. Even in Python, there is currently no standard on the structure of docstrings. Python provides a lot of freedom, so just let it be dude ;)
Writing copyright information in python code
What is the standard way of writing "copyright information" in python code? Should it be inside docstring or in block comments? I could not find it in PEPs.
[ "Some projects use module variables like __license__, as in:\n__author__ = \"Software Authors Name\"\n__copyright__ = \"Copyright (C) 2004 Author Name\"\n__license__ = \"Public Domain\"\n__version__ = \"1.0\"\n\nSeems like a pretty clean solution to me (unless you overdo it and dump epic texts into these variables), but only __version__ seems to be in widespread use, as it is mentioned in PEP 8.\n", "# Comment in the beginning of the file\n\nAt least python built-in modules do this. (found out by doing grep 'Copyright' /usr/lib64/python2.4/*.py)\n", "We follow the recommendations found (somewhere) on the Software Freedom Law Center's site. Here is an example of a simple GPL'ed file.\n", "As I know, there is currently no standard way. Each company/organization will have their own template to doc the copyright information. If this is your personal project, then just feel free to doc it in the way you feel most comforable. Adding a LICENSE file is a very common way for projects with many source files. Even in Python, there is currently no standard on the structure of docstrings.\nPython provides a lot of freedom, so just let it be dude ;)\n" ]
[ 39, 13, 6, 3 ]
[]
[]
[ "coding_style", "copyright_display", "python" ]
stackoverflow_0002048874_coding_style_copyright_display_python.txt
Q: How to get a function to execute I have a function and I want it to execute. Does anyone know how to do this? def a(): a = 'print' print a A: The name of your function is a. It takes no arguments. So call it using a(): >>> def a(): ... a = 'print' ... print a ... >>> a() print Note that you shadow the definition of a as a function within a itself, by defining a local variable with that same name. You may want to avoid that, as it may confuse you or other readers of your code. Also, it makes it impossible to apply recursion. Anyway, in general, if f is some function object then you can call it by putting parentheses behind it, possibly containing some arguments. Example: >>> def twice(text): ... print text ... print text ... >>> twice('the text I want to print twice') the text I want to print twice the text I want to print twice A: To do this you just use. a() If you want this for use inside the current file use: if __name__ == '__main__': a() And if you want to pass the variable a on for use in other functions use: if __name__ == '__main__': b = a() The 'b' being the variable and 'a' being the function you have defined. So the whole function could look like this: def a(): b = 'print' print b if __name__ == '__main__': b = a() A: just write a() ! A: I'm not sure I understood your question, but a simple function call goes as in a() of course, after the definition, so it would be def a(): a = 'print' print a a()
How to get a function to execute
I have a function and I want it to execute. Does anyone know how to do this? def a(): a = 'print' print a
[ "The name of your function is a. It takes no arguments. So call it using a():\n>>> def a():\n... a = 'print'\n... print a\n... \n>>> a()\nprint\n\nNote that you shadow the definition of a as a function within a itself, by defining a local variable with that same name. You may want to avoid that, as it may confuse you or other readers of your code. Also, it makes it impossible to apply recursion.\nAnyway, in general, if f is some function object then you can call it by putting parentheses behind it, possibly containing some arguments. Example:\n>>> def twice(text):\n... print text\n... print text\n... \n>>> twice('the text I want to print twice')\nthe text I want to print twice\nthe text I want to print twice\n\n", "To do this you just use.\na()\n\nIf you want this for use inside the current file use:\nif __name__ == '__main__': a()\n\nAnd if you want to pass the variable a on for use in other functions use:\nif __name__ == '__main__': b = a()\n\nThe 'b' being the variable and 'a' being the function you have defined.\nSo the whole function could look like this:\ndef a():\n\n b = 'print'\n print b\n\nif __name__ == '__main__': b = a()\n\n", "just write a() !\n", "I'm not sure I understood your question, but a simple function call goes as in\na()\n\nof course, after the definition, so it would be \ndef a():\n\n a = 'print'\n print a\n\na()\n\n" ]
[ 14, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002049605_python.txt
Q: Change the events for different parts of the same widget I have created a margin in a gtk.TextView widget. Now I want to make sure that the default event handler for mouse click, which is moving the text cursor to the clicked position, works only when clicked to the right of the margin. Is this possible? A: Try connecting to the button-press-event but doing it before the widget's own connection. If you connect after the view does it, this will be the default (GObject signal handlers are handled in reverse order of connection by default). Then determine if the event should be let through or not, by returning TRUE (to stop the event) or FALSE as required.
Change the events for different parts of the same widget
I have created a margin in a gtk.TextView widget. Now I want to make sure that the default event handler for mouse click, which is moving the text cursor to the clicked position, works only when clicked to the right of the margin. Is this possible?
[ "Try connecting to the button-press-event but doing it before the widget's own connection. If you connect after the view does it, this will be the default (GObject signal handlers are handled in reverse order of connection by default). Then determine if the event should be let through or not, by returning TRUE (to stop the event) or FALSE as required.\n" ]
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002033810_gtk_pygtk_python.txt
Q: architecture of chat website using twisted matrix I am willing to devlop a anonymus chat website.The website pairs 2 random people who are logged into the website and then allows them to chat to each other.Now if any one of them gets disconnected then the other will get connected to any other person who is single. Now i have some doubts regarding archicture. Each time there is a messages sent by any one the server recievies it and then forwards to other.Now to handle these meaases(both ways) i am willing to create a server in python. The server just forwards the message to appropriate person and handles pairing of users. Now when the user connects for first time he must get a html page along with js.Then the actual paring and message forwarding shold be done by my python server.Python server will be written by me using twisted matrix framework.But how do i giv a webpage first to user and then handle messages by sever? A: Take a look at Nevow and Athena. These will let you serve web pages to clients and handle messages sent back from them.
architecture of chat website using twisted matrix
I am willing to devlop a anonymus chat website.The website pairs 2 random people who are logged into the website and then allows them to chat to each other.Now if any one of them gets disconnected then the other will get connected to any other person who is single. Now i have some doubts regarding archicture. Each time there is a messages sent by any one the server recievies it and then forwards to other.Now to handle these meaases(both ways) i am willing to create a server in python. The server just forwards the message to appropriate person and handles pairing of users. Now when the user connects for first time he must get a html page along with js.Then the actual paring and message forwarding shold be done by my python server.Python server will be written by me using twisted matrix framework.But how do i giv a webpage first to user and then handle messages by sever?
[ "Take a look at Nevow and Athena. These will let you serve web pages to clients and handle messages sent back from them.\n" ]
[ 3 ]
[]
[]
[ "chat", "python", "twisted" ]
stackoverflow_0002046973_chat_python_twisted.txt
Q: Why can't I pickle this object? I have a class (below): class InstrumentChange(object): '''This class acts as the DTO object to send instrument change information from the client to the server. See InstrumentChangeTransport below ''' def __init__(self, **kwargs): self.kwargs = kwargs self._changed = None def _method_name(self, text): return text.replace(' ','_').lower() def _what_changed(self): ''' Denotes the column that changed on the instrument returning the column_name of what changed.''' if not self._changed: self._changed = self._method_name(self.kwargs.pop('What Changed')) return self._changed def __getattr__(self, attr): for key in self.kwargs.iterkeys(): if self._method_name(key) == attr: return self.kwargs[key] def __str__(self): return "Instrument:%s" % self.kwargs __repr__ = __str__ what_changed = property(_what_changed) When I run the following test: def test_that_instrumentchangetransport_is_picklable(self): test_dict = {'Updated': 'PAllum', 'Description': 'BR/EUR/BRAZIL/11%/26/06/2017/BD', 'Ask Q': 500, 'Bbg': 'On', 'C Bid': 72.0, 'Benchmark': 'NL/USD/KKB/7.000%/03/11/2009/BD', 'ISIN': 'XS0077157575', 'Bid YTM': 0.0, 'Bid Q': 100, 'C Ask': 72.25, 'Ask YTM': 0.0, 'Bid ASW': 0.0, 'Position': 1280000, 'What Changed': 'C Bid', 'Ask ASW': 0.0} ins_change = InstrumentChangeTransport(**test_dict) assert isinstance(ins_change, InstrumentChangeTransport) # Create a mock filesystem object file = open('testpickle.dat', 'w') file = Mock() pickle.dump(ins_change, file) I get: Traceback (most recent call last): File "c:\python23\lib\site-packages\nose-0.11.0-py2.3.egg\nose\case.py", line 183, in runTest self.test(*self.arg) File "C:\Code\branches\demo\tests\test_framework.py", line 142, in test_that_instrumentchangetransport_is_picklable pickle.dump(ins_change, file) File "C:\Python23\Lib\copy_reg.py", line 83, in _reduce_ex dict = getstate() TypeError: 'NoneType' object is not callable I've looked at the pickle docs, but I don't quite get it. Any ideas? Ben A: Your code has several minor "side" issues: the sudden appearance of a 'Transport' in the class name used in the test (it's not the class name that you're defining), the dubious trampling over built-in identifier file as a local variable (don't do that -- it doesn't hurt here, but the habit of trampling over built-in identifiers will cause mysterious bugs one day), the misuses of Mock that has already been noted, the default use of the slowest, grungiest pickling protocol and text rather than binary for the pickle file. However, at the heart, as @coonj says, is the lack of state control. A "normal" class doesn't need it (because self.__dict__ gets pickled and unpickled by default in classes missing state control and without other peculiarities) -- but since you're overriding __getattr__ that doesn't apply to your class. You just need two more very simple methods: def __getstate__(self): return self.__dict__ def __setstate__(self, d): self.__dict__.update(d) which basically tell pickle to treat your class just like a normal one, taking self.__dict__ as representing the whole of the instance state, despite the existence of the __getattr__. A: It is failing because it can't find __getstate__() for your object. Pickle needs these to determine how to pickle/unpickle the object. You just need the __getstate__() and __setstate__() methods. See the TextReader example in the docs: http://docs.python.org/library/pickle.html Update: I just looked at the sourceforge page for the Mock module, and I think you are also using it incorrectly. You are mocking a file-object, but when pickle tries to read from it, it won't get anything back which is why getattr() returns none. A: file = open('testpickle.dat', 'w') file = Mock() You are losing here reference to the opened file. Might that be a problem?
Why can't I pickle this object?
I have a class (below): class InstrumentChange(object): '''This class acts as the DTO object to send instrument change information from the client to the server. See InstrumentChangeTransport below ''' def __init__(self, **kwargs): self.kwargs = kwargs self._changed = None def _method_name(self, text): return text.replace(' ','_').lower() def _what_changed(self): ''' Denotes the column that changed on the instrument returning the column_name of what changed.''' if not self._changed: self._changed = self._method_name(self.kwargs.pop('What Changed')) return self._changed def __getattr__(self, attr): for key in self.kwargs.iterkeys(): if self._method_name(key) == attr: return self.kwargs[key] def __str__(self): return "Instrument:%s" % self.kwargs __repr__ = __str__ what_changed = property(_what_changed) When I run the following test: def test_that_instrumentchangetransport_is_picklable(self): test_dict = {'Updated': 'PAllum', 'Description': 'BR/EUR/BRAZIL/11%/26/06/2017/BD', 'Ask Q': 500, 'Bbg': 'On', 'C Bid': 72.0, 'Benchmark': 'NL/USD/KKB/7.000%/03/11/2009/BD', 'ISIN': 'XS0077157575', 'Bid YTM': 0.0, 'Bid Q': 100, 'C Ask': 72.25, 'Ask YTM': 0.0, 'Bid ASW': 0.0, 'Position': 1280000, 'What Changed': 'C Bid', 'Ask ASW': 0.0} ins_change = InstrumentChangeTransport(**test_dict) assert isinstance(ins_change, InstrumentChangeTransport) # Create a mock filesystem object file = open('testpickle.dat', 'w') file = Mock() pickle.dump(ins_change, file) I get: Traceback (most recent call last): File "c:\python23\lib\site-packages\nose-0.11.0-py2.3.egg\nose\case.py", line 183, in runTest self.test(*self.arg) File "C:\Code\branches\demo\tests\test_framework.py", line 142, in test_that_instrumentchangetransport_is_picklable pickle.dump(ins_change, file) File "C:\Python23\Lib\copy_reg.py", line 83, in _reduce_ex dict = getstate() TypeError: 'NoneType' object is not callable I've looked at the pickle docs, but I don't quite get it. Any ideas? Ben
[ "Your code has several minor \"side\" issues: the sudden appearance of a 'Transport' in the class name used in the test (it's not the class name that you're defining), the dubious trampling over built-in identifier file as a local variable (don't do that -- it doesn't hurt here, but the habit of trampling over built-in identifiers will cause mysterious bugs one day), the misuses of Mock that has already been noted, the default use of the slowest, grungiest pickling protocol and text rather than binary for the pickle file.\nHowever, at the heart, as @coonj says, is the lack of state control. A \"normal\" class doesn't need it (because self.__dict__ gets pickled and unpickled by default in classes missing state control and without other peculiarities) -- but since you're overriding __getattr__ that doesn't apply to your class. You just need two more very simple methods:\ndef __getstate__(self): return self.__dict__\ndef __setstate__(self, d): self.__dict__.update(d)\n\nwhich basically tell pickle to treat your class just like a normal one, taking self.__dict__ as representing the whole of the instance state, despite the existence of the __getattr__.\n", "It is failing because it can't find __getstate__() for your object. Pickle needs these to determine how to pickle/unpickle the object. You just need the __getstate__() and __setstate__() methods.\nSee the TextReader example in the docs: http://docs.python.org/library/pickle.html\nUpdate: I just looked at the sourceforge page for the Mock module, and I think you are also using it incorrectly.\nYou are mocking a file-object, but when pickle tries to read from it, it won't get anything back which is why getattr() returns none.\n", " file = open('testpickle.dat', 'w')\n file = Mock()\n\nYou are losing here reference to the opened file. Might that be a problem?\n" ]
[ 37, 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002049849_python.txt
Q: python CGI and JQUERY problem I have a simple python CGI script where I query a MySQL database and then prints the result to the screen/webpage. My problem is that the "cursor.execute()" function returns a list of tuples. I use a simple for loop to iterate through this list and extract each tuple. This was working great until.....I got the bright idea to use jquery to make some eyecandy for the user. My whole script still work....except the for loop. I have tried to (to my mind) everything, but for some reason when I do a loop it breaks everything. Could someone enlighten me please. I have also noticed that if I try and seperate my HTML formatting and python code by using function calls this also breaks the whole thing. By breaking I mean I get a server error(apache) Below is the error via /var/log/httpd/error.log: [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] ^, referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] SyntaxError, referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] : , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] invalid syntax, referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] Premature end of script headers: userdata_submit.py, referer: http://test/index-test.html A: It looks like you have a syntax error. In Python and Javascript, the code: {referer: http://test/index-test.html} is invalid. In Javascript, you'd have to write it like: {referer: "http://test/index-test.html"} and in Python (assuming "referer" is a key and not a variable) as: {"referer": "http://test/index-test.html"} It's hard to tell from your log, but you may have a similar problem with other keys in the same hash/dictionary prior to the referer key.
python CGI and JQUERY problem
I have a simple python CGI script where I query a MySQL database and then prints the result to the screen/webpage. My problem is that the "cursor.execute()" function returns a list of tuples. I use a simple for loop to iterate through this list and extract each tuple. This was working great until.....I got the bright idea to use jquery to make some eyecandy for the user. My whole script still work....except the for loop. I have tried to (to my mind) everything, but for some reason when I do a loop it breaks everything. Could someone enlighten me please. I have also noticed that if I try and seperate my HTML formatting and python code by using function calls this also breaks the whole thing. By breaking I mean I get a server error(apache) Below is the error via /var/log/httpd/error.log: [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] ^, referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] SyntaxError, referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] : , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] invalid syntax, referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] , referer: http://test/index-test.html [Tue Jan 12 14:56:25 2010] [error] [client 192.168.7.32] Premature end of script headers: userdata_submit.py, referer: http://test/index-test.html
[ "It looks like you have a syntax error. In Python and Javascript, the code:\n{referer: http://test/index-test.html}\n\nis invalid. In Javascript, you'd have to write it like:\n{referer: \"http://test/index-test.html\"}\n\nand in Python (assuming \"referer\" is a key and not a variable) as:\n{\"referer\": \"http://test/index-test.html\"}\n\nIt's hard to tell from your log, but you may have a similar problem with other keys in the same hash/dictionary prior to the referer key.\n" ]
[ 0 ]
[]
[]
[ "cgi", "jquery", "python" ]
stackoverflow_0002049506_cgi_jquery_python.txt
Q: python to Java checksum calculation I received this python script that generates a file checksum: import sys,os if __name__=="__main__": #filename=os.path.abspath(sys.argv[1]) #filename=r"H:\Javier Ortiz\559-7 From Pump.bin" cksum=0 offset=0 pfi=open(filename,'rb') while 1: icks=0 chunk=pfi.read(256) if not chunk: break #if EOF exit loop for iter in chunk: icks+=ord(iter) print ord(iter) cksum=(cksum+icks) & 0xffff pfi.close() print "cksum=0x%4.4x"%cksum And I'm trying to convert it to Java but I'm not geting the same results. Here's my Java code: import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class ChecksumCalculator { private ChecksumCalculator() { } public static int getChecksum(File file) { int cksum = 0; FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); // Here BufferedInputStream is added for fast reading. bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); byte[] buffer = new byte[256]; // dis.available() returns 0 if the file does not have more lines. while (dis.read(buffer) != -1) { int icks = 0; for (byte b : buffer) { icks += b & 0xff; System.out.println(b & 0xff); } cksum = (cksum + icks) & 0xffff; System.out.println("Checksum: " + cksum); } // dispose all the resources after using them. fis.close(); bis.close(); dis.close(); return cksum; } catch (FileNotFoundException e) { e.printStackTrace(); return -1; } catch (IOException e) { e.printStackTrace(); return -1; } } static public void main(String[] s) { System.out.println("0x" + getChecksum(new File("H:\\Javier Ortiz\\559-7 From Pump.bin"))); } } But I get different results on a file. For example if I run it on a plain txt file containing only the word test it gives out the following result: python: cksum=0x01c0 java: cksum=0x448 Any idea? A: Your Python version prints the checksum in hex, while your Java version prints it in decimal. You should make your Java version print in hex, too. 0x1c0 == 448. To use the cksum=0x%4.4x format string as you had in your Python version, use this: System.out.printf("cksum=0x%4.4x%n", ...); or even better System.out.printf("cksum=%#04x%n", ...); Also, you don't need a DataInputStream for this. Just use bis.read(buffer) instead of dis.read(buffer). A: 1C016 = 44810 I think that's your problem. A: dis.read(buffer) returns the number of bytes that was actually read. For the last chunk, it will probably be less than 256. So the for loop shouldn't always be performed 256 times - it should be performed as many times as the actual byte count that was read from the stream. I'm not a Python developer, but it doesn't look like ord(icks) in Python does the same as b & 0xff in Java. Keep in mind that all Java types are signed; this might affect the calculation. Also, although this doesn't affect correctness - it's a good practice to clean all the resources (i.e. to close the streams) in a finally block.
python to Java checksum calculation
I received this python script that generates a file checksum: import sys,os if __name__=="__main__": #filename=os.path.abspath(sys.argv[1]) #filename=r"H:\Javier Ortiz\559-7 From Pump.bin" cksum=0 offset=0 pfi=open(filename,'rb') while 1: icks=0 chunk=pfi.read(256) if not chunk: break #if EOF exit loop for iter in chunk: icks+=ord(iter) print ord(iter) cksum=(cksum+icks) & 0xffff pfi.close() print "cksum=0x%4.4x"%cksum And I'm trying to convert it to Java but I'm not geting the same results. Here's my Java code: import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class ChecksumCalculator { private ChecksumCalculator() { } public static int getChecksum(File file) { int cksum = 0; FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); // Here BufferedInputStream is added for fast reading. bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); byte[] buffer = new byte[256]; // dis.available() returns 0 if the file does not have more lines. while (dis.read(buffer) != -1) { int icks = 0; for (byte b : buffer) { icks += b & 0xff; System.out.println(b & 0xff); } cksum = (cksum + icks) & 0xffff; System.out.println("Checksum: " + cksum); } // dispose all the resources after using them. fis.close(); bis.close(); dis.close(); return cksum; } catch (FileNotFoundException e) { e.printStackTrace(); return -1; } catch (IOException e) { e.printStackTrace(); return -1; } } static public void main(String[] s) { System.out.println("0x" + getChecksum(new File("H:\\Javier Ortiz\\559-7 From Pump.bin"))); } } But I get different results on a file. For example if I run it on a plain txt file containing only the word test it gives out the following result: python: cksum=0x01c0 java: cksum=0x448 Any idea?
[ "Your Python version prints the checksum in hex, while your Java version prints it in decimal. You should make your Java version print in hex, too. 0x1c0 == 448.\nTo use the cksum=0x%4.4x format string as you had in your Python version, use this:\nSystem.out.printf(\"cksum=0x%4.4x%n\", ...);\n\nor even better\nSystem.out.printf(\"cksum=%#04x%n\", ...);\n\nAlso, you don't need a DataInputStream for this. Just use bis.read(buffer) instead of dis.read(buffer).\n", "1C016 = 44810\nI think that's your problem.\n", "\ndis.read(buffer) returns the number of bytes that was actually read. For the last chunk, it will probably be less than 256. So the for loop shouldn't always be performed 256 times - it should be performed as many times as the actual byte count that was read from the stream.\nI'm not a Python developer, but it doesn't look like ord(icks) in Python does the same as b & 0xff in Java.\nKeep in mind that all Java types are signed; this might affect the calculation.\n\nAlso, although this doesn't affect correctness - it's a good practice to clean all the resources (i.e. to close the streams) in a finally block.\n" ]
[ 5, 3, 1 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002050325_java_python.txt
Q: Django/Python - Try/except problem i have code like this: try: var = request.POST['var'] except NameError: var = '' Why always code after "except" is executing? Even if request.POST['var'] exist. A: How do you know it is executing? Perhaps request.POST['var'] is also '' so you couldn't tell the difference. Also, the only way that var = request.POST['var'] could raise a NameError is if request doesn't exist. If request.POST doesn't exist, means POST doesn't exist as an attribute of request thus raising AttributeError instead, and if request.POST['var'] doesn't exist, means 'var' is not a key of request.POST thus raising KeyError instead. EDIT: My guess is that you're not sending a POST. But can't know for sure. A: Eliminate the guesswork and replace NameError with something like KeyboardInterrupt, look at the traceback and you'll know exactly what the problem is. A: A better way to do what you seem to be trying to do might be var = request.POST.get('var', 'some default value') where the second argument to the POST dict's get method is the value to return if the key ('var' in this case) doesn't exist. Translating your example exactly would result in: var = request.POST.get('var', '') That way, no try...except block or conditional statements are needed. A: what's the result of the following in your case? except NameError, e: print e A: try try: if request.method == 'POST': var = request.POST['var'] except NameError: var = ''
Django/Python - Try/except problem
i have code like this: try: var = request.POST['var'] except NameError: var = '' Why always code after "except" is executing? Even if request.POST['var'] exist.
[ "How do you know it is executing? Perhaps request.POST['var'] is also '' so you couldn't tell the difference.\nAlso, the only way that \nvar = request.POST['var'] \n\ncould raise a NameError is if request doesn't exist.\nIf request.POST doesn't exist, means POST doesn't exist as an attribute of request thus raising AttributeError instead, and if request.POST['var'] doesn't exist, means 'var' is not a key of request.POST thus raising KeyError instead.\n\nEDIT:\nMy guess is that you're not sending a POST. But can't know for sure.\n", "Eliminate the guesswork and replace NameError with something like KeyboardInterrupt, look at the traceback and you'll know exactly what the problem is.\n", "A better way to do what you seem to be trying to do might be\nvar = request.POST.get('var', 'some default value')\n\nwhere the second argument to the POST dict's get method is the value to return if the key ('var' in this case) doesn't exist. Translating your example exactly would result in:\nvar = request.POST.get('var', '')\n\nThat way, no try...except block or conditional statements are needed.\n", "what's the result of the following in your case?\nexcept NameError, e:\n print e\n\n", "try\n\ntry:\n if request.method == 'POST':\n var = request.POST['var'] \nexcept NameError: \n var = ''\n\n" ]
[ 8, 2, 1, 1, 0 ]
[]
[]
[ "django", "python", "variables" ]
stackoverflow_0002050568_django_python_variables.txt
Q: Python: fill out a form and confirm with a button click Which do you think is the best method to fill out a form and confirm with clicking a button with Python? Do I have to use django? I want to do it in a simple way. Is there a library? Thanks in advance! A: mechanize A: There are tons. Check out this question for some gory details.
Python: fill out a form and confirm with a button click
Which do you think is the best method to fill out a form and confirm with clicking a button with Python? Do I have to use django? I want to do it in a simple way. Is there a library? Thanks in advance!
[ "mechanize\n", "There are tons. Check out this question for some gory details.\n" ]
[ 4, 3 ]
[]
[]
[ "button", "forms", "python" ]
stackoverflow_0002050705_button_forms_python.txt
Q: Standard Regex vs python regex discrepancy I am reading a book and they provide an example of how to match a given string with regular expressions. Here is their example: b*(abb*)*(a|∊) - Strings of a's and b's with no consecutive a's. Now I've tried converting it to python like so: >> p = re.compile(r'b*(abb*)*(a|)') # OR >> p = re.compile(r'b*(abb*)*(a|\b)') # BUT it still doesn't work >>> p.match('aa') <_sre.SRE_Match object at 0x7fd9ad028c68> My question is two-fold: What is the equivalent of epsilon in python to make the above example work? Can someone explain to me why theoretical or standard way of doing regular expressions does not work in python? Might it have something to do with the longest vs shortest matching? Clarification: For people asking what standard regex is - it is the formal language theory standard: http://en.wikipedia.org/wiki/Regular_expression#Formal_language_theory A: Actually, the example works just fine ... to a small details. I would write: >>> p = re.compile('b*(abb*)*a?') >>> m = p.match('aa') >>> print m.group(0) 'a' >>> m = p.match('abbabbabababbabbbbbaaaaa') >>> print m.group(0) abbabbabababbabbbbba Note that the group 0 returns the part of the string matched by the regular expression. As you can see, the expression matches a succession of a and b without repetition of a. If indeed, you want to check the whole string, you need to changed slightly: >>> p = re.compile('^b*(abb*)*a?$') >>> m = p.match('aa') >>> print m None the ^ and $ force recognition of the beginning and end of the string. At last, you can combine both methods by using the first regular expression, but testing at the end: >>> len(m.group(0)) == len('aa') Added: For the second part of the OT, it seems to me there is no discrepancy between the standard regex and the python implementation. Of course, the notation is slightly different, and the python implementation suggest some extensions (as most other packages). A: Thanks for the answers. I feel each answer had part of the answer. Here is what I was looking for. ? symbol is just a shorthand for (something|ε). Thus (a|ε) can be rewritten as a?. So the example becomes: b*(abb*)*a? In python we would write: p = re.compile(r'^b*(abb*)*a?$') The reason straight translation of regular regular expression syntax into python (i.e. copy and paste) does not work is because python matches the shortest substring (if the symbols $ or ^ are absent) while the theoretical regular expressions match longest initial substring. So for example if we had a string: s = 'aa' Our textbook regex b*(abb*)*a? would not match it because it has two a's. However if we copy it straight to python: >> p = re.compile(r'b*(abb*)*a?') >> bool(p.match(s)) True This is because our regex matches only the substring 'a' of our string 'aa'. In order to tell python to do a match on the whole string we have to tell it where the beginning and the end of the string is, with the ^ and $ symbols respectively: >> p = re.compile(r'^b*(abb*)*a?$') >> bool(p.match(s)) False Note that python regex match() matches at the beginning of the string, so it automatically assumes the ^ at the start. However the search() function does not, and thus we keep the ^. So for example: >> s = 'aa' >> p = re.compile(r'b*(abb*)*a?$') >> bool(p.match(s)) False # Correct >> bool(p.search(s)) True # Incorrect - search ignored the first 'a' A: 1 Use bool(p.match('aa')) to check if the regexp matches or not p = re.compile('b*(abb*)*a?$') \b matches border of string; place between \w and \W (word characters and non-word characters) 2 Regexp is quite standard in python. Yet every language has some flavour of them, they are not 100% portable. There are minor differences which you're expected to lookup prior to using regexp in any specific language. Addition \epsilon does not have special symbol in python. It is an empty character set. In your example a|\epsilon is equivalent to (a|) or just a?. After which $ is obligatory to match end of string. A: I'm not exactly sure how match works in python, but I think you might need to add ^....$ to your RE. RegExp matching usually matches sub-strings, and it finds the largest match, in the case of p.match('aa') that's "a" (probably the first one). ^...$ makes sure that you're matching the ENTIRE string, which is I believe what you want. Theoretical/standard reg exps assume that you're always matching the whole string, because you're using it to define a language of strings that match, not find a substring in an input string. A: You're matching because your regex matches any zero-width segment of any specimen text. You need to anchor your regex. Here's one way of doing it, using a zero-width lookahead assertion: re.compile(r'^(a(?!a)|b)*$') A: Your second re should be an appropriate replacement for epsilon, as best as I understand it, though I've never seen epsilon in a regex before. For what it's worth, your pattern is matching 'a'. That is to say, it is matching: zero or more "b"s (choosing zero) zero or more "(abb*)"s (choosing zero) one "a" or word ending (choosing an a). As Jonathan Feinberg pointed out, if you want to ensure the whole string matches, you have to anchor the beginning ('^') and end ('$') of your regex. You should also use a raw string whenever constructing regexes in python: r'my regex'. That will prevent excessive backslash escaping confusion. A: the problem with your expression is that it matches the empty string, meaning that if you do: >>> p = re.compile('b*(abb*)*(a|)') >>> p.match('c').group(0) '' and since re.match attempts to match the start of the string, you have to tell it to match it until the end of the string. just use $ for that >>> p = re.compile(r'b*(abb*)*(a|)$') >>> print p.match('c') None >>> p.match('ababababab').group(0) 'ababababab' ps- you may have noted that i used r'pattern' instead of 'pattern' more on that here (first paragraphs)
Standard Regex vs python regex discrepancy
I am reading a book and they provide an example of how to match a given string with regular expressions. Here is their example: b*(abb*)*(a|∊) - Strings of a's and b's with no consecutive a's. Now I've tried converting it to python like so: >> p = re.compile(r'b*(abb*)*(a|)') # OR >> p = re.compile(r'b*(abb*)*(a|\b)') # BUT it still doesn't work >>> p.match('aa') <_sre.SRE_Match object at 0x7fd9ad028c68> My question is two-fold: What is the equivalent of epsilon in python to make the above example work? Can someone explain to me why theoretical or standard way of doing regular expressions does not work in python? Might it have something to do with the longest vs shortest matching? Clarification: For people asking what standard regex is - it is the formal language theory standard: http://en.wikipedia.org/wiki/Regular_expression#Formal_language_theory
[ "Actually, the example works just fine ... to a small details. I would write:\n>>> p = re.compile('b*(abb*)*a?')\n>>> m = p.match('aa')\n>>> print m.group(0)\n'a'\n>>> m = p.match('abbabbabababbabbbbbaaaaa')\n>>> print m.group(0)\nabbabbabababbabbbbba\n\nNote that the group 0 returns the part of the string matched by the regular expression.\nAs you can see, the expression matches a succession of a and b without repetition of a. If indeed, you want to check the whole string, you need to changed slightly:\n>>> p = re.compile('^b*(abb*)*a?$')\n>>> m = p.match('aa')\n>>> print m\nNone\n\nthe ^ and $ force recognition of the beginning and end of the string.\nAt last, you can combine both methods by using the first regular expression, but testing at the end:\n>>> len(m.group(0)) == len('aa')\n\nAdded: For the second part of the OT, it seems to me there is no discrepancy between the standard regex and the python implementation. Of course, the notation is slightly different, and the python implementation suggest some extensions (as most other packages).\n", "Thanks for the answers. I feel each answer had part of the answer. Here is what I was looking for.\n\n? symbol is just a shorthand for (something|ε). Thus (a|ε) can be rewritten as a?. So the example becomes:\nb*(abb*)*a?\n\nIn python we would write:\np = re.compile(r'^b*(abb*)*a?$')\n\nThe reason straight translation of regular regular expression syntax into python (i.e. copy and paste) does not work is because python matches the shortest substring (if the symbols $ or ^ are absent) while the theoretical regular expressions match longest initial substring. \nSo for example if we had a string:\ns = 'aa'\n\nOur textbook regex b*(abb*)*a? would not match it because it has two a's. However if we copy it straight to python:\n>> p = re.compile(r'b*(abb*)*a?')\n>> bool(p.match(s))\nTrue\n\nThis is because our regex matches only the substring 'a' of our string 'aa'. \nIn order to tell python to do a match on the whole string we have to tell it where the beginning and the end of the string is, with the ^ and $ symbols respectively:\n>> p = re.compile(r'^b*(abb*)*a?$')\n>> bool(p.match(s))\nFalse\n\nNote that python regex match() matches at the beginning of the string, so it automatically assumes the ^ at the start. However the search() function does not, and thus we keep the ^.\n So for example:\n>> s = 'aa'\n>> p = re.compile(r'b*(abb*)*a?$')\n>> bool(p.match(s))\nFalse # Correct\n>> bool(p.search(s))\nTrue # Incorrect - search ignored the first 'a'\n\n\n", "1\n\nUse bool(p.match('aa')) to check if the regexp matches or not\np = re.compile('b*(abb*)*a?$')\n\\b matches border of string; place between \\w and \\W (word characters and non-word characters)\n\n2 \nRegexp is quite standard in python. Yet every language has some flavour of them, they are not 100% portable. There are minor differences which you're expected to lookup prior to using regexp in any specific language.\nAddition\n\\epsilon does not have special symbol in python. It is an empty character set. \nIn your example a|\\epsilon is equivalent to (a|) or just a?. After which $ is obligatory to match end of string.\n", "I'm not exactly sure how match works in python, but I think you might need to add ^....$ to your RE. RegExp matching usually matches sub-strings, and it finds the largest match, in the case of p.match('aa') that's \"a\" (probably the first one). ^...$ makes sure that you're matching the ENTIRE string, which is I believe what you want.\nTheoretical/standard reg exps assume that you're always matching the whole string, because you're using it to define a language of strings that match, not find a substring in an input string.\n", "You're matching because your regex matches any zero-width segment of any specimen text. You need to anchor your regex. Here's one way of doing it, using a zero-width lookahead assertion:\nre.compile(r'^(a(?!a)|b)*$')\n\n", "Your second re should be an appropriate replacement for epsilon, as best as I understand it, though I've never seen epsilon in a regex before. \nFor what it's worth, your pattern is matching 'a'. That is to say, it is matching:\n\nzero or more \"b\"s (choosing zero)\nzero or more \"(abb*)\"s (choosing zero)\none \"a\" or word ending (choosing an a).\n\nAs Jonathan Feinberg pointed out, if you want to ensure the whole string matches, you have to anchor the beginning ('^') and end ('$') of your regex. You should also use a raw string whenever constructing regexes in python: r'my regex'. That will prevent excessive backslash escaping confusion.\n", "the problem with your expression is that it matches the empty string, meaning that if you do:\n>>> p = re.compile('b*(abb*)*(a|)')\n>>> p.match('c').group(0)\n''\n\nand since re.match attempts to match the start of the string, you have to tell it to match it until the end of the string. just use $ for that\n>>> p = re.compile(r'b*(abb*)*(a|)$')\n>>> print p.match('c')\nNone\n>>> p.match('ababababab').group(0)\n'ababababab'\n\nps- you may have noted that i used r'pattern' instead of 'pattern' more on that here (first paragraphs)\n" ]
[ 5, 5, 3, 3, 1, 1, 1 ]
[]
[]
[ "python", "regex", "theory" ]
stackoverflow_0002049685_python_regex_theory.txt
Q: Sending stdout as response from CGI spawned program I'm trying to compose a .zip file in a CGI program and send that as the content response. I'm getting stuck in that whenever I spawn a program that prints to stdout, that somehow doesn't get accepted by Apache. It seems to be something to do with spawning a program that writes to stdout. The snippet below reproduces this problem. I always get the following error form Apache: malformed header from script. Bad header=hello world print ("Content-Type: text/html"); print (""); #print ("hello world"); <-----This works os.system("echo hello world"); <-----This doesn't work It works fine if I just print the string from my CGI script. If I run it with either statement from the command line, there's no difference in behaviour. Is there something special I need to do to get the stdout from a spawned program out as my respone? A: Try sys.stdout.flush() before calling external programs.
Sending stdout as response from CGI spawned program
I'm trying to compose a .zip file in a CGI program and send that as the content response. I'm getting stuck in that whenever I spawn a program that prints to stdout, that somehow doesn't get accepted by Apache. It seems to be something to do with spawning a program that writes to stdout. The snippet below reproduces this problem. I always get the following error form Apache: malformed header from script. Bad header=hello world print ("Content-Type: text/html"); print (""); #print ("hello world"); <-----This works os.system("echo hello world"); <-----This doesn't work It works fine if I just print the string from my CGI script. If I run it with either statement from the command line, there's no difference in behaviour. Is there something special I need to do to get the stdout from a spawned program out as my respone?
[ "Try sys.stdout.flush() before calling external programs.\n" ]
[ 1 ]
[]
[]
[ "apache", "cgi", "python" ]
stackoverflow_0002051030_apache_cgi_python.txt
Q: why is this an infinite loop in python? I can't seem to figure out why this is an infinite loop in python?? for i in range(n): j=1 while((i*j)<n): j+=1 shouldn't the outer loop go n times. incrementing j until its equal to n div i each time? A: i starts at 0, so the while condition stays always true; see the range docs for details. A: You can create a "trace" showing the state changes of the variables. n= 5; i= 0 n= 5; i= 0; j= 1 i*j < n -> 0 < 5: n= 5; i= 0; j= 2 i*j < n -> 0 < 5: n= 5; i= 0; j= 3 i*j < n -> 0 < 5: n= 5; i= 0; j= 4 i*j < n -> 0 < 5: n= 5; i= 0; j= 5 i*j < n -> 0 < 5: n= 5; i= 0; j= 6 etc. You can prove that your trace is correct by inserting print statements. When in doubt, print it out. A: i starts at zero, so the condition for the inner loop is always 0*j < n, which will always be true. A: Because the initial value of i is 0. A: The first value in i will be 0. 0 times anything is 0. A: because i is 0!! and i*j=0 A: range(n) starts at 0, not 1. 0 * j will always be less than n. A: On the first time through the outer loop, the inner loop becomes an infinite loop. It doesn't matter what happens after that. There's no "after infinity". A: i is 0 rewrite you loop like for i in range(1,n): j=1 while((i*j)<n): j+=1 using this version of the range function will create a range that starts at 1 instead of 0
why is this an infinite loop in python?
I can't seem to figure out why this is an infinite loop in python?? for i in range(n): j=1 while((i*j)<n): j+=1 shouldn't the outer loop go n times. incrementing j until its equal to n div i each time?
[ "i starts at 0, so the while condition stays always true; see the range docs for details.\n", "You can create a \"trace\" showing the state changes of the variables.\n\nn= 5; i= 0\nn= 5; i= 0; j= 1\ni*j < n -> 0 < 5: n= 5; i= 0; j= 2\ni*j < n -> 0 < 5: n= 5; i= 0; j= 3\ni*j < n -> 0 < 5: n= 5; i= 0; j= 4\ni*j < n -> 0 < 5: n= 5; i= 0; j= 5\ni*j < n -> 0 < 5: n= 5; i= 0; j= 6\n\netc.\nYou can prove that your trace is correct by inserting print statements.\nWhen in doubt, print it out.\n", "i starts at zero, so the condition for the inner loop is always 0*j < n, which will always be true.\n", "Because the initial value of i is 0.\n", "The first value in i will be 0. 0 times anything is 0.\n", "because i is 0!! and i*j=0\n", "range(n) starts at 0, not 1. 0 * j will always be less than n.\n", "On the first time through the outer loop, the inner loop becomes an infinite loop.\nIt doesn't matter what happens after that. There's no \"after infinity\".\n", "i is 0 rewrite you loop like\nfor i in range(1,n):\nj=1\nwhile((i*j)<n):\n j+=1\n\nusing this version of the range function will create a range that starts at 1 instead of 0\n" ]
[ 36, 16, 12, 7, 4, 2, 2, 1, 0 ]
[]
[]
[ "infinite_loop", "loops", "python" ]
stackoverflow_0002051034_infinite_loop_loops_python.txt
Q: Get HTML links within a specified using minidom I'm looking to use Python and xml.dom.minidom to get a list of links within a particular <table> specified by the table id. Based on some excellent advice, I'm trying to use the DOM instead of pattern matching. import urllib import xml.dom.minidom url = 'http://www.batstrading.com/market_data/shortsales' page = xml.dom.minidom.parse(urllib.urlopen(url)) I can get all the links by the tag name page.getElementsByTagName('a'), but I cannot limit the links returned by those only contained within the table with ID "monthly-short-sale". Using getElementById returns None. Is this because the "monthly-short-sale" ID is not defined within the DTD? If so, what would be the best way to extract this information? Here is the code that I'm currently using, which works, but sins against god: import urllib import xml.dom.minidom import datetime url = 'http://www.batstrading.com/market_data/shortsales' def getDownloadLink(alink, prefix = 'BATSsh'): """return (datetime.date, link) for the provided link if the link target starts with the data file prefix""" n = len(prefix) href = alink.getAttribute('href') if href.startswith(prefix) and (len(href) == 25): year = int(href[n:n+4]) month = int(href[n+4:n+6]) day = int(href[n+6:n+8]) date = datetime.date(year, month, day) return (date, url + '/' + href) page = xml.dom.minidom.parse(urllib.urlopen(url)) link = (getDownloadLink(a) for a in page.getElementsByTagName('a')) link = dict(i for i in link if i is not None) A: The problem is that minidom is a non-external-entity-reading XML parser. That means it doesn't even look at the DTD, so it doesn't know that in HTML the attribute with the name id corresponds to an ID schema type. A further consequence of this is that minidom won't know about the HTML-specific entities like &eacute; that are defined in the XHTML doctype, so you may lose text that way. If you don't care about this, you can continue using minidom and using an alternative way to get at the table, involving getElementsByTagName and checking element.id manually. (You could hack up your own getElementById function to do it the slow way.) Or you could use an XML parser that does allow external entities such as pxdom. However this means the parser will have to fetch and parse the DTD from W3 each time, which will be unpleasantly slow. Or you could go for an HTML parser, which has the HTML entities and ID-nesses built in, such as BeautifulSoup. This might be a better idea when you are dealing with real-world HTML pages served as text/html, which though they may claim to be XHTML often includes naughty bits that aren't well-formed. A: I think that you want to first find the TABLE element then call getElemenetByTagName on it. That should return all a elements that are children on the table element. Also, double check that your HTML is XHTML; minidom is meant to parse XML, not HTML.
Get HTML links within a specified using minidom
I'm looking to use Python and xml.dom.minidom to get a list of links within a particular <table> specified by the table id. Based on some excellent advice, I'm trying to use the DOM instead of pattern matching. import urllib import xml.dom.minidom url = 'http://www.batstrading.com/market_data/shortsales' page = xml.dom.minidom.parse(urllib.urlopen(url)) I can get all the links by the tag name page.getElementsByTagName('a'), but I cannot limit the links returned by those only contained within the table with ID "monthly-short-sale". Using getElementById returns None. Is this because the "monthly-short-sale" ID is not defined within the DTD? If so, what would be the best way to extract this information? Here is the code that I'm currently using, which works, but sins against god: import urllib import xml.dom.minidom import datetime url = 'http://www.batstrading.com/market_data/shortsales' def getDownloadLink(alink, prefix = 'BATSsh'): """return (datetime.date, link) for the provided link if the link target starts with the data file prefix""" n = len(prefix) href = alink.getAttribute('href') if href.startswith(prefix) and (len(href) == 25): year = int(href[n:n+4]) month = int(href[n+4:n+6]) day = int(href[n+6:n+8]) date = datetime.date(year, month, day) return (date, url + '/' + href) page = xml.dom.minidom.parse(urllib.urlopen(url)) link = (getDownloadLink(a) for a in page.getElementsByTagName('a')) link = dict(i for i in link if i is not None)
[ "The problem is that minidom is a non-external-entity-reading XML parser. That means it doesn't even look at the DTD, so it doesn't know that in HTML the attribute with the name id corresponds to an ID schema type.\nA further consequence of this is that minidom won't know about the HTML-specific entities like &eacute; that are defined in the XHTML doctype, so you may lose text that way.\nIf you don't care about this, you can continue using minidom and using an alternative way to get at the table, involving getElementsByTagName and checking element.id manually. (You could hack up your own getElementById function to do it the slow way.)\nOr you could use an XML parser that does allow external entities such as pxdom. However this means the parser will have to fetch and parse the DTD from W3 each time, which will be unpleasantly slow.\nOr you could go for an HTML parser, which has the HTML entities and ID-nesses built in, such as BeautifulSoup. This might be a better idea when you are dealing with real-world HTML pages served as text/html, which though they may claim to be XHTML often includes naughty bits that aren't well-formed.\n", "I think that you want to first find the TABLE element then call getElemenetByTagName on it. That should return all a elements that are children on the table element. Also, double check that your HTML is XHTML; minidom is meant to parse XML, not HTML.\n" ]
[ 4, 0 ]
[]
[]
[ "minidom", "python" ]
stackoverflow_0002051270_minidom_python.txt
Q: Accessing samba shares with gio in python I am trying to make a simple command line client for accessing shares via the Python bindings of gio (yes, the main requirement is to use gio). I can see that comparing with it's predecessor gnome-vfs, it provides some means to do authentication stuff (subclassing MountOperation), and even some methods which are quite specific to samba shares, like set_domain(). But I'm stuck with this code: import gio fh = gio.File("smb://server_name/") If that server needs authentication, I suppose that a call to fh.mount_enclosing_volume() is needed, as this methods takes a MountOperation as a parameter. The problem is that calling this methods does nothing, and the logical fh.enumerate_children() (to list the available shares) that comes next fails. Anybody could provide a working example of how this would be done with gio ? A: The following appears to be the minimum code needed to mount a volume: def mount(f): op = gio.MountOperation() op.connect('ask-password', ask_password_cb) f.mount_enclosing_volume(op, mount_done_cb) def ask_password_cb(op, message, default_user, default_domain, flags): op.set_username(USERNAME) op.set_domain(DOMAIN) op.set_password(PASSWORD) op.reply(gio.MOUNT_OPERATION_HANDLED) def mount_done_cb(obj, res): obj.mount_enclosing_volume_finish(res) (Derived from gvfs-mount.) In addition, you may need a glib.MainLoop running because GIO mount functions are asynchronous. See the gvfs-mount source code for details.
Accessing samba shares with gio in python
I am trying to make a simple command line client for accessing shares via the Python bindings of gio (yes, the main requirement is to use gio). I can see that comparing with it's predecessor gnome-vfs, it provides some means to do authentication stuff (subclassing MountOperation), and even some methods which are quite specific to samba shares, like set_domain(). But I'm stuck with this code: import gio fh = gio.File("smb://server_name/") If that server needs authentication, I suppose that a call to fh.mount_enclosing_volume() is needed, as this methods takes a MountOperation as a parameter. The problem is that calling this methods does nothing, and the logical fh.enumerate_children() (to list the available shares) that comes next fails. Anybody could provide a working example of how this would be done with gio ?
[ "The following appears to be the minimum code needed to mount a volume:\ndef mount(f):\n op = gio.MountOperation()\n op.connect('ask-password', ask_password_cb)\n f.mount_enclosing_volume(op, mount_done_cb)\n\ndef ask_password_cb(op, message, default_user, default_domain, flags):\n op.set_username(USERNAME)\n op.set_domain(DOMAIN)\n op.set_password(PASSWORD)\n op.reply(gio.MOUNT_OPERATION_HANDLED)\n\ndef mount_done_cb(obj, res):\n obj.mount_enclosing_volume_finish(res)\n\n(Derived from gvfs-mount.)\nIn addition, you may need a glib.MainLoop running because GIO mount functions are asynchronous. See the gvfs-mount source code for details.\n" ]
[ 6 ]
[]
[]
[ "authentication", "gio", "gnome", "python", "samba" ]
stackoverflow_0001991206_authentication_gio_gnome_python_samba.txt
Q: "Optional" backreferences in regular expression I have a regular expression with two groups that are OR'd and I'm wondering if it's possible to have a group be a back reference only if it matched? In all cases, I'm wanting to match spam.eggs.com Example: import re monitorName = re.compile(r"HQ01 : HTTP Service - [Ss][Rr][Vv]\d+\.\w+\.com:(\w+\.\w+\.(?:net|com|org))|(\w+\.\w+\.(?:net|com|org))") test = ["HQ01 : HTTP Service - spam.eggs.com", "HQ01 : HTTP Service - spam.eggs.com - DISABLED", "HQ01 : HTTP Service - srv04.example.com:spam.eggs.com", "HQ01 : HTTP Service - srv04.example.com:spam.eggs.com - DISABLED"] for t in test: m = monitorName.search(t) print m.groups() Produces: (None, 'spam.eggs.com') (None, 'spam.eggs.com') ('spam.eggs.com', None) ('spam.eggs.com', None) It'd be nice if my groups would only return my one matched group and not both. A: The | operator has early precedence so it applies to everything before it (from the beginning of your regex in this case) OR everything after it. In your regex, if there is no "srv04.example.com", it isn't checking if the string contains "HTTP Service"! Your two capturing groups are identical, so there's no point in having both. All you want is to have the srv*: part optional, right? Try this one: r"HQ01 : HTTP Service - (?:[Ss][Rr][Vv]\d+\.\w+\.com:)?(\w+\.\w+\.(?:net|com|org))" A: m = monitorName.search(t) g = m.groups() print g[0] or g[1] A: Use m.group(1) or m.group(2). A: I will rewrite the regular expression to be monitorName = re.compile(r"HQ01 : HTTP Service - (?:(?i)SRV\d+\.\w+\.com:)?(\w+\.\w+\.(?:net|com|org))") Produces ('spam.eggs.com',) ('spam.eggs.com',) ('spam.eggs.com',) ('spam.eggs.com',) You can make group optional by tailing with ?. A: Did you consider this? HQ01 : HTTP Service - (?:[Ss][Rr][Vv]\d+\.\w+\.com:)?(\w+\.\w+\.(?:net|com|org))
"Optional" backreferences in regular expression
I have a regular expression with two groups that are OR'd and I'm wondering if it's possible to have a group be a back reference only if it matched? In all cases, I'm wanting to match spam.eggs.com Example: import re monitorName = re.compile(r"HQ01 : HTTP Service - [Ss][Rr][Vv]\d+\.\w+\.com:(\w+\.\w+\.(?:net|com|org))|(\w+\.\w+\.(?:net|com|org))") test = ["HQ01 : HTTP Service - spam.eggs.com", "HQ01 : HTTP Service - spam.eggs.com - DISABLED", "HQ01 : HTTP Service - srv04.example.com:spam.eggs.com", "HQ01 : HTTP Service - srv04.example.com:spam.eggs.com - DISABLED"] for t in test: m = monitorName.search(t) print m.groups() Produces: (None, 'spam.eggs.com') (None, 'spam.eggs.com') ('spam.eggs.com', None) ('spam.eggs.com', None) It'd be nice if my groups would only return my one matched group and not both.
[ "The | operator has early precedence so it applies to everything before it (from the beginning of your regex in this case) OR everything after it. In your regex, if there is no \"srv04.example.com\", it isn't checking if the string contains \"HTTP Service\"!\nYour two capturing groups are identical, so there's no point in having both. All you want is to have the srv*: part optional, right?\nTry this one:\nr\"HQ01 : HTTP Service - (?:[Ss][Rr][Vv]\\d+\\.\\w+\\.com:)?(\\w+\\.\\w+\\.(?:net|com|org))\"\n\n", "m = monitorName.search(t)\ng = m.groups()\nprint g[0] or g[1]\n\n", "Use m.group(1) or m.group(2).\n", "I will rewrite the regular expression to be\nmonitorName = re.compile(r\"HQ01 : HTTP Service - (?:(?i)SRV\\d+\\.\\w+\\.com:)?(\\w+\\.\\w+\\.(?:net|com|org))\")\n\nProduces\n('spam.eggs.com',)\n('spam.eggs.com',)\n('spam.eggs.com',)\n('spam.eggs.com',)\n\nYou can make group optional by tailing with ?.\n", "Did you consider this?\nHQ01 : HTTP Service - (?:[Ss][Rr][Vv]\\d+\\.\\w+\\.com:)?(\\w+\\.\\w+\\.(?:net|com|org))\n\n" ]
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002051552_python_regex.txt
Q: django combine models.DecimalField with forms -> error: quantize result has too many digits for current context I want to combine a model decimal field with a forms choice field. The field in the model: sum = models.DecimalField(max_digits=2, decimal_places=2) The field in the form: sum = forms.ChoiceField(choices=WORK_HOUR_CHOICES, label='Sum Working Hours', required=True) The choices: WORK_HOUR_CHOICES = ( (0, '0'), (0.5, '0.5'), (1, '1'), (1.5, '1.5'), (2, '2'), (2.5, '2.5') ) But always when I want to store a value with a decimal place I get this error: quantize result has too many digits for current context When I save a 0 or 1 it works fine. What's wrong? A: It's just a guess, but I bet you need to put Decimals in there: WORK_HOUR_CHOICES = ( (Decimal("0"), '0'), (Decimal("0.5"), '0.5'), (Decimal("1"), '1'), (Decimal("1.5"), '1.5'), (Decimal("2"), '2'), (Decimal("2.5"), '2.5') ) You can't initialize a Decimal with a float constant, you have to use a string. >>> from decimal import Decimal >>> Decimal(1.5) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\software\Python25\lib\decimal.py", line 578, in __new__ "First convert the float to a string") TypeError: Cannot convert float to Decimal. First convert the float to a string >>> Decimal("1.5") Decimal("1.5")
django combine models.DecimalField with forms -> error: quantize result has too many digits for current context
I want to combine a model decimal field with a forms choice field. The field in the model: sum = models.DecimalField(max_digits=2, decimal_places=2) The field in the form: sum = forms.ChoiceField(choices=WORK_HOUR_CHOICES, label='Sum Working Hours', required=True) The choices: WORK_HOUR_CHOICES = ( (0, '0'), (0.5, '0.5'), (1, '1'), (1.5, '1.5'), (2, '2'), (2.5, '2.5') ) But always when I want to store a value with a decimal place I get this error: quantize result has too many digits for current context When I save a 0 or 1 it works fine. What's wrong?
[ "It's just a guess, but I bet you need to put Decimals in there: \nWORK_HOUR_CHOICES = (\n (Decimal(\"0\"), '0'),\n (Decimal(\"0.5\"), '0.5'),\n (Decimal(\"1\"), '1'),\n (Decimal(\"1.5\"), '1.5'),\n (Decimal(\"2\"), '2'),\n (Decimal(\"2.5\"), '2.5')\n)\n\nYou can't initialize a Decimal with a float constant, you have to use a string. \n>>> from decimal import Decimal\n>>> Decimal(1.5)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"C:\\software\\Python25\\lib\\decimal.py\", line 578, in __new__\n \"First convert the float to a string\")\nTypeError: Cannot convert float to Decimal. First convert the float to a string\n>>> Decimal(\"1.5\")\nDecimal(\"1.5\")\n\n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002051575_django_python.txt
Q: access to gnome configuration information using python Is there a standard way of accessing Gnome configuration information (i.e. ~/.gconf) using Python? Updated: please provide a short example. A: Python GConf, also check out packages like python-gconf and/or gnome-python-gconf in your distros package repo: /usr/share/doc/python-gconf/examples/ Or browse the svn at http://svn.gnome.org/viewvc/gnome-python/trunk/examples/gconf/ for the examples. On Fedora12 (my distro) it is called gnome-python2-gconf-2.28.0-1.fc12.x86_64.rpm, but it may be in a generic gnome-python2 package. An example of GConf key editing (background wallpaper) in Python: #! /usr/bin/python import gtk import gtk.glade import gconf class GConfExample: def __init__(self): self.client = gconf.client_get_default() def get_key(self, key): return client.get_string(key) def set_key(self, key, val): client.set_string(key, str(val)) Found http://therning.org/magnus/archives/57 , and I trimmed out the GTK stuff. Of course, this would make some good getitem and setitem usage to map for example: mygconf['/path/to/key']; Also some good information here about using the API. Of course, my example is poor, but illustrates the simplicity of the API. Here are more methods: foo = self.gconf_client.get_string("/path/to/my/config/data/foo") bar = self.gconf_client.get_int("/path/to/my/config/data/bar") baz = self.gconf_client.get_bool("/path/to/my/config/data/baz") And each get_* has an equivalent setter set_* in most cases.
access to gnome configuration information using python
Is there a standard way of accessing Gnome configuration information (i.e. ~/.gconf) using Python? Updated: please provide a short example.
[ "Python GConf, also check out packages like python-gconf and/or gnome-python-gconf in your distros package repo:\n\n/usr/share/doc/python-gconf/examples/\n\nOr browse the svn at http://svn.gnome.org/viewvc/gnome-python/trunk/examples/gconf/ for the examples.\nOn Fedora12 (my distro) it is called gnome-python2-gconf-2.28.0-1.fc12.x86_64.rpm, but it may be in a generic gnome-python2 package.\nAn example of GConf key editing (background wallpaper) in Python:\n#! /usr/bin/python\n\nimport gtk\nimport gtk.glade\nimport gconf\n\nclass GConfExample:\n def __init__(self):\n self.client = gconf.client_get_default()\n\n def get_key(self, key):\n return client.get_string(key)\n\n def set_key(self, key, val):\n client.set_string(key, str(val))\n\nFound http://therning.org/magnus/archives/57 , and I trimmed out the GTK stuff. Of course, this would make some good getitem and setitem usage to map for example:\nmygconf['/path/to/key'];\n\nAlso some good information here about using the API. Of course, my example is poor, but illustrates the simplicity of the API. Here are more methods:\nfoo = self.gconf_client.get_string(\"/path/to/my/config/data/foo\")\nbar = self.gconf_client.get_int(\"/path/to/my/config/data/bar\")\nbaz = self.gconf_client.get_bool(\"/path/to/my/config/data/baz\")\n\nAnd each get_* has an equivalent setter set_* in most cases.\n" ]
[ 10 ]
[]
[]
[ "gnome", "python" ]
stackoverflow_0002051905_gnome_python.txt
Q: PyQt4 Drag & Drop Qt4 has support for Drag & Drop actions and I've used them like in the tutorial. Now I want to be able to drag external elements (files) into the GUI form and perform actions based on that (like get the full path and copy it somewhere). I'm not sure whether this is a limitation like something Qt cannot do. Does someone know how you can do that with Qt? Simply drag a file into a GUI... Thanks, Marius A: Most file managers provide drag-and-drop data using the text/uri-list target. Regarding the linked tutorial, first you need to set the widget to accept dropping text/uri-list data, then you can retrieve the URIs by calling event.mimeData().urls(). The return value is a list of QUrl objects.
PyQt4 Drag & Drop
Qt4 has support for Drag & Drop actions and I've used them like in the tutorial. Now I want to be able to drag external elements (files) into the GUI form and perform actions based on that (like get the full path and copy it somewhere). I'm not sure whether this is a limitation like something Qt cannot do. Does someone know how you can do that with Qt? Simply drag a file into a GUI... Thanks, Marius
[ "Most file managers provide drag-and-drop data using the text/uri-list target.\nRegarding the linked tutorial, first you need to set the widget to accept dropping text/uri-list data, then you can retrieve the URIs by calling event.mimeData().urls(). The return value is a list of QUrl objects.\n" ]
[ 3 ]
[]
[]
[ "pyqt4", "python", "qt4" ]
stackoverflow_0002051488_pyqt4_python_qt4.txt
Q: How to use a Django include tag for a separate HTML template? I am trying to use the include Django template tag, and inside it I reference a template which handles the format of the form. When I reference this though inside my template it outputs each of the dynamic parts, each character per new line, it is really strange. For example here is a snippet of the output: <form action="/admin/events/create_submit/" method="post"> <div class="fieldWrapper"> : &lt; </div> <div class="fieldWrapper"> : l </div> <div class="fieldWrapper"> : i </div> <div class="fieldWrapper"> : &gt; </div> ... EXPECTED OUTPUT <form action="/admin/events/create_submit/" method="post"> <div class="fieldWrapper"> <li><label>field</label><input type="text" /></li> </div> ... I realise the markup on the li inside the div is incorrect but I am trying to understand why the html is being encoded and each character split into a new line inside the template div and prefixed with the colon ":" The template which I am trying to render is this: <form action="{{action}}" method="post"> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %} <p><input type="submit" value="Submit" /></p> </form> And I reference the include template like this: {% include "forms/form_template.html" %} Does anyone know or could help m as to why this would be causing each dynamic piece to output per character on each line? TIA Andrew A: spaceless tag Removes whitespace between HTML tags. This includes tab characters and newlines. A: form is probably a string rather than a Form object, and iterating over a string yields its individual characters.
How to use a Django include tag for a separate HTML template?
I am trying to use the include Django template tag, and inside it I reference a template which handles the format of the form. When I reference this though inside my template it outputs each of the dynamic parts, each character per new line, it is really strange. For example here is a snippet of the output: <form action="/admin/events/create_submit/" method="post"> <div class="fieldWrapper"> : &lt; </div> <div class="fieldWrapper"> : l </div> <div class="fieldWrapper"> : i </div> <div class="fieldWrapper"> : &gt; </div> ... EXPECTED OUTPUT <form action="/admin/events/create_submit/" method="post"> <div class="fieldWrapper"> <li><label>field</label><input type="text" /></li> </div> ... I realise the markup on the li inside the div is incorrect but I am trying to understand why the html is being encoded and each character split into a new line inside the template div and prefixed with the colon ":" The template which I am trying to render is this: <form action="{{action}}" method="post"> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %} <p><input type="submit" value="Submit" /></p> </form> And I reference the include template like this: {% include "forms/form_template.html" %} Does anyone know or could help m as to why this would be causing each dynamic piece to output per character on each line? TIA Andrew
[ "\nspaceless tag\nRemoves whitespace between HTML tags. This includes tab characters and newlines.\n\n", "form is probably a string rather than a Form object, and iterating over a string yields its individual characters.\n" ]
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002052114_django_python.txt
Q: creating 2 foreign keys that relate to one another class Product(models.Model): name = models.CharField(max_length = 127) description = models.TextField() code = models.CharField(max_length = 127) def __unicode__(self): return self.name class ProductLot(models.Model): product = models.ForeignKey(Product) code = models.ForeignKey(Product) lot_no = models.CharField(max_length = 30) location = models.CharField(max_length = 127) incoming = models.IntegerField() commited = models.IntegerField() available = models.IntegerField() reorder = models.IntegerField() created_date = models.DateField(auto_now_add=True) def __unicode__(self): return self.product.name + " - " + self.lot_no I want the code to correlate with product foreignkey so what you enter in for code correlates to the product. ok Im trying to get a drop down box for the codes that correspond to a product. For example, when In Django I use the ForeignKey for a dropdown box that uses the products in the database but they also have a corresponding code number that doesn't show up in the code box as a dropdown box. I was thinking an embedded class code? Sorry I'm new to this A: if you have two FK to one model you need to give different related names: product = models.ForeignKey(Product, related_name='lot_product') code = models.ForeignKey(Product, related_name='lot_code') related_name comes from django docs: ForeignKey.related_name The name to use for the relation from the related object back to this one. See the related objects documentation for a full explanation and example. A: Make code a property that looks at product: def getCode(self): return self.product and self.product.code def setCode(self, value): if self.product: self.product.code = value self.product.save() code = property(getCode, setCode) You won't be able to use it in a query, but that's what product__code is for. A: I think you should revise your models. Right now, each instance of ProductLot points exactly to two products. I'm not sure this is what you want. It really depends on what the relation between code and product is. Some thoughts: Every Product has a unique code (1:1 relation): Just omit the second ForeignKey named code in model ProductLot. Every Product might have multiple different codes but each code only points to exactly one Product (1:n relation): I'd add another model for your codes such as: class Product(models.Model): name = models.CharField(max_length = 127) ... class ProductCode(models.Model): product = models.ForeignKey(Product) ... class ProductLot(models.Model): product_code = models.ForeignKey(ProductCode) ... def correspondingProductName(self): return self.product_code.product.name
creating 2 foreign keys that relate to one another
class Product(models.Model): name = models.CharField(max_length = 127) description = models.TextField() code = models.CharField(max_length = 127) def __unicode__(self): return self.name class ProductLot(models.Model): product = models.ForeignKey(Product) code = models.ForeignKey(Product) lot_no = models.CharField(max_length = 30) location = models.CharField(max_length = 127) incoming = models.IntegerField() commited = models.IntegerField() available = models.IntegerField() reorder = models.IntegerField() created_date = models.DateField(auto_now_add=True) def __unicode__(self): return self.product.name + " - " + self.lot_no I want the code to correlate with product foreignkey so what you enter in for code correlates to the product. ok Im trying to get a drop down box for the codes that correspond to a product. For example, when In Django I use the ForeignKey for a dropdown box that uses the products in the database but they also have a corresponding code number that doesn't show up in the code box as a dropdown box. I was thinking an embedded class code? Sorry I'm new to this
[ "if you have two FK to one model you need to give different related names:\nproduct = models.ForeignKey(Product, related_name='lot_product')\ncode = models.ForeignKey(Product, related_name='lot_code')\n\nrelated_name comes from django docs:\n\nForeignKey.related_name\nThe name to use for the relation from the related object back to this one.\nSee the related objects documentation for a full explanation and example.\n\n", "Make code a property that looks at product:\ndef getCode(self):\n return self.product and self.product.code\n\ndef setCode(self, value):\n if self.product:\n self.product.code = value\n self.product.save()\n\ncode = property(getCode, setCode)\n\nYou won't be able to use it in a query, but that's what product__code is for.\n", "I think you should revise your models. Right now, each instance of ProductLot points exactly to two products. I'm not sure this is what you want.\nIt really depends on what the relation between code and product is. Some thoughts:\n\nEvery Product has a unique code (1:1 relation):\nJust omit the second ForeignKey named code in model ProductLot.\nEvery Product might have multiple different codes but each code only points to exactly one Product (1:n relation):\nI'd add another model for your codes such as:\nclass Product(models.Model):\n name = models.CharField(max_length = 127)\n ...\n\nclass ProductCode(models.Model):\n product = models.ForeignKey(Product)\n ...\n\nclass ProductLot(models.Model):\n product_code = models.ForeignKey(ProductCode)\n ...\n def correspondingProductName(self):\n return self.product_code.product.name\n\n\n" ]
[ 3, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002051895_django_python.txt
Q: Safely executing user-submitted python code on the server I am looking into starting a project which involves executing python code that the user enters via a HTML form. I know this can be potentially lethal (exec), but I have seen it done successfully in at least one instance. I sent an email off to the developers of the Python Challenge and I was told they are using a solution they came up with themselves, and they only let on that they are using "security features provided by the operating system" and that "the operating system [Linux] provides most of the security you need if you know how to use it." Would anyone know how a safe and secure way to go about doing this? I thought about spawning a new VM for every submission, but that would have way too much overhead and be pert-near impossible to implement efficiently. A: On a modern Linux in addition to chroot(2) you can restrict process further by using clone(2) instead of fork(2). There are several interesting clone(2) flags: CLONE_NEWIPC (new namespace for semaphores, shared memory, message queues) CLONE_NEWNET (new network namespace - nice one) CLONE_NEWNS (new set of mountpoints) CLONE_NEWPID (new set of process identifiers) CLONE_NEWUTS (new hostname, domainname, etc) Previously this functionality was implemented in OpenVZ and merged then upstream, so there is no need for patched kernel anymore. A: http://codepad.org/about has implemented such a system successfully (as a public code pasting/running service!) codepad.org is an online compiler/interpreter, and a simple collaboration tool. It's a pastebin that executes code for you. [...] How it works Code execution is handled by a supervisor based on geordi. The strategy is to run everything under ptrace, with many system calls disallowed or ignored. Compilers and final executables are both executed in a chroot jail, with strict resource limits. The supervisor is written in Haskell. [...] When your app is remote code execution, you have to expect security problems. Rather than rely on just the chroot and ptrace supervisor, I've taken some additional precautions: The supervisor processes run on virtual machines, which are firewalled such that they are incapable of making outgoing connections. The machines that run the virtual machines are also heavily firewalled, and restored from their source images periodically. A: If you run the script as user nobody (on Linux), it can write practically nowhere and read no data that has its permissions set up properly. But it could still cause a DoS attack by, for example: filling up /tmp eating all RAM eating all CPU Furthermore, outside network connections can be opened, etcetera etcetera. You can probably lock all these down with kernel limits, but you are bound to forget something. So I think that a virtual machine with no access to the network or the real hard drive would be the only (reasonably) safe route. Perhaps the developers of the Python Challenge use KVM which is, in principle, "provided by the operating system". For efficiency, you could run all submissions in the same VM. That saves you much overhead, and in the worst-case scenario they only hamper each other, but not your server. A: Using chroot (Wikipedia) may be part of the solution, e.g. combined with ulimit and some other common (or custom) tools.
Safely executing user-submitted python code on the server
I am looking into starting a project which involves executing python code that the user enters via a HTML form. I know this can be potentially lethal (exec), but I have seen it done successfully in at least one instance. I sent an email off to the developers of the Python Challenge and I was told they are using a solution they came up with themselves, and they only let on that they are using "security features provided by the operating system" and that "the operating system [Linux] provides most of the security you need if you know how to use it." Would anyone know how a safe and secure way to go about doing this? I thought about spawning a new VM for every submission, but that would have way too much overhead and be pert-near impossible to implement efficiently.
[ "On a modern Linux in addition to chroot(2) you can restrict process further by using clone(2) instead of fork(2). There are several interesting clone(2) flags:\nCLONE_NEWIPC (new namespace for semaphores, shared memory, message queues)\nCLONE_NEWNET (new network namespace - nice one)\nCLONE_NEWNS (new set of mountpoints)\nCLONE_NEWPID (new set of process identifiers)\nCLONE_NEWUTS (new hostname, domainname, etc)\n\nPreviously this functionality was implemented in OpenVZ and merged then upstream, so there is no need for patched kernel anymore.\n", "http://codepad.org/about has implemented such a system successfully (as a public code pasting/running service!)\n\ncodepad.org is an online compiler/interpreter, and a simple collaboration tool. It's a pastebin that executes code for you. [...]\nHow it works\nCode execution is handled by a supervisor based on geordi. The strategy is to run everything under ptrace, with many system calls disallowed or ignored. Compilers and final executables are both executed in a chroot jail, with strict resource limits. The supervisor is written in Haskell.\n[...]\nWhen your app is remote code execution, you have to expect security problems. Rather than rely on just the chroot and ptrace supervisor, I've taken some additional precautions:\n\nThe supervisor processes run on virtual machines, which are firewalled such that they are incapable of making outgoing connections.\nThe machines that run the virtual machines are also heavily firewalled, and restored from their source images periodically.\n\n\n", "If you run the script as user nobody (on Linux), it can write practically nowhere and read no data that has its permissions set up properly. But it could still cause a DoS attack by, for example:\n\nfilling up /tmp\neating all RAM\neating all CPU\n\nFurthermore, outside network connections can be opened, etcetera etcetera. You can probably lock all these down with kernel limits, but you are bound to forget something.\nSo I think that a virtual machine with no access to the network or the real hard drive would be the only (reasonably) safe route. Perhaps the developers of the Python Challenge use KVM which is, in principle, \"provided by the operating system\".\nFor efficiency, you could run all submissions in the same VM. That saves you much overhead, and in the worst-case scenario they only hamper each other, but not your server.\n", "Using chroot (Wikipedia) may be part of the solution, e.g. combined with ulimit and some other common (or custom) tools.\n" ]
[ 3, 3, 2, 0 ]
[]
[]
[ "python", "user_input" ]
stackoverflow_0001737524_python_user_input.txt
Q: Updating the wx.gauge without while-loop Have been wondering about this for days now: I have a basic wxpython program like this: from MyModule import * class Form(wx.Panel): def __init__(self, parent, id): self.gauge = wx.Gauge(...) ... def ButtonClick(self, event): proc = LongProcess() while (LongProcess): self.gauge.SetValue(LongProcess.status) wx.Yield() which imports the MyModule.py: from threading import * class LongProcess(self): def __init__(self): Thread.__init__(self) self.start() def run(self): for i in range(100): Do_something() self.status = i This updates the gauge according to the value LongProcess.status, as expected. But the while-loop doesn't seem appropriate as the whole program uses 100% cpu load because it continuously checks the status (not surprising, tho). Is there any way to send the status back to the "mother program" without doing that millions of times per second? A: You can instantiate custom events from the non-GUI thread and wx.PostEvent them back to the GUI-thread. This is a thread-safe action. My use cases typically work like this: Start worker thread - Custom event 'Starting Action' Start processing Post events back updating progress 'Line 435 of 15000 is parsed' etc. Then I bind the custom event to update a dialog or textctrl/log or whatever. It's surprisingly easy to do. If you'd like I can post some sample code of a little test case I wrote a while back when I was figuring this stuff out. --Edit: Okay here's some code, first the threading example: #!usr/bin/env python import wx import threading import Queue import random import time TextEventType = wx.NewEventType() EVT_THREAD_TEXT_EVENT = wx.PyEventBinder(TextEventType, 1) global_queue = Queue.Queue() def threadStart(numthrds, queue, window): for i in range(numthrds): i = TextThread(queue, window) class TextThread(threading.Thread): def __init__(self, queue, output_window): threading.Thread.__init__(self) self.inqueue = queue self.output_window = output_window self.start() def run(self): word = self.inqueue.get() self.setName(word.upper()) wait = random.randrange(1, 10) time.sleep(wait) msg = 'Thread: ' + self.getName() + '--wait= ' + str(wait) + ' ' + word evt = NewTextEvent(TextEventType, -1) evt.setText(msg) wx.PostEvent(self.output_window, evt) #post EVT_THREAD_TEXT_EVENT #self.inqueue.task_done() #may not need this if non-blocking class NewTextEvent(wx.PyCommandEvent): def __init__(self, evtType, id): wx.PyCommandEvent.__init__(self, evtType, id) self.msg = '' def setText(self, text): self.msg = text def getText(self): return self.msg class TextFrame(wx.Frame): def __init__(self, parent, id, *args, **kwargs): wx.Frame.__init__(self, parent, id, *args, **kwargs) self.queue = Queue.Queue() framesizer = wx.BoxSizer(wx.VERTICAL) self.panel = ThreadPanel(self, wx.ID_ANY) framesizer.Add(self.panel, 0, wx.EXPAND) self.SetSizerAndFit(framesizer) self.Bind(EVT_THREAD_TEXT_EVENT, self.OnThreadText) def OnThreadText(self, evt): msg = evt.getText() self.panel.out_tc.AppendText(msg + '\n') class ThreadPanel(wx.Panel): def __init__(self, parent, id, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) vsizer = wx.BoxSizer(wx.VERTICAL) self.wordtc = wx.TextCtrl(self, id=wx.ID_ANY, value='', size=(350, -1)) self.inst_text = wx.StaticText(self, wx.ID_ANY, label='Enter a list of space-separated words') self.out_tc = wx.TextCtrl(self, id=wx.ID_ANY, size=(350, 300), value='', style=wx.TE_MULTILINE) self.start_button = wx.Button(self, wx.ID_ANY, label='Start Threads') vsizer.Add(self.inst_text, 0, wx.ALIGN_LEFT) vsizer.Add(self.wordtc, 0, wx.EXPAND) vsizer.Add(self.start_button) vsizer.Add((100,100)) vsizer.Add(self.out_tc, 0, wx.EXPAND) self.SetSizer(vsizer) self.Bind(wx.EVT_BUTTON, self.OnStartButton, self.start_button) def OnStartButton(self, evt): self.out_tc.Clear() text = self.wordtc.GetValue() self.wordtc.Clear() if not text.count(','): text = text.split(' ') num_thrds = len(text) for word in text: word = word.strip() self.GetParent().queue.put(word) threadStart(num_thrds, self.GetParent().queue, self.GetParent()) if __name__ == "__main__": app = wx.App() frame = TextFrame(None, wx.ID_ANY, 'Thread test') frame.Show() app.MainLoop() And a second, more simple example with custom events: #!usr/bin/env python import wx import random colorEventType = wx.NewEventType() EVT_COLOR_EVENT = wx.PyEventBinder(colorEventType, 1) class ButtonPanel(wx.Panel): def __init__(self, parent, *args, **kwargs): wx.Panel.__init__(self, parent, *args, **kwargs) vsizer = wx.BoxSizer(wx.VERTICAL) self.rstbutt = wx.Button(self, wx.ID_ANY, label='Restore') self.rstbutt.Disable() self.Bind(wx.EVT_BUTTON, self.OnButt, self.rstbutt) vsizer.Add(self.rstbutt, 0, wx.ALIGN_CENTER) vsizer.Add((500,150), 0) self.SetSizer(vsizer) def OnButt(self, evt): self.SetBackgroundColour(wx.NullColor) self.GetParent().Refresh() self.rstbutt.Disable() class ColorEvent(wx.PyCommandEvent): def __init__(self, evtType, id): wx.PyCommandEvent.__init__(self, evtType, id) self.color = None def SetMyColor(self, color): self.color = color def GetMyColor(self): return self.color class MainFrame(wx.Frame): def __init__(self, parent, *args, **kwargs): wx.Frame.__init__(self, parent, *args, **kwargs) framesizer = wx.BoxSizer(wx.VERTICAL) self.panel = ButtonPanel(self, wx.ID_ANY) framesizer.Add(self.panel, 1, wx.EXPAND) menubar = wx.MenuBar() filemenu = wx.Menu() menuquit = filemenu.Append(wx.ID_ANY, '&Quit') menubar.Append(filemenu, 'File') colormenu = wx.Menu() switch = colormenu.Append(wx.ID_ANY, '&Switch Color') menubar.Append(colormenu, '&Color') self.SetMenuBar(menubar) self.Bind(wx.EVT_MENU, self.OnQuit, menuquit) self.Bind(wx.EVT_MENU, self.OnColor, switch) self.Bind(EVT_COLOR_EVENT, self.ColorSwitch) self.SetSizerAndFit(framesizer) def OnQuit(self, evt): self.Close() def OnColor(self, evt): colevt = ColorEvent(colorEventType, -1) colors = ['red', 'green', 'blue', 'white', 'black', 'pink', (106, 90, 205), #slate blue (64, 224, 208), #turquoise ] choice = random.choice(colors) colevt.SetMyColor(choice) self.GetEventHandler().ProcessEvent(colevt) #evt.Skip() def ColorSwitch(self, evt): color = evt.GetMyColor() #print(color) self.panel.SetBackgroundColour(color) self.Refresh() self.panel.rstbutt.Enable() if __name__ == "__main__": app = wx.App() frame = MainFrame(None, wx.ID_ANY, title="Change Panel Color Custom Event") frame.Show(True) app.MainLoop()
Updating the wx.gauge without while-loop
Have been wondering about this for days now: I have a basic wxpython program like this: from MyModule import * class Form(wx.Panel): def __init__(self, parent, id): self.gauge = wx.Gauge(...) ... def ButtonClick(self, event): proc = LongProcess() while (LongProcess): self.gauge.SetValue(LongProcess.status) wx.Yield() which imports the MyModule.py: from threading import * class LongProcess(self): def __init__(self): Thread.__init__(self) self.start() def run(self): for i in range(100): Do_something() self.status = i This updates the gauge according to the value LongProcess.status, as expected. But the while-loop doesn't seem appropriate as the whole program uses 100% cpu load because it continuously checks the status (not surprising, tho). Is there any way to send the status back to the "mother program" without doing that millions of times per second?
[ "You can instantiate custom events from the non-GUI thread and wx.PostEvent them back to the GUI-thread. This is a thread-safe action. My use cases typically work like this:\n\nStart worker thread - Custom event 'Starting Action'\nStart processing\nPost events back updating progress 'Line 435 of 15000 is parsed'\netc.\n\nThen I bind the custom event to update a dialog or textctrl/log or whatever. It's surprisingly easy to do. If you'd like I can post some sample code of a little test case I wrote a while back when I was figuring this stuff out.\n--Edit:\nOkay here's some code, first the threading example:\n#!usr/bin/env python\n\nimport wx\nimport threading\nimport Queue\nimport random\nimport time\n\nTextEventType = wx.NewEventType()\nEVT_THREAD_TEXT_EVENT = wx.PyEventBinder(TextEventType, 1)\n\nglobal_queue = Queue.Queue()\n\ndef threadStart(numthrds, queue, window):\n for i in range(numthrds):\n i = TextThread(queue, window)\n\nclass TextThread(threading.Thread):\n def __init__(self, queue, output_window):\n threading.Thread.__init__(self)\n self.inqueue = queue\n self.output_window = output_window\n self.start()\n\n\n def run(self):\n word = self.inqueue.get()\n self.setName(word.upper())\n wait = random.randrange(1, 10)\n time.sleep(wait)\n msg = 'Thread: ' + self.getName() + '--wait= ' + str(wait) + ' ' + word\n evt = NewTextEvent(TextEventType, -1)\n evt.setText(msg)\n wx.PostEvent(self.output_window, evt) #post EVT_THREAD_TEXT_EVENT\n #self.inqueue.task_done() #may not need this if non-blocking\n\n\n\nclass NewTextEvent(wx.PyCommandEvent):\n def __init__(self, evtType, id):\n wx.PyCommandEvent.__init__(self, evtType, id)\n\n self.msg = ''\n\n def setText(self, text):\n self.msg = text\n\n def getText(self):\n return self.msg\n\nclass TextFrame(wx.Frame):\n def __init__(self, parent, id, *args, **kwargs):\n wx.Frame.__init__(self, parent, id, *args, **kwargs)\n self.queue = Queue.Queue()\n framesizer = wx.BoxSizer(wx.VERTICAL)\n self.panel = ThreadPanel(self, wx.ID_ANY)\n framesizer.Add(self.panel, 0, wx.EXPAND)\n self.SetSizerAndFit(framesizer)\n\n self.Bind(EVT_THREAD_TEXT_EVENT, self.OnThreadText)\n\n def OnThreadText(self, evt):\n msg = evt.getText()\n self.panel.out_tc.AppendText(msg + '\\n')\n\nclass ThreadPanel(wx.Panel):\n def __init__(self, parent, id, *args, **kwargs):\n wx.Panel.__init__(self, parent, *args, **kwargs)\n vsizer = wx.BoxSizer(wx.VERTICAL)\n self.wordtc = wx.TextCtrl(self, id=wx.ID_ANY, value='', size=(350, -1))\n self.inst_text = wx.StaticText(self, wx.ID_ANY,\n label='Enter a list of space-separated words')\n self.out_tc = wx.TextCtrl(self, id=wx.ID_ANY, size=(350, 300), \n value='', style=wx.TE_MULTILINE)\n self.start_button = wx.Button(self, wx.ID_ANY, label='Start Threads')\n\n vsizer.Add(self.inst_text, 0, wx.ALIGN_LEFT)\n vsizer.Add(self.wordtc, 0, wx.EXPAND)\n vsizer.Add(self.start_button)\n vsizer.Add((100,100))\n vsizer.Add(self.out_tc, 0, wx.EXPAND)\n self.SetSizer(vsizer)\n self.Bind(wx.EVT_BUTTON, self.OnStartButton, self.start_button)\n\n def OnStartButton(self, evt):\n self.out_tc.Clear()\n text = self.wordtc.GetValue()\n self.wordtc.Clear()\n if not text.count(','):\n text = text.split(' ')\n num_thrds = len(text)\n for word in text:\n word = word.strip()\n self.GetParent().queue.put(word)\n threadStart(num_thrds, self.GetParent().queue, self.GetParent())\n\n\n\n\nif __name__ == \"__main__\":\n app = wx.App()\n frame = TextFrame(None, wx.ID_ANY, 'Thread test')\n frame.Show() \n app.MainLoop()\n\nAnd a second, more simple example with custom events:\n#!usr/bin/env python\n\nimport wx\nimport random\n\ncolorEventType = wx.NewEventType()\nEVT_COLOR_EVENT = wx.PyEventBinder(colorEventType, 1)\n\nclass ButtonPanel(wx.Panel):\n def __init__(self, parent, *args, **kwargs):\n wx.Panel.__init__(self, parent, *args, **kwargs)\n\n vsizer = wx.BoxSizer(wx.VERTICAL)\n self.rstbutt = wx.Button(self, wx.ID_ANY, label='Restore')\n self.rstbutt.Disable()\n self.Bind(wx.EVT_BUTTON, self.OnButt, self.rstbutt)\n vsizer.Add(self.rstbutt, 0, wx.ALIGN_CENTER)\n vsizer.Add((500,150), 0)\n self.SetSizer(vsizer)\n\n def OnButt(self, evt):\n self.SetBackgroundColour(wx.NullColor)\n self.GetParent().Refresh()\n self.rstbutt.Disable()\n\nclass ColorEvent(wx.PyCommandEvent):\n def __init__(self, evtType, id):\n wx.PyCommandEvent.__init__(self, evtType, id)\n self.color = None\n\n def SetMyColor(self, color):\n self.color = color\n\n def GetMyColor(self):\n return self.color\n\nclass MainFrame(wx.Frame):\n def __init__(self, parent, *args, **kwargs):\n wx.Frame.__init__(self, parent, *args, **kwargs)\n framesizer = wx.BoxSizer(wx.VERTICAL)\n self.panel = ButtonPanel(self, wx.ID_ANY)\n framesizer.Add(self.panel, 1, wx.EXPAND)\n\n menubar = wx.MenuBar()\n filemenu = wx.Menu()\n menuquit = filemenu.Append(wx.ID_ANY, '&Quit')\n menubar.Append(filemenu, 'File')\n colormenu = wx.Menu()\n switch = colormenu.Append(wx.ID_ANY, '&Switch Color')\n menubar.Append(colormenu, '&Color')\n self.SetMenuBar(menubar)\n\n self.Bind(wx.EVT_MENU, self.OnQuit, menuquit)\n self.Bind(wx.EVT_MENU, self.OnColor, switch)\n self.Bind(EVT_COLOR_EVENT, self.ColorSwitch)\n self.SetSizerAndFit(framesizer)\n\n def OnQuit(self, evt):\n self.Close()\n\n def OnColor(self, evt):\n colevt = ColorEvent(colorEventType, -1) \n colors = ['red', 'green', 'blue', 'white', 'black', 'pink', \n (106, 90, 205), #slate blue\n (64, 224, 208), #turquoise\n ]\n choice = random.choice(colors)\n colevt.SetMyColor(choice)\n self.GetEventHandler().ProcessEvent(colevt)\n #evt.Skip()\n\n def ColorSwitch(self, evt):\n color = evt.GetMyColor()\n #print(color)\n self.panel.SetBackgroundColour(color)\n self.Refresh()\n self.panel.rstbutt.Enable()\n\n\n\nif __name__ == \"__main__\":\n app = wx.App()\n frame = MainFrame(None, wx.ID_ANY, title=\"Change Panel Color Custom Event\")\n frame.Show(True)\n\n app.MainLoop()\n\n" ]
[ 8 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002052369_python_wxpython.txt
Q: Problem assigning input to list I know this is probably an easy question but after reviewing the documentation for python 2.6.4 I cannot seem to find out what is wrong. This is my file, in it's entirety. The problem I am having is in get_phone_number(). After asking for the amount of phone numbers, I get this error: Traceback (most recent call last): File "/home/charles/workspace/HelloWorld/hello.py", line 27, in <module> c.get_phone_number() File "/home/charles/workspace/HelloWorld/hello.py", line 17, in get_phone_number self.phone_number[phone_count] AttributeError: Contact instance has no attribute 'phone_number' It seems that I am able to define an attribute on the fly, but not if it is a list? Please help! class Name(): def get_name(self): self.first = raw_input("First Name?\n") self.middle = raw_input("Middle Name?\n") self.last = raw_input("Last Name?\n") pass class Address(): def get_address(self): self.street = raw_input("Street?\n") self.city = raw_input("City?\n") self.zip = raw_input("Zip Code?\n") pass class Phone_Number(): def get_phone_number(self): count = 0 phone_count = raw_input("How many phone numbers?\n") self.phone_number[phone_count] while count < (phone_count - 1): self.phone_number[phone_count] = raw_input("Phone Number: ") phone_count -= 1 pass class Contact(Name, Address, Phone_Number): pass c = Contact() c.get_name() c.get_address() c.get_phone_number() A: replace self.phone_number[phone_count] with self.phone_number = [] The first statement does nothing (actually, it tries to access the phone_count-th element of a list called phone_number in self, which does not exist, and hence the error). The second statement defines a new list called phone_number. A: Your code contains quite a few errors and is not Pythonic. Some points: you need to convert the first user input to an integer. You can use a for loop instead of a while loop. On Python 2.5 you can use xrange instead of range but for Python 3.0 use range. Use append to add an item to a list. class Phone_Number(): def get_phone_numbers(self): phone_count = int(raw_input("How many phone numbers?\n")) self.phone_numbers = [] for _ in range(phone_count): self.phone_numbers.append(raw_input("Phone Number: ")) p = Phone_Number() p.get_phone_numbers() for phone_number in p.phone_numbers: print phone_number A: You need to initialise self.phone_number def get_phone_number(self): count = 0 phone_count = raw_input("How many phone numbers?\n") self.phone_number = [] while count < (phone_count - 1): self.phone_number.append (raw_input("Phone Number: ")) phone_count -= 1
Problem assigning input to list
I know this is probably an easy question but after reviewing the documentation for python 2.6.4 I cannot seem to find out what is wrong. This is my file, in it's entirety. The problem I am having is in get_phone_number(). After asking for the amount of phone numbers, I get this error: Traceback (most recent call last): File "/home/charles/workspace/HelloWorld/hello.py", line 27, in <module> c.get_phone_number() File "/home/charles/workspace/HelloWorld/hello.py", line 17, in get_phone_number self.phone_number[phone_count] AttributeError: Contact instance has no attribute 'phone_number' It seems that I am able to define an attribute on the fly, but not if it is a list? Please help! class Name(): def get_name(self): self.first = raw_input("First Name?\n") self.middle = raw_input("Middle Name?\n") self.last = raw_input("Last Name?\n") pass class Address(): def get_address(self): self.street = raw_input("Street?\n") self.city = raw_input("City?\n") self.zip = raw_input("Zip Code?\n") pass class Phone_Number(): def get_phone_number(self): count = 0 phone_count = raw_input("How many phone numbers?\n") self.phone_number[phone_count] while count < (phone_count - 1): self.phone_number[phone_count] = raw_input("Phone Number: ") phone_count -= 1 pass class Contact(Name, Address, Phone_Number): pass c = Contact() c.get_name() c.get_address() c.get_phone_number()
[ "replace \nself.phone_number[phone_count]\n\nwith\nself.phone_number = []\n\nThe first statement does nothing (actually, it tries to access the phone_count-th element of a list called phone_number in self, which does not exist, and hence the error).\nThe second statement defines a new list called phone_number.\n", "Your code contains quite a few errors and is not Pythonic. Some points: you need to convert the first user input to an integer. You can use a for loop instead of a while loop. On Python 2.5 you can use xrange instead of range but for Python 3.0 use range. Use append to add an item to a list.\nclass Phone_Number():\n def get_phone_numbers(self):\n phone_count = int(raw_input(\"How many phone numbers?\\n\"))\n self.phone_numbers = []\n for _ in range(phone_count):\n self.phone_numbers.append(raw_input(\"Phone Number: \"))\n\np = Phone_Number()\np.get_phone_numbers()\nfor phone_number in p.phone_numbers:\n print phone_number\n\n", "You need to initialise self.phone_number\n def get_phone_number(self):\n count = 0\n phone_count = raw_input(\"How many phone numbers?\\n\")\n self.phone_number = []\n while count < (phone_count - 1):\n self.phone_number.append (raw_input(\"Phone Number: \"))\n phone_count -= 1\n\n" ]
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002052452_python.txt
Q: How to submit a form with more than 1 submit button. Sending a POST to a website. (Python) I am creating a script using Python Mechanize that can login to a website and submit a form. However, this form has 3 submit buttons (Preview, Post, and Cancel). I'm used to only one button... This is the form: <TextControl(subject=Is this good for the holidays? Anyone know about the new tech?)> <IgnoreControl(threads=<None>)> <TextareaControl(message=Im new to technology stocks.)> <SelectControl(identity=[*annamae41g])> <RadioControl(E=[5, 4, *3, 2, 1, 0])> <SubmitControl(SubmitPreview=Preview Message) (readonly)> <SubmitControl(SubmitPost=Post Message) (readonly)> <SubmitControl(SubmitCancel=Cancel) (readonly)> <HiddenControl(action_btn=) (readonly)> <HiddenControl(_charset_=) (readonly)> <HiddenControl(.crumb=4DxnFEwMIGG) (readonly)> <HiddenControl(r=/Stocks_(A_to_Z)/Stocks_G) (readonly)> <HiddenControl(bn=25263) (readonly)> <HiddenControl(<None>=annamae41g) (readonly)>> And this is my code: br.open(newtopic_url) br.select_form(name="postmsg") br.form['subject'] = "Is this good for the holidays? Anyone know about the new tech?" br.form['message'] = "Im new to technology stocks." br.form['E'] = ['3'] br.form['identity'] = ['annamae41g'] print br.form br.submit() If I run this script...it won't work. Nothing happens. I am assuming since it has 3 submit buttons in the form? Or is it another issue? A: I had the same problem as you. A form with two submit buttons, first was preview, second was submit. At first, mechanize was using only the first button, I could see the server answer using response = browser.submit() print response.read() I put the submit button name as a parameter to the mechanize submit function, and it worked! response = browser.submit("submit") Test it, it should work for you too! A: problem solved. Do not use python mechanize. It won't let you send other post data. For some reason, the post data currently in the question is NOT sufficient. There are other stuff that needs to be sent to the server. Therefore, you must use the regular opener/cookiejar method to send all the data through. I got the additional data (besides subject, message, E, identity) from Firebug (looking at the NET)
How to submit a form with more than 1 submit button. Sending a POST to a website. (Python)
I am creating a script using Python Mechanize that can login to a website and submit a form. However, this form has 3 submit buttons (Preview, Post, and Cancel). I'm used to only one button... This is the form: <TextControl(subject=Is this good for the holidays? Anyone know about the new tech?)> <IgnoreControl(threads=<None>)> <TextareaControl(message=Im new to technology stocks.)> <SelectControl(identity=[*annamae41g])> <RadioControl(E=[5, 4, *3, 2, 1, 0])> <SubmitControl(SubmitPreview=Preview Message) (readonly)> <SubmitControl(SubmitPost=Post Message) (readonly)> <SubmitControl(SubmitCancel=Cancel) (readonly)> <HiddenControl(action_btn=) (readonly)> <HiddenControl(_charset_=) (readonly)> <HiddenControl(.crumb=4DxnFEwMIGG) (readonly)> <HiddenControl(r=/Stocks_(A_to_Z)/Stocks_G) (readonly)> <HiddenControl(bn=25263) (readonly)> <HiddenControl(<None>=annamae41g) (readonly)>> And this is my code: br.open(newtopic_url) br.select_form(name="postmsg") br.form['subject'] = "Is this good for the holidays? Anyone know about the new tech?" br.form['message'] = "Im new to technology stocks." br.form['E'] = ['3'] br.form['identity'] = ['annamae41g'] print br.form br.submit() If I run this script...it won't work. Nothing happens. I am assuming since it has 3 submit buttons in the form? Or is it another issue?
[ "I had the same problem as you.\nA form with two submit buttons, first was preview, second was submit.\nAt first, mechanize was using only the first button, I could see the server answer using\nresponse = browser.submit()\nprint response.read()\n\nI put the submit button name as a parameter to the mechanize submit function, and it worked!\nresponse = browser.submit(\"submit\")\n\nTest it, it should work for you too!\n", "problem solved.\nDo not use python mechanize. It won't let you send other post data.\nFor some reason, the post data currently in the question is NOT sufficient. There are other stuff that needs to be sent to the server.\nTherefore, you must use the regular opener/cookiejar method to send all the data through.\nI got the additional data (besides subject, message, E, identity) from Firebug (looking at the NET)\n" ]
[ 4, 0 ]
[]
[]
[ "http", "mechanize", "python", "url", "urllib2" ]
stackoverflow_0001830413_http_mechanize_python_url_urllib2.txt
Q: Python CGI script IOError Broken Pipe I have an old Python based web form that I am updating to use a GPG for encyption instead of a no longer supported python package. When call the script via the command line it works just fine, but via the web brower and CGI there is a error: IOError: [Errno 32] Broken pipe. This error occurs if I use the gnupg package or if I try to talk to gpg directly via subprocess. Versions: Python 2.4.1 gnupg 0.2.2 (python GPG wrapper) Apache/2.2.9 gpg 1.4.9 Here is a simplified script: #!/usr/bin/python import sys # send python tracebacks out to the web browser sys.stderr = sys.stdout import gnupg gpg = gnupg.GPG() gpgkey = 'np' message = 'Our secret message!' print "Content-type: text/html\r\n" print '''<html><head><title>Test GPG access via cgi</title> </head><body><pre>''' print 'message in the clear:' print message encrypted = str(gpg.encrypt(message, 'np')) print 'message encrypted:' print encrypted print '''</pre></body></html>'''sf When the the above script is called via the command line, it runs just fine but when called via CGI it generates the following errors: message in the clear: Our secret message! Traceback (most recent call last): File "/home/dkmaster/www/nickads/secure-cgi/gpgtest.py", line 23, in encrypted = str(gpg.encrypt(message, 'np')) File "/home/dkmaster/www/nickads/secure-cgi/gnupg.py", line 517, in encrypt return self.encrypt_file(StringIO(data), recipients, **kwargs) File "/home/dkmaster/www/nickads/secure-cgi/gnupg.py", line 467, in encrypt_file self._handle_io(args, file, result, passphrase=passphrase) File "/home/dkmaster/www/nickads/secure-cgi/gnupg.py", line 201, in _handle_io _copy_data(file, stdin) File "/home/dkmaster/www/nickads/secure-cgi/gnupg.py", line 75, in _copy_data outstream.write(data) IOError: [Errno 32] Broken pipe I also tried to talk to GPG directly via subprocess and not the gnupg module. #!/usr/bin/python import sys import subprocess sys.stderr = sys.stdout print "Content-type: text/html\r\n" print '''<html><head><title>Test subprocess via cgi</title> </head><body><pre>''' plain_text = 'the quick fox ' * 10 print plain_text gpgCommand = "/usr/bin/gpg --quiet -a -e -r 'np' " gpgProcess = subprocess.Popen( gpgCommand, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) encrypted_text = gpgProcess.communicate(plain_text)[0] print encrypted_text Again this works fine from the command line, but not via CGI which generates a similar error: Traceback (most recent call last): File "/home/dkmaster/www/nickads/secure-cgi/subprocesstest.py", line 20, in encrypted_text = gpgProcess.communicate(plain_text)[0] File "/usr/lib/python2.5/subprocess.py", line 670, in communicate return self._communicate(input) File "/usr/lib/python2.5/subprocess.py", line 1220, in _communicate bytes_written = self._write_no_intr(self.stdin.fileno(), buffer(input, input_offset, 512)) File "/usr/lib/python2.5/subprocess.py", line 999, in _write_no_intr return os.write(fd, s) OSError: [Errno 32] Broken pipe So how do I fix the pipes in CGI? A: I know my answer might come too late, but I recently had the same problem and I think I could solve it. GPG seems to output some stuff ("You need a passphrase" blabla) to the terminal regardless of stdout being redirected - don't ask me how :) However, the Broken Pipe seems to occur because gpg can't output these messages in a cgi environment (happens for me with uwsgi). It even prints them out if --quiet was passed. It only seems to be really really quiet if you pass --batch additionally. A: Good question - I'm not sure that it's either a python-gnupg issue or even a gpg issue. It might be an issue with subprocess or cgi or some interaction between the two. What happens if you try this with a very minimal script which reads from stdin and writes the output to a file? Does that work? It's also worth enabling logging to see what that throws up, if anything. See the test_gnupg.py script for an example on how to do that.
Python CGI script IOError Broken Pipe
I have an old Python based web form that I am updating to use a GPG for encyption instead of a no longer supported python package. When call the script via the command line it works just fine, but via the web brower and CGI there is a error: IOError: [Errno 32] Broken pipe. This error occurs if I use the gnupg package or if I try to talk to gpg directly via subprocess. Versions: Python 2.4.1 gnupg 0.2.2 (python GPG wrapper) Apache/2.2.9 gpg 1.4.9 Here is a simplified script: #!/usr/bin/python import sys # send python tracebacks out to the web browser sys.stderr = sys.stdout import gnupg gpg = gnupg.GPG() gpgkey = 'np' message = 'Our secret message!' print "Content-type: text/html\r\n" print '''<html><head><title>Test GPG access via cgi</title> </head><body><pre>''' print 'message in the clear:' print message encrypted = str(gpg.encrypt(message, 'np')) print 'message encrypted:' print encrypted print '''</pre></body></html>'''sf When the the above script is called via the command line, it runs just fine but when called via CGI it generates the following errors: message in the clear: Our secret message! Traceback (most recent call last): File "/home/dkmaster/www/nickads/secure-cgi/gpgtest.py", line 23, in encrypted = str(gpg.encrypt(message, 'np')) File "/home/dkmaster/www/nickads/secure-cgi/gnupg.py", line 517, in encrypt return self.encrypt_file(StringIO(data), recipients, **kwargs) File "/home/dkmaster/www/nickads/secure-cgi/gnupg.py", line 467, in encrypt_file self._handle_io(args, file, result, passphrase=passphrase) File "/home/dkmaster/www/nickads/secure-cgi/gnupg.py", line 201, in _handle_io _copy_data(file, stdin) File "/home/dkmaster/www/nickads/secure-cgi/gnupg.py", line 75, in _copy_data outstream.write(data) IOError: [Errno 32] Broken pipe I also tried to talk to GPG directly via subprocess and not the gnupg module. #!/usr/bin/python import sys import subprocess sys.stderr = sys.stdout print "Content-type: text/html\r\n" print '''<html><head><title>Test subprocess via cgi</title> </head><body><pre>''' plain_text = 'the quick fox ' * 10 print plain_text gpgCommand = "/usr/bin/gpg --quiet -a -e -r 'np' " gpgProcess = subprocess.Popen( gpgCommand, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) encrypted_text = gpgProcess.communicate(plain_text)[0] print encrypted_text Again this works fine from the command line, but not via CGI which generates a similar error: Traceback (most recent call last): File "/home/dkmaster/www/nickads/secure-cgi/subprocesstest.py", line 20, in encrypted_text = gpgProcess.communicate(plain_text)[0] File "/usr/lib/python2.5/subprocess.py", line 670, in communicate return self._communicate(input) File "/usr/lib/python2.5/subprocess.py", line 1220, in _communicate bytes_written = self._write_no_intr(self.stdin.fileno(), buffer(input, input_offset, 512)) File "/usr/lib/python2.5/subprocess.py", line 999, in _write_no_intr return os.write(fd, s) OSError: [Errno 32] Broken pipe So how do I fix the pipes in CGI?
[ "I know my answer might come too late, but I recently had the same problem and I think I could solve it.\nGPG seems to output some stuff (\"You need a passphrase\" blabla) to the terminal regardless of stdout being redirected - don't ask me how :)\nHowever, the Broken Pipe seems to occur because gpg can't output these messages in a cgi environment (happens for me with uwsgi). It even prints them out if --quiet was passed. It only seems to be really really quiet if you pass --batch additionally.\n", "Good question - I'm not sure that it's either a python-gnupg issue or even a gpg issue. It might be an issue with subprocess or cgi or some interaction between the two. What happens if you try this with a very minimal script which reads from stdin and writes the output to a file? Does that work?\nIt's also worth enabling logging to see what that throws up, if anything. See the test_gnupg.py script for an example on how to do that.\n" ]
[ 2, 0 ]
[]
[]
[ "cgi", "gnupg", "python" ]
stackoverflow_0001798311_cgi_gnupg_python.txt
Q: Opening different windows in wxPython using strings from a list I have a list of file locations stored as strings. I want to be able to open a separate window for all of the different strings. What would be the best way to do that? Essentially, You click a button, the strings are constructed and they are left in a list. When I was prototyping, I built a small program to display the contents of one static file. It works, but the location is static.I want to add to the clicked button function a program that would iterate over the list and open each one of the contents in a new window. Right now the list is constructed and the window opens with the contents, but I am not sure how to combine the two. As always, any help much appreciated. A: for s in mystrings: open_window_for_string(s) I'm sure you can supply a definition for open_window_for_string if you know how to open a window with the contents of a file... Also, it doesn't actually have to be a function of one argument, of course, define it to accept whatever additional arguments are necessary. Or use whatever expression will open the kind of window you'd like to use without wrapping it up in a function. In fact, just take the code you use to display your static file, replace the filename with a variable -- called filename, perhaps -- then use a for loop to iterate over your list of strings. Simple!
Opening different windows in wxPython using strings from a list
I have a list of file locations stored as strings. I want to be able to open a separate window for all of the different strings. What would be the best way to do that? Essentially, You click a button, the strings are constructed and they are left in a list. When I was prototyping, I built a small program to display the contents of one static file. It works, but the location is static.I want to add to the clicked button function a program that would iterate over the list and open each one of the contents in a new window. Right now the list is constructed and the window opens with the contents, but I am not sure how to combine the two. As always, any help much appreciated.
[ "for s in mystrings:\n open_window_for_string(s)\n\nI'm sure you can supply a definition for open_window_for_string if you know how to open a window with the contents of a file...\nAlso, it doesn't actually have to be a function of one argument, of course, define it to accept whatever additional arguments are necessary. Or use whatever expression will open the kind of window you'd like to use without wrapping it up in a function.\nIn fact, just take the code you use to display your static file, replace the filename with a variable -- called filename, perhaps -- then use a for loop to iterate over your list of strings. Simple!\n" ]
[ 0 ]
[]
[]
[ "iteration", "list", "python", "wxpython" ]
stackoverflow_0002053009_iteration_list_python_wxpython.txt
Q: Regex replace (in Python) - a simpler way? Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like: "(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)" And then concatenate the start group with the new data for replace and then the end group. Is there a better method for this? A: >>> import re >>> s = "start foo end" >>> s = re.sub("foo", "replaced", s) >>> s 'start replaced end' >>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s) >>> s 'start can use a callable for the replaced text too end' >>> help(re.sub) Help on function sub in module re: sub(pattern, repl, string, count=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a callable, it's passed the match object and must return a replacement string to be used. A: Look in the Python re documentation for lookaheads (?=...) and lookbehinds (?<=...) -- I'm pretty sure they're what you want. They match strings, but do not "consume" the bits of the strings they match. A: The short version is that you cannot use variable-width patterns in lookbehinds using Python's re module. There is no way to change this: >>> import re >>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz") 'fooquuxbaz' >>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz") Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> re.sub("(?<=fo+)bar(?=baz)", "quux", string) File "C:\Development\Python25\lib\re.py", line 150, in sub return _compile(pattern, 0).sub(repl, string, count) File "C:\Development\Python25\lib\re.py", line 241, in _compile raise error, v # invalid expression error: look-behind requires fixed-width pattern This means that you'll need to work around it, the simplest solution being very similar to what you're doing now: >>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz") 'fooquuxbaz' >>> >>> # If you need to turn this into a callable function: >>> def replace(start, replace, end, replacement, search): return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search) This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one. A: I believe that the best idea is just to capture in a group whatever you want to replace, and then replace it by using the start and end properties of the captured group. regards Adrián #the pattern will contain the expression we want to replace as the first group pat = "word1\s(.*)\sword2" test = "word1 will never be a word2" repl = "replace" import re m = re.search(pat,test) if m and m.groups() > 0: line = test[:m.start(1)] + repl + test[m.end(1):] print line else: print "the pattern didn't capture any text" This will print: 'word1 will never be a word2' The group to be replaced could be located in any position of the string.
Regex replace (in Python) - a simpler way?
Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like: "(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)" And then concatenate the start group with the new data for replace and then the end group. Is there a better method for this?
[ ">>> import re\n>>> s = \"start foo end\"\n>>> s = re.sub(\"foo\", \"replaced\", s)\n>>> s\n'start replaced end'\n>>> s = re.sub(\"(?<= )(.+)(?= )\", lambda m: \"can use a callable for the %s text too\" % m.group(1), s)\n>>> s\n'start can use a callable for the replaced text too end'\n>>> help(re.sub)\nHelp on function sub in module re:\n\nsub(pattern, repl, string, count=0)\n Return the string obtained by replacing the leftmost\n non-overlapping occurrences of the pattern in string by the\n replacement repl. repl can be either a string or a callable;\n if a callable, it's passed the match object and must return\n a replacement string to be used.\n\n", "Look in the Python re documentation for lookaheads (?=...) and lookbehinds (?<=...) -- I'm pretty sure they're what you want. They match strings, but do not \"consume\" the bits of the strings they match.\n", "The short version is that you cannot use variable-width patterns in lookbehinds using Python's re module. There is no way to change this:\n>>> import re\n>>> re.sub(\"(?<=foo)bar(?=baz)\", \"quux\", \"foobarbaz\")\n'fooquuxbaz'\n>>> re.sub(\"(?<=fo+)bar(?=baz)\", \"quux\", \"foobarbaz\")\n\nTraceback (most recent call last):\n File \"<pyshell#2>\", line 1, in <module>\n re.sub(\"(?<=fo+)bar(?=baz)\", \"quux\", string)\n File \"C:\\Development\\Python25\\lib\\re.py\", line 150, in sub\n return _compile(pattern, 0).sub(repl, string, count)\n File \"C:\\Development\\Python25\\lib\\re.py\", line 241, in _compile\n raise error, v # invalid expression\nerror: look-behind requires fixed-width pattern\n\nThis means that you'll need to work around it, the simplest solution being very similar to what you're doing now:\n>>> re.sub(\"(fo+)bar(?=baz)\", \"\\\\1quux\", \"foobarbaz\")\n'fooquuxbaz'\n>>>\n>>> # If you need to turn this into a callable function:\n>>> def replace(start, replace, end, replacement, search):\n return re.sub(\"(\" + re.escape(start) + \")\" + re.escape(replace) + \"(?=\" + re.escape + \")\", \"\\\\1\" + re.escape(replacement), search)\n\nThis doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.\n", "I believe that the best idea is just to capture in a group whatever you want to replace, and then replace it by using the start and end properties of the captured group.\nregards\nAdrián\n#the pattern will contain the expression we want to replace as the first group\npat = \"word1\\s(.*)\\sword2\" \ntest = \"word1 will never be a word2\"\nrepl = \"replace\"\n\nimport re\nm = re.search(pat,test)\n\nif m and m.groups() > 0:\n line = test[:m.start(1)] + repl + test[m.end(1):]\n print line\nelse:\n print \"the pattern didn't capture any text\"\n\nThis will print:\n'word1 will never be a word2'\nThe group to be replaced could be located in any position of the string.\n" ]
[ 105, 18, 11, 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000490597_python_regex.txt
Q: Bash or Python for extracting blocks from text files I have a huge text file, which is structured as: SEPARATOR STRING1 (arbitrary number of lines) SEPARATOR ... SEPARATOR STRING2 (arbitrary number of lines) SEPARATOR SEPARATOR STRING3 (arbitrary number of lines) SEPARATOR .... What only changes between the different "blocks" of the file is the STRING and the content between the separator. I need to get a script in bash or python which given a STRING_i in the input, gives as output a file, which contains SEPARATOR STRING_i (number of lines for this string) SEPARATOR What is the best approach here to use bash or python? Another option? It must also be fast. Thanks A: In Python 2.6 or better: def doit(inf, ouf, thestring, separator='SEPARATOR\n'): thestring += '\n' for line in inf: # here we're always at the start-of-block separator assert line == separator blockid = next(inf) if blockid == thestring: # found block of interest, use enumerate to count its lines for c, line in enumerate(inf): if line == separator: break assert line == separator # emit results and terminate function ouf.writelines((separator, thestring, '(%d)' % c, separator)) inf.close() ouf.close() return # non-interesting block, just skip it for line in inf: if line == separator: break In older Python versions you can do almost the same, but change the line blockid = next(inf) to blockid = inf.next(). The assumptions here are that the input and output files are opened by the caller (which also passes in the interesting values of thestring, and optionally separator) but it's this function's job to close them (e.g. for maximum ease of use as a pipeline filter, with inf of sys.stdin and ouf of sys.stdout); easy to tweak if needed of course. Removing the asserts will speed it up microscopically, but I like their "sanity checking" role (and they may also help understand the logic of the code flow). Key to this approach is that a file is an iterator (of lines) and iterators can be advanced in multiple places (so we can have multiple for statements, or specific "advance the iterator" calls such as next(inf), and they cooperate properly). A: I would use Python and write something similar to this: import sys file = open("file", "r") counter = 0 count = False for line in file: if count: counter += 1 if count and SEPARATOR == line: break if not count and sys.argv[1] == line: count = True print SEPARATOR, sys.argv[1], counter, SEPARATOR file.close() A: If you want this to be fast, you need to avoid reading the entire file to find the block of data you need. read over the file once and store an index of a) byte offset for the start of each STRING_I and b) length (bytes) of block - distance to the next SEPARATOR in bytes. You can store this index in a separate file or in a 'header' of the current file for each STRING_I query - read in index if STRING_I in index: file.seek( start_byte_location ) file.read( length ) return parse_with_any_of_procedures_above # like @gruszczy's doit() but w/o loop don't go overboard with the index: use a dict of STRING_I -> ( location,length), and just simplejson / pickle it out to a file A: you can use (g)awk, which is a relatively fast tool to process files. read -p "Enter input: " input awk -vinput="$input" -vRS="SEPARATOR" '$0~input{ printf RT; print $0; printf RT }' file
Bash or Python for extracting blocks from text files
I have a huge text file, which is structured as: SEPARATOR STRING1 (arbitrary number of lines) SEPARATOR ... SEPARATOR STRING2 (arbitrary number of lines) SEPARATOR SEPARATOR STRING3 (arbitrary number of lines) SEPARATOR .... What only changes between the different "blocks" of the file is the STRING and the content between the separator. I need to get a script in bash or python which given a STRING_i in the input, gives as output a file, which contains SEPARATOR STRING_i (number of lines for this string) SEPARATOR What is the best approach here to use bash or python? Another option? It must also be fast. Thanks
[ "In Python 2.6 or better:\ndef doit(inf, ouf, thestring, separator='SEPARATOR\\n'):\n thestring += '\\n'\n for line in inf:\n # here we're always at the start-of-block separator\n assert line == separator\n blockid = next(inf)\n if blockid == thestring:\n # found block of interest, use enumerate to count its lines\n for c, line in enumerate(inf):\n if line == separator: break\n assert line == separator\n # emit results and terminate function\n ouf.writelines((separator, thestring, '(%d)' % c, separator))\n inf.close()\n ouf.close()\n return\n # non-interesting block, just skip it\n for line in inf:\n if line == separator: break\n\nIn older Python versions you can do almost the same, but change the line blockid = next(inf) to blockid = inf.next().\nThe assumptions here are that the input and output files are opened by the caller (which also passes in the interesting values of thestring, and optionally separator) but it's this function's job to close them (e.g. for maximum ease of use as a pipeline filter, with inf of sys.stdin and ouf of sys.stdout); easy to tweak if needed of course.\nRemoving the asserts will speed it up microscopically, but I like their \"sanity checking\" role (and they may also help understand the logic of the code flow).\nKey to this approach is that a file is an iterator (of lines) and iterators can be advanced in multiple places (so we can have multiple for statements, or specific \"advance the iterator\" calls such as next(inf), and they cooperate properly).\n", "I would use Python and write something similar to this:\nimport sys\n\nfile = open(\"file\", \"r\")\ncounter = 0\ncount = False\nfor line in file:\n if count:\n counter += 1\n if count and SEPARATOR == line:\n break\n if not count and sys.argv[1] == line:\n count = True\nprint SEPARATOR, sys.argv[1], counter, SEPARATOR\nfile.close()\n\n", "If you want this to be fast, you need to avoid reading the entire file to find the block of data you need.\n\nread over the file once and store an index of a) byte offset for the start of each STRING_I and b) length (bytes) of block - distance to the next SEPARATOR in bytes. You can store this index in a separate file or in a 'header' of the current file\nfor each STRING_I query - read in index\n\n\n if STRING_I in index:\n file.seek( start_byte_location )\n file.read( length )\n return parse_with_any_of_procedures_above # like @gruszczy's doit() but w/o loop\n\ndon't go overboard with the index: use a dict of STRING_I -> ( location,length), and just simplejson / pickle it out to a file\n", "you can use (g)awk, which is a relatively fast tool to process files.\nread -p \"Enter input: \" input\nawk -vinput=\"$input\" -vRS=\"SEPARATOR\" '$0~input{ printf RT; print $0; printf RT }' file\n\n" ]
[ 3, 0, 0, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002050411_bash_python.txt
Q: How do I determine if an element is in a list? thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}] How do I say: If "red" is in thelist and time does not equal 2 for that element (that's we just got from the list): A: Using any() to find out if there is an element satisfying the conditions: >>> any(item['color'] == 'red' and item['time'] != 2 for item in thelist) False A: def colorRedAndTimeNotEqualTo2(thelist): for i in thelist: if i["color"] == "red" and i["time"] != 2: return True return False print colorRedAndTimeNotEqualTo2([{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]) for i in thelist iterates through thelist, assigning the current element to i and doing the rest of the code in the block (for each value of i) Thanks for the catch, Benson. A: You can do most of the list manipulation in a list comprehension. Here's one that makes a list of times for all elements where the color is red. Then you can ask if 2 exists in those times. thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}] reds = ( x['time'] == 2 for x in thelist if x['color'] == red ) if False in reds: do_stuff() You can condense that even further by eliminating the variable "reds" like this: thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}] if False in ( x['time'] == 2 for x in thelist if x['color'] == red ): do_stuff() A: Well, there's nothing as elegant as "find" but you can use a list comprehension: matches = [x for x in thelist if x["color"] == "red" and x["time"] != 2] if len(matches): m = matches[0] # do something with m However, I find the [0] and len() tedious. I often use a for loop with an array slice, such as: matches = [x for x in thelist if x["color"] == "red" and x["time"] != 2] for m in matches[:1]: # do something with m A: list = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}] for i in list: if i['color'] == 'red' && i['time'] != 2: print i A: for val in thelist: if val['color'] == 'red' and val['time'] != 2: #do something here But it doesn't look like that's the right data structure to use.
How do I determine if an element is in a list?
thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}] How do I say: If "red" is in thelist and time does not equal 2 for that element (that's we just got from the list):
[ "Using any() to find out if there is an element satisfying the conditions:\n>>> any(item['color'] == 'red' and item['time'] != 2 for item in thelist)\nFalse\n\n", "def colorRedAndTimeNotEqualTo2(thelist):\n for i in thelist:\n if i[\"color\"] == \"red\" and i[\"time\"] != 2:\n return True\n return False\n\nprint colorRedAndTimeNotEqualTo2([{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}])\n\nfor i in thelist iterates through thelist, assigning the current element to i and doing the rest of the code in the block (for each value of i)\nThanks for the catch, Benson.\n", "You can do most of the list manipulation in a list comprehension. Here's one that makes a list of times for all elements where the color is red. Then you can ask if 2 exists in those times. \nthelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]\nreds = ( x['time'] == 2 for x in thelist if x['color'] == red )\nif False in reds:\n do_stuff()\n\nYou can condense that even further by eliminating the variable \"reds\" like this: \nthelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]\nif False in ( x['time'] == 2 for x in thelist if x['color'] == red ):\n do_stuff()\n\n", "Well, there's nothing as elegant as \"find\" but you can use a list comprehension:\nmatches = [x for x in thelist if x[\"color\"] == \"red\" and x[\"time\"] != 2]\nif len(matches):\n m = matches[0]\n # do something with m\n\nHowever, I find the [0] and len() tedious. I often use a for loop with an array slice, such as:\nmatches = [x for x in thelist if x[\"color\"] == \"red\" and x[\"time\"] != 2]\nfor m in matches[:1]:\n # do something with m\n\n", "list = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}]\nfor i in list:\n if i['color'] == 'red' && i['time'] != 2:\n print i\n\n", "for val in thelist:\n if val['color'] == 'red' and val['time'] != 2:\n #do something here\n\nBut it doesn't look like that's the right data structure to use.\n" ]
[ 13, 1, 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002053492_list_python.txt
Q: GQL with two tables Hello i am doing a very small application in google appengine and i use python. My problem is that i have two tables using de db.model ("clients" and "requests"). The table "client" has got the email and name fields and the table "requests" has got the email and issue fields. I want to do a query that returns for each request the email, issue and client name, if the email is the same in the two tables. Can anyone help, please? A: The app engine datastore does not support joins, so you will not be able to solve this problem with GQL. You can use two gets, one for client and one for request, or you can use a ReferenceProperty to establish a relationship between the two entities. If you need to model a one-to-many relationship, you can do it with a reference property. For your case, it would look something like this: class Client(db.Model): email = db.UserProperty() name = db.StringProperty() class Request(db.Model): client = db.ReferencePrpoerty(Client, collection_name='requests') issue = db.StringProperty() Any Client entity that has a Request associated with it will automatically get a property called requests which is a Query object that will return all Request entities that have a client field set to the particular Client entity you are dealing with. You might also want to make sure that the code that creates Request entities set each new entity to have the Client entity for the particular user as its ancestor. Keeping these associated items in the same entity group could be helpful for performance reasons and transactions. A: using this models: class Client(db.Model): email = db.StringProperty() name = db.StringProperty() class Request(db.Model): client = db.ReferenceProperty(Client, collection_name='requests') issue = db.StringProperty() With this code can query the data from modelos import Client,Request ctes=Client.all().filter("email =","somemail@mailbox.com.mx") for ct in ctes: allRequest4ThisUser=Request.all().filter("client =",ct) for req in allRequest4ThisUser: print req.issue
GQL with two tables
Hello i am doing a very small application in google appengine and i use python. My problem is that i have two tables using de db.model ("clients" and "requests"). The table "client" has got the email and name fields and the table "requests" has got the email and issue fields. I want to do a query that returns for each request the email, issue and client name, if the email is the same in the two tables. Can anyone help, please?
[ "The app engine datastore does not support joins, so you will not be able to solve this problem with GQL. You can use two gets, one for client and one for request, or you can use a ReferenceProperty to establish a relationship between the two entities.\nIf you need to model a one-to-many relationship, you can do it with a reference property. For your case, it would look something like this:\nclass Client(db.Model):\n email = db.UserProperty()\n name = db.StringProperty()\n\nclass Request(db.Model):\n client = db.ReferencePrpoerty(Client, collection_name='requests')\n issue = db.StringProperty()\n\nAny Client entity that has a Request associated with it will automatically get a property called requests which is a Query object that will return all Request entities that have a client field set to the particular Client entity you are dealing with.\nYou might also want to make sure that the code that creates Request entities set each new entity to have the Client entity for the particular user as its ancestor. Keeping these associated items in the same entity group could be helpful for performance reasons and transactions.\n", "using this models:\nclass Client(db.Model):\n email = db.StringProperty()\n name = db.StringProperty()\n\nclass Request(db.Model):\n client = db.ReferenceProperty(Client, collection_name='requests')\n issue = db.StringProperty() \n\nWith this code can query the data\nfrom modelos import Client,Request\n\nctes=Client.all().filter(\"email =\",\"somemail@mailbox.com.mx\")\n\nfor ct in ctes:\n allRequest4ThisUser=Request.all().filter(\"client =\",ct)\n for req in allRequest4ThisUser:\n print req.issue\n\n" ]
[ 3, 0 ]
[]
[]
[ "django", "google_app_engine", "gql", "python" ]
stackoverflow_0002002856_django_google_app_engine_gql_python.txt
Q: Can I ask for screenshot of some great personalized IDE for python? How to setup a Linux/Unix machine for python development? Which Linux/Unix version should I use? What IDE should be used? What development plugins should I have? What code style should would be THE BEST? All above, a great development machine for open source (python developers) development? Can i ask for screenshot of some great personalized IDE for Python? All platform users are invited. Please, do include the source/plugin/article how you made it. Thanks. A: Which Linux/Unix version should I use? Doesn't matter. They all work. Pick one that you're going to be successful with. What IDE should be used? Duplicate: What IDE to use for Python? What development plugins should I have? No clue from the vague question. What code style should would be THE BEST? "BEST" doesn't mean anything. Nor does "style". Everyone follows PEP-8, if that's helpful. All above, a great development machine for open source (python developers) development? Doesn't matter. They all work. A: Install any of the Linux distributions on your computer. If you have a preference, great. If not, try Ubuntu, Fedora, Debian. Any of them is pretty user and developer friendly too. IDE, well I don't use one. But you may try NetBeans with Python support or Eclipse (with PyDev). Code style- well, try and learn to be pythonic. It should come with practice and asking questions I think that should get you started! A: I use ubuntu 10.4 with geany and standard python code style. Basically that's all I need. I can install python packages both from ubuntu repos and using easy install (you can actually use it on all supported platforms). You don't need much for Python. It's small and flexible :-) A: Any of the new Linux distros should be fine, though Ubuntu is very user friendly when you are starting. You will also be happier starting with a simple editor like gedit / geany. But do make an attempt to learn emacs / vim. You will get the hang of one of those and it can really be life changing (I use emacs). As a great development machine, I recommend thinkpads for the excellent full size keyboards and linux friendly hardware. This image is a fairly representative screenshot of python development on emacs.
Can I ask for screenshot of some great personalized IDE for python?
How to setup a Linux/Unix machine for python development? Which Linux/Unix version should I use? What IDE should be used? What development plugins should I have? What code style should would be THE BEST? All above, a great development machine for open source (python developers) development? Can i ask for screenshot of some great personalized IDE for Python? All platform users are invited. Please, do include the source/plugin/article how you made it. Thanks.
[ "Which Linux/Unix version should I use? Doesn't matter. They all work. Pick one that you're going to be successful with.\nWhat IDE should be used? Duplicate: What IDE to use for Python?\nWhat development plugins should I have? No clue from the vague question.\nWhat code style should would be THE BEST? \"BEST\" doesn't mean anything. Nor does \"style\". Everyone follows PEP-8, if that's helpful. \nAll above, a great development machine for open source (python developers) development? Doesn't matter. They all work.\n", "\nInstall any of the Linux distributions on your computer. If you have a preference, great. If not, try Ubuntu, Fedora, Debian. Any of them is pretty user and developer friendly too. \nIDE, well I don't use one. But you may try NetBeans with Python support or Eclipse (with PyDev).\nCode style- well, try and learn to be pythonic. It should come with practice and asking questions\n\nI think that should get you started!\n", "I use ubuntu 10.4 with geany and standard python code style. Basically that's all I need. I can install python packages both from ubuntu repos and using easy install (you can actually use it on all supported platforms). You don't need much for Python. It's small and flexible :-)\n", "Any of the new Linux distros should be fine, though Ubuntu is very user friendly when you are starting. You will also be happier starting with a simple editor like gedit / geany. But do make an attempt to learn emacs / vim. You will get the hang of one of those and it can really be life changing (I use emacs). As a great development machine, I recommend thinkpads for the excellent full size keyboards and linux friendly hardware. This image is a fairly representative screenshot of python development on emacs.\n" ]
[ 5, 0, 0, 0 ]
[]
[]
[ "development_environment", "open_source", "python" ]
stackoverflow_0002048345_development_environment_open_source_python.txt
Q: Watch over another process (svn) I have a python script to download source code from a list of repositories, some of them are big. Sometimes, svn hangs in the middle of a check out. Is there a way to watch over svn process, and so I know it is hang or not? A: You can use PySVN, and register a callback for each "event" processes. PySVN can also poll a "cancel" callback. The first callback could start a timer, and if the timer expires, you can do tell the "cancel" callback to return False, thus cancelling the checkout. #!/usr/bin/python url = "svn://server/path/to/repo" path = "/path/to/local/wc" import pysvn import threading # Set to something reasonable SVN_TIMEOUT = 1000 svn_timer = None stop_svn = False def timer_expired(): # Too long since last SVN event, so do something sensible... print "SVN took too long!" global stop_svn stop_svn = True def svn_cancel(): return stop_svn def notify( event_dict ): global svn_timer if svn_timer: svn_timer.cancel() svn_timer = threading.Timer(SVN_TIMEOUT, timer_expired) svn_timer.start() svn_client = pysvn.Client() svn_client.callback_notify = notify svn_client.callback_cancel = svn_cancel svn_timer = threading.Timer(SVN_TIMEOUT, timer_expired) svn_timer.start() revision = svn_client.checkout(url,path) if svn_timer: svn_timer.cancel() A: You can keep polling the stdout of the svn process, and test how often you get new files. If you don't get a new file within x seconds, bounce the process. Launch svn using subprocess from within your master script, and poll stdout while waiting for the process to complete.
Watch over another process (svn)
I have a python script to download source code from a list of repositories, some of them are big. Sometimes, svn hangs in the middle of a check out. Is there a way to watch over svn process, and so I know it is hang or not?
[ "You can use PySVN, and register a callback for each \"event\" processes. PySVN can also poll a \"cancel\" callback. The first callback could start a timer, and if the timer expires, you can do tell the \"cancel\" callback to return False, thus cancelling the checkout.\n#!/usr/bin/python\n\nurl = \"svn://server/path/to/repo\"\npath = \"/path/to/local/wc\"\n\nimport pysvn\nimport threading\n\n# Set to something reasonable\nSVN_TIMEOUT = 1000\n\nsvn_timer = None\nstop_svn = False\n\ndef timer_expired():\n # Too long since last SVN event, so do something sensible...\n print \"SVN took too long!\"\n global stop_svn\n stop_svn = True\n\ndef svn_cancel():\n return stop_svn\n\ndef notify( event_dict ):\n global svn_timer\n if svn_timer:\n svn_timer.cancel()\n svn_timer = threading.Timer(SVN_TIMEOUT, timer_expired)\n svn_timer.start()\n\nsvn_client = pysvn.Client()\nsvn_client.callback_notify = notify\nsvn_client.callback_cancel = svn_cancel\n\nsvn_timer = threading.Timer(SVN_TIMEOUT, timer_expired)\nsvn_timer.start()\n\nrevision = svn_client.checkout(url,path)\n\nif svn_timer:\n svn_timer.cancel()\n\n", "You can keep polling the stdout of the svn process, and test how often you get new files. If you don't get a new file within x seconds, bounce the process.\nLaunch svn using subprocess from within your master script, and poll stdout while waiting for the process to complete.\n" ]
[ 1, 0 ]
[]
[]
[ "multiprocessing", "python", "svn" ]
stackoverflow_0002053857_multiprocessing_python_svn.txt
Q: How to get a flat XML so that external entities are merged to the top level I know this is a borderline case whether it really belongs to stackoverflow or superuser, but as it seems there are quite a few 'editing code' questions over here, I am posting it on SO. I have a pile of XML files that someone in their infinite wisdom have decided to explode to a multiple files using the tags, which in result makes debugging/editing them a huge P-i-t-A. Therefore I am looking for: A way in VIM to open them in a single buffer (preferably so that the changes are saved in correct external entity files), OR; A way to expand the files in VIM so that the external entities are read and replaced in the buffer, OR; an easy bash/sed/python way of doing this on a command line (or in .vimrc) The files included on top level might include new files and so on on who knows on how many levels so this needs to be recursive... Here's a mockup sample on what the top level file looks like: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE foobar PUBLIC "foobar:dtd" "foobar.dtd" [ <!ENTITY foo SYSTEM "foo.xml"> <!ENTITY bar SYSTEM "bar.xml"> ]> <foo> <params> &foo; </params> <bar> &bar; </bar> </foo> EDIT: The list is in order of preference - if no 1. or 2. solutions are available, the bounty goes for the best #3... EDIT 2: Looks like @Gaby 's answer works, but unfortunately only partially, unless I am doing something wrong - I'll write some sort of tool using his answer and post it here for improvements. Of course, a #1 or #2 solution would be appreciated... :) EDIT 3: Ok, the best non-Emacs -answer will get the bounty ;) Conclusion: Thanks to @hcayless I now have a working #2 solution, I added: autocmd BufReadPost,FileReadPost *.xml silent %!xmllint --noent - 2> /dev/null to my .vimrc and everything is hunky dory. A: If you have libxml2 installed, then xmllint will probably do this for you. Depending on your setup, you might need more params, but for your example, xmllint --noent foobar.xml will print your file to stdout with all entities resolved. Should be easy enough to wrap some bash scripting around it to do what you need. A: For the #3 option you can take a look at pixdom and look at the documentation at pxdom 1.5 A Python DOM implementation DOMConfiguration parameters The result of the parse operation depends on the parameters set on the LSParser.domConfig mapping. By default, in accordance with the DOM specification, all CDATA sections will be replaced with plain text nodes and all bound entity references will be replaced by the contents of the entity referred to. This includes external entity references and the external subset. it includes serializer to save the document to a file .. A: Are you looking for something like this? #!/opt/local/bin/python import sys if len(sys.argv) < 2: print "some files needed." sys.exit() final = """ <?xml version="1.0" encoding="ISO-8859-1"?> <nodes> """ for a in sys.argv[1:]: ca = a.replace(".xml","") final += "<" + ca + ">\n" infile = open(a) final += infile.read() final += "</" + ca + ">\n" final += "</nodes>\n" outfile = open("final.xml", "w") outfile.write(final) outfile.close()
How to get a flat XML so that external entities are merged to the top level
I know this is a borderline case whether it really belongs to stackoverflow or superuser, but as it seems there are quite a few 'editing code' questions over here, I am posting it on SO. I have a pile of XML files that someone in their infinite wisdom have decided to explode to a multiple files using the tags, which in result makes debugging/editing them a huge P-i-t-A. Therefore I am looking for: A way in VIM to open them in a single buffer (preferably so that the changes are saved in correct external entity files), OR; A way to expand the files in VIM so that the external entities are read and replaced in the buffer, OR; an easy bash/sed/python way of doing this on a command line (or in .vimrc) The files included on top level might include new files and so on on who knows on how many levels so this needs to be recursive... Here's a mockup sample on what the top level file looks like: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE foobar PUBLIC "foobar:dtd" "foobar.dtd" [ <!ENTITY foo SYSTEM "foo.xml"> <!ENTITY bar SYSTEM "bar.xml"> ]> <foo> <params> &foo; </params> <bar> &bar; </bar> </foo> EDIT: The list is in order of preference - if no 1. or 2. solutions are available, the bounty goes for the best #3... EDIT 2: Looks like @Gaby 's answer works, but unfortunately only partially, unless I am doing something wrong - I'll write some sort of tool using his answer and post it here for improvements. Of course, a #1 or #2 solution would be appreciated... :) EDIT 3: Ok, the best non-Emacs -answer will get the bounty ;) Conclusion: Thanks to @hcayless I now have a working #2 solution, I added: autocmd BufReadPost,FileReadPost *.xml silent %!xmllint --noent - 2> /dev/null to my .vimrc and everything is hunky dory.
[ "If you have libxml2 installed, then xmllint will probably do this for you. Depending on your setup, you might need more params, but for your example, \nxmllint --noent foobar.xml\n\nwill print your file to stdout with all entities resolved. Should be easy enough to wrap some bash scripting around it to do what you need.\n", "For the #3 option you can take a look at pixdom\nand look at the documentation at pxdom 1.5 A Python DOM implementation\n\nDOMConfiguration parameters\nThe result of the parse operation\ndepends on the parameters set on the\nLSParser.domConfig mapping. By\ndefault, in accordance with the DOM\nspecification, all CDATA sections will\nbe replaced with plain text nodes and\nall bound entity references will be\nreplaced by the contents of the entity\nreferred to. This includes external\nentity references and the external\nsubset.\n\nit includes serializer to save the document to a file ..\n", "Are you looking for something like this?\n#!/opt/local/bin/python\nimport sys\nif len(sys.argv) < 2:\n print \"some files needed.\"\n sys.exit()\n\nfinal = \"\"\"\n<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<nodes>\n\"\"\"\nfor a in sys.argv[1:]:\n ca = a.replace(\".xml\",\"\")\n final += \"<\" + ca + \">\\n\"\n infile = open(a)\n final += infile.read()\n final += \"</\" + ca + \">\\n\" \n\nfinal += \"</nodes>\\n\"\n\noutfile = open(\"final.xml\", \"w\")\noutfile.write(final)\noutfile.close()\n\n" ]
[ 5, 1, 0 ]
[]
[]
[ "bash", "editor", "python", "sed", "xml" ]
stackoverflow_0002019317_bash_editor_python_sed_xml.txt
Q: fastest way to compare strings in python I'm writing a script in Python that will allow the user to input a string, which will be a command that instructs the script to perform a specific action. For the sake of argument, I'll say my command list is: lock read write request log Now, I want the user to be able to enter the word "log" and it will peform a specific action, which is very simple. However, I would like to match partial words. So, for example, if a user enters "lo", it should match "lock", as it's higher in the list. I've tried using strncmp from libc using ctypes to accomplish this, but have yet to make heads or tails of it. A: If you are accepting input from a user, then why are you worried about the speed of comparison? Even the slowest technique will be far faster than the user can perceive. Use the simplest most understandable code you can, and leave efficiency concerns for tight inner loops. cmds = [ "lock", "read", "write", "request", "log", ] def match_cmd(s): matched = [c for c in cmds if c.startswith(s)] if matched: return matched[0] A: This will do what you want: def select_command(commands, user_input): user_input = user_input.strip().lower() for command in commands: if command.startswith(user_input): return command return None However: You seem overworried about the wrong thing. So 50 users means 50 milliseconds -- you're not going to be run out of town for that kind of "lag". Worry about inefficient database access or problems caused by users typing "r" and getting "read" when they thought they'd get "request". Minimising user keystrokes at the risk of errors is so 1960s that it's not funny. What are they using? ASR33 teletypes? At the very least you could insist on a unique match -- "rea" for read and "req" for request. A: This is optimized at runtime like you requested... (although most likely not needed) Here is a simple bit of code which will take an input dictionary of command mapped to function, and results in an output dictionary of all non-duplicate sub commands mapped to the same function. So you run this when you start your service, and then you have 100% optimized lookups. I am sure there is a more clever way to do this, so feel free to edit. commands = { 'log': log_function, 'exit': exit_function, 'foo': foo_function, 'line': line_function, } cmap = {} kill = set() for command in commands: for pos in range(len(1,command)): subcommand = command[0:pos] if subcommand in cmap: kill.add(subcommand) del(cmap[subcommand]) if subcommand not in kill: cmap[subcommand] = commands[command] #cmap now is the following - notice the duplicate prefixes removed? { 'lo': log_function, 'log': log_function, 'e': exit_function, 'ex': exit_function, 'exi': exit_function, 'exit': exit_function, 'f' : foo_function, 'fo' : foo_function, 'foo' : foo_function, 'li' : line_function, 'lin' : line_function, 'line' : line_function, } A: you can use startswith eg myword = "lock" if myword.startswith("lo"): print "ok" or if you want to find "lo" in the word, regardless of position, just use the "in" operator if "lo" in myword therefore, one way you can do this: for cmd in ["lock","read","write","request","log"]: if cmd.startswith(userinput): print cmd break A: I suggest you look at using the readline python library, rather than reinventing the wheel. The user will have to hit tab to complete the word, but you can set readline up so that tab matches as far as possible or cycles through all words starting wit the current stub. This seems to be a fairly decent introduction to readline in python http://www.doughellmann.com/PyMOTW/readline/index.html A: jaro_winkler() in python-Levenshtein might be what you're looking for. A: Replace with your favorite string compare function. Fairly fast, and to the point. matches = ( x for x in list if x[:len(stringToSearchFor)] == stringToSearchFor ) print matches[0] A: This is adapted from J.Tauber's Trie implementation in Python, which you could compare and/or re-adapt with whatever extra features you need. See also the Wikipedia entry on tries. class Trie: def __init__(self): self.root = [None, {}] def add(self, key): curr_node = self.root for ch in key: curr_node = curr_node[1].setdefault(ch, [key, {}]) curr_node[0] = key def find(self, key): curr_node = self.root for ch in key: try: curr_node = curr_node[1][ch] except KeyError: return None return curr_node[0] Setup (order of addition matters!): t = Trie() for word in [ 'lock', 'read', 'write', 'request', 'log']: t.add(word) Then call like this: >>> t.find('lo') 'lock' >>> t.find('log') 'log' >>> t.find('req') 'request' >>> t.find('requiem') >>> A: If i understand your Q correctly, you want a snippet that will return the answer as soon as it has it, without traversing further through your 'command list.' This should do what you want: from itertools import ifilter def check_input(some_string, code_book) : for q in ifilter(code_book.__contains__, some_string) : return True return False A: import timeit cmds = [] for i in range(1,10000): cmds.append("test") def get_cmds(user_input): return [c for c in cmds if c.startswith(user_input)] if __name__=='__main__': t = timeit.Timer("get_cmds('te')", "from __main__ import get_cmds") print "%0.3f seconds" % (t.timeit(number=1)) #>>> 0.008 seconds So basically, per my comment, you're asking how to optimise an operation that takes no measurable time or CPU. I used 10,000 commands here and the test string matches every one just to show that even under extreme circumstances you could still have hundreds of users doing this and they would never see any lag.
fastest way to compare strings in python
I'm writing a script in Python that will allow the user to input a string, which will be a command that instructs the script to perform a specific action. For the sake of argument, I'll say my command list is: lock read write request log Now, I want the user to be able to enter the word "log" and it will peform a specific action, which is very simple. However, I would like to match partial words. So, for example, if a user enters "lo", it should match "lock", as it's higher in the list. I've tried using strncmp from libc using ctypes to accomplish this, but have yet to make heads or tails of it.
[ "If you are accepting input from a user, then why are you worried about the speed of comparison? Even the slowest technique will be far faster than the user can perceive. Use the simplest most understandable code you can, and leave efficiency concerns for tight inner loops.\ncmds = [\n \"lock\",\n \"read\",\n \"write\",\n \"request\",\n \"log\",\n ]\n\ndef match_cmd(s):\n matched = [c for c in cmds if c.startswith(s)]\n if matched:\n return matched[0]\n\n", "This will do what you want:\ndef select_command(commands, user_input):\n user_input = user_input.strip().lower()\n for command in commands:\n if command.startswith(user_input):\n return command\n return None\n\nHowever:\nYou seem overworried about the wrong thing. So 50 users means 50 milliseconds -- you're not going to be run out of town for that kind of \"lag\". Worry about inefficient database access or problems caused by users typing \"r\" and getting \"read\" when they thought they'd get \"request\". Minimising user keystrokes at the risk of errors is so 1960s that it's not funny. What are they using? ASR33 teletypes? At the very least you could insist on a unique match -- \"rea\" for read and \"req\" for request.\n", "This is optimized at runtime like you requested... (although most likely not needed)\nHere is a simple bit of code which will take an input dictionary of command mapped to function, and results in an output dictionary of all non-duplicate sub commands mapped to the same function.\nSo you run this when you start your service, and then you have 100% optimized lookups. I am sure there is a more clever way to do this, so feel free to edit.\ncommands = {\n 'log': log_function,\n 'exit': exit_function,\n 'foo': foo_function,\n 'line': line_function,\n }\n\ncmap = {}\nkill = set()\nfor command in commands:\n for pos in range(len(1,command)):\n subcommand = command[0:pos]\n if subcommand in cmap:\n kill.add(subcommand)\n del(cmap[subcommand])\n if subcommand not in kill:\n cmap[subcommand] = commands[command]\n\n#cmap now is the following - notice the duplicate prefixes removed?\n{\n 'lo': log_function,\n 'log': log_function,\n 'e': exit_function,\n 'ex': exit_function,\n 'exi': exit_function,\n 'exit': exit_function,\n 'f' : foo_function,\n 'fo' : foo_function,\n 'foo' : foo_function,\n 'li' : line_function,\n 'lin' : line_function,\n 'line' : line_function,\n}\n\n", "you can use startswith\neg\nmyword = \"lock\"\nif myword.startswith(\"lo\"):\n print \"ok\"\n\nor if you want to find \"lo\" in the word, regardless of position, just use the \"in\" operator\nif \"lo\" in myword\n\ntherefore, one way you can do this:\nfor cmd in [\"lock\",\"read\",\"write\",\"request\",\"log\"]:\n if cmd.startswith(userinput):\n print cmd\n break\n\n", "I suggest you look at using the readline python library, rather than reinventing the wheel.\nThe user will have to hit tab to complete the word, but you can set readline up so that tab matches as far as possible or cycles through all words starting wit the current stub.\nThis seems to be a fairly decent introduction to readline in python http://www.doughellmann.com/PyMOTW/readline/index.html\n", "jaro_winkler() in python-Levenshtein might be what you're looking for.\n", "Replace with your favorite string compare function. Fairly fast, and to the point.\nmatches = ( x for x in list if x[:len(stringToSearchFor)] == stringToSearchFor )\nprint matches[0]\n\n", "This is adapted from J.Tauber's Trie implementation in Python, which you could compare and/or re-adapt with whatever extra features you need. See also the Wikipedia entry on tries.\nclass Trie:\n def __init__(self):\n self.root = [None, {}]\n\n def add(self, key):\n curr_node = self.root\n for ch in key:\n curr_node = curr_node[1].setdefault(ch, [key, {}])\n curr_node[0] = key\n\n def find(self, key):\n curr_node = self.root\n for ch in key:\n try:\n curr_node = curr_node[1][ch]\n except KeyError:\n return None\n return curr_node[0]\n\nSetup (order of addition matters!):\nt = Trie()\nfor word in [\n 'lock',\n 'read',\n 'write',\n 'request',\n 'log']:\n t.add(word)\n\nThen call like this:\n>>> t.find('lo')\n'lock'\n>>> t.find('log')\n'log'\n>>> t.find('req')\n'request'\n>>> t.find('requiem')\n>>>\n\n", "If i understand your Q correctly, you want a snippet that will return the answer as soon as it has it, without traversing further through your 'command list.' This should do what you want:\nfrom itertools import ifilter\n\ndef check_input(some_string, code_book) :\n for q in ifilter(code_book.__contains__, some_string) :\n return True\n return False\n\n", "import timeit\n\ncmds = []\nfor i in range(1,10000):\n cmds.append(\"test\")\n\ndef get_cmds(user_input):\n return [c for c in cmds if c.startswith(user_input)]\n\nif __name__=='__main__':\n t = timeit.Timer(\"get_cmds('te')\", \"from __main__ import get_cmds\")\n print \"%0.3f seconds\" % (t.timeit(number=1))\n\n#>>> 0.008 seconds\n\nSo basically, per my comment, you're asking how to optimise an operation that takes no measurable time or CPU. I used 10,000 commands here and the test string matches every one just to show that even under extreme circumstances you could still have hundreds of users doing this and they would never see any lag.\n" ]
[ 16, 5, 3, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0002053937_parsing_python_regex.txt
Q: How to average certain sized subsections of a list in python? I would like to take bites out of a list (or array) of a certain size, return the average for that bite, and then move on to the next bite and do that all over again. Is there some way to do this without writing a for loop? In [1]: import numpy as np In [2]: x = range(10) In [3]: np.average(x[:4]) Out[3]: 1.5 In [4]: np.average(x[4:8]) Out[4]: 5.5 In [5]: np.average(x[8:]) Out[5]: 8.5 I'm looking for something like, np.average(x[:bitesize=4]) to return: [1.5,5.5,8.5]. I have looked at slicing arrays and stepping through arrays, but I haven't found anything that does something like I want to have happen. A: [np.average(x[i:i+4]) for i in xrange(0, len(x), 4) ] A: The grouper itertools recipe can help. A: Using numpy, you can use np.average with the axis keyword: import numpy as np x=np.arange(12) y=x.reshape(3,4) print(y) # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] print(np.average(y,axis=1)) # [ 1.5 5.5 9.5] Note that to reshape x, I had to make x start with a length evenly divisible by the group size (in this case 4). If the length of x is not evenly divisible by the group size, then could create a masked array and use np.ma.average to compute the appropriate average. For example, x=np.ma.arange(12) y=x.reshape(3,4) mask=(x>=10) y.mask=mask print(y) # [[0 1 2 3] # [4 5 6 7] # [8 9 -- --]] print(np.ma.average(y,axis=1)) # [1.5 5.5 8.5]
How to average certain sized subsections of a list in python?
I would like to take bites out of a list (or array) of a certain size, return the average for that bite, and then move on to the next bite and do that all over again. Is there some way to do this without writing a for loop? In [1]: import numpy as np In [2]: x = range(10) In [3]: np.average(x[:4]) Out[3]: 1.5 In [4]: np.average(x[4:8]) Out[4]: 5.5 In [5]: np.average(x[8:]) Out[5]: 8.5 I'm looking for something like, np.average(x[:bitesize=4]) to return: [1.5,5.5,8.5]. I have looked at slicing arrays and stepping through arrays, but I haven't found anything that does something like I want to have happen.
[ "[np.average(x[i:i+4]) for i in xrange(0, len(x), 4) ]\n", "The grouper itertools recipe can help.\n", "Using numpy, you can use np.average with the axis keyword:\nimport numpy as np\nx=np.arange(12)\ny=x.reshape(3,4)\nprint(y)\n# [[ 0 1 2 3]\n# [ 4 5 6 7]\n# [ 8 9 10 11]]\nprint(np.average(y,axis=1))\n# [ 1.5 5.5 9.5]\n\nNote that to reshape x, I had to make x start with a length evenly divisible by the group size (in this case 4). \nIf the length of x is not evenly divisible by the group size, then could create a masked array and use np.ma.average to compute the appropriate average.\nFor example,\nx=np.ma.arange(12)\ny=x.reshape(3,4)\nmask=(x>=10)\ny.mask=mask\nprint(y)\n# [[0 1 2 3]\n# [4 5 6 7]\n# [8 9 -- --]]\nprint(np.ma.average(y,axis=1))\n# [1.5 5.5 8.5]\n\n" ]
[ 5, 1, 1 ]
[]
[]
[ "average", "list", "python" ]
stackoverflow_0002054013_average_list_python.txt
Q: how to create 2d array in python if we know number of rows,and number of columns depends on some condition? My array maximum dimension could be 2x27,but number of columns could be lower than 27.Number of columns depends on some condition.Is good solution to initialize array 2x27 and then delete unnecessary columns or has more elegant way to do this? A: No, it makes no particular sense to build a larger array then remove some part of it -- just build what you need. Assuming that by "2d array" you actually mean "list of lists": def makarray(value, nrows, ncols): return [[value]*ncols for _ in range(nrows)] A: For so few elements use a dictionary, with tuples as keys: dct = {} dct[(0,0)] = 'X' if (10,10) in dct: dct[(10,10)] += 1 else: dct[(10,10] = 0 # Deleting a row / column dct.pop((10,0)) dct.pop((10,1)) ... dct.pop((10,10)) Dictionaries are very flexible. Alternatively use a numpy array. A: Here is a simple way to handle it: num_rows, num_cols = 2, 27 table = [] for r in range(num_rows): row = [] table.append(row) for c in range(num_cols): row.append(c) print table
how to create 2d array in python if we know number of rows,and number of columns depends on some condition?
My array maximum dimension could be 2x27,but number of columns could be lower than 27.Number of columns depends on some condition.Is good solution to initialize array 2x27 and then delete unnecessary columns or has more elegant way to do this?
[ "No, it makes no particular sense to build a larger array then remove some part of it -- just build what you need. Assuming that by \"2d array\" you actually mean \"list of lists\":\ndef makarray(value, nrows, ncols):\n return [[value]*ncols for _ in range(nrows)]\n\n", "For so few elements use a dictionary, with tuples as keys:\ndct = {}\ndct[(0,0)] = 'X'\nif (10,10) in dct:\n dct[(10,10)] += 1\nelse:\n dct[(10,10] = 0\n# Deleting a row / column\ndct.pop((10,0))\ndct.pop((10,1))\n...\ndct.pop((10,10))\n\nDictionaries are very flexible.\nAlternatively use a numpy array.\n", "Here is a simple way to handle it:\nnum_rows, num_cols = 2, 27\ntable = []\n\nfor r in range(num_rows):\n row = []\n table.append(row)\n for c in range(num_cols):\n row.append(c)\n\nprint table\n\n" ]
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002053387_python.txt
Q: Python: Why does my function not display what's being returned in the interpreter? In the Python interactive interpreter: I am importing a module that contains a class. These are the methods of that class (some of them): def do_api_call(self, params): return self.__apicall(params) def __apicall(self, params): return urllib2.urlopen(self.endpoint, params).read() When I import the class and use the method do_api_call(), it doesn't output anything when it finishes running. def do_api_call(self, params): print(self.__apicall(params)) def __apicall(self, params): return urllib2.urlopen(self.endpoint, params).read() I create an instance of the class and run the method: myapi = MyAPIClass() myapi.do_api_call(params={'param': 'value'}) When I do the second version (note the print function) however, it outputs the HTML of the page that is being called. Why doesn't the first version output anything? It's working (ie, it's getting the page and not raising any errors). A: Your first version only returns the value that you would like to see as the output. The second version actually prints this value. If I were you, I would consider storing the return value of the call to the first version into a variable and printing that variable. That should solve your issue
Python: Why does my function not display what's being returned in the interpreter?
In the Python interactive interpreter: I am importing a module that contains a class. These are the methods of that class (some of them): def do_api_call(self, params): return self.__apicall(params) def __apicall(self, params): return urllib2.urlopen(self.endpoint, params).read() When I import the class and use the method do_api_call(), it doesn't output anything when it finishes running. def do_api_call(self, params): print(self.__apicall(params)) def __apicall(self, params): return urllib2.urlopen(self.endpoint, params).read() I create an instance of the class and run the method: myapi = MyAPIClass() myapi.do_api_call(params={'param': 'value'}) When I do the second version (note the print function) however, it outputs the HTML of the page that is being called. Why doesn't the first version output anything? It's working (ie, it's getting the page and not raising any errors).
[ "Your first version only returns the value that you would like to see as the output. The second version actually prints this value.\nIf I were you, I would consider storing the return value of the call to the first version into a variable and printing that variable. That should solve your issue\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002054228_python.txt
Q: Asynchronous data through Bloomberg's new data API (COM v3) with Python? Does anyone know how to get asynchronous data through Bloomberg's new data API (COM v3) with Python? I found this code below on wilmott.com and it works just fine, but it's for the old API version. Does anyone know the corresponding code for the new version? from win32com.client import DispatchWithEvents from pythoncom import PumpWaitingMessages, Empty, Missing from time import time class BBCommEvent: def OnData(self, Security, cookie, Fields, Data, Status): print 'OnData: ' + `Data` def OnStatus(self, Status, SubStatus, StatusDescription): print 'OnStatus' class TestAsync: def __init__(self): clsid = '{F2303261-4969-11D1-B305-00805F815CBF}' progid = 'Bloomberg.Data.1' print 'connecting to BBComm' blp = DispatchWithEvents(clsid, BBCommEvent) blp.AutoRelease = False blp.Subscribe('EUR Curncy', 1, 'LAST_PRICE', Results = Empty) blp.Flush() end_time = time() + 5 while 1: PumpWaitingMessages() if end_time < time(): print 'timed out' break if __name__ == "__main__": ta = TestAsync() A: I finally figured it out. I did a fair bit of combrowse.py detective work, and I compared with the JAVA, C, C++, and .NET examples in the BBG API download. Interestingly enough the Bloomberg Helpdesk people knew pretty much null when it came to these things, or perhaps I was just talking to the wrong person. Here is my code. asynchronousHandler.py: import win32com.client from pythoncom import PumpWaitingMessages from time import time, strftime import constants class EventHandler: def OnProcessEvent(self, result): event = win32com.client.gencache.EnsureDispatch(result) if event.EventType == constants.SUBSCRIPTION_DATA: self.getData(event) elif event.EventType == constants.SUBSCRIPTION_STATUS: self.getStatus(event) else: self.getMisc(event) def getData(self, event): iterator = event.CreateMessageIterator() while iterator.Next(): message = iterator.Message dataString = '' for fieldIndex, field in enumerate(constants.fields): if message.AsElement.HasElement(field): element = message.GetElement(field) if element.IsNull: theValue = '' else: theValue = ', Value: ' + str(element.Value) dataString = dataString + ', (Type: ' + element.Name + theValue + ')' print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + dataString def getMisc(self, event): iterator = event.CreateMessageIterator() while iterator.Next(): message = iterator.Message print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString def getStatus(self, event): iterator = event.CreateMessageIterator() while iterator.Next(): message = iterator.Message if message.AsElement.HasElement('reason'): element = message.AsElement.GetElement('reason') print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + ', Category: ' + element.GetElement('category').Value + ', Description: ' + element.GetElement('description').Value if message.AsElement.HasElement('exceptions'): element = message.AsElement.GetElement('exceptions') exceptionString = '' for n in range(element.NumValues): exceptionInfo = element.GetValue(n) fieldId = exceptionInfo.GetElement('fieldId') reason = exceptionInfo.GetElement('reason') exceptionString = exceptionString + ', (Field: ' + fieldId.Value + ', Category: ' + reason.GetElement('category').Value + ', Description: ' + reason.GetElement('description').Value + ') ' print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + exceptionString class bloombergSource: def __init__(self): session = win32com.client.DispatchWithEvents('blpapicom.Session' , EventHandler) session.Start() started = session.OpenService('//blp/mktdata') subscriptions = session.CreateSubscriptionList() for tickerIndex, ticker in enumerate(constants.tickers): if len(constants.interval) > 0: subscriptions.AddEx(ticker, constants.fields, constants.interval, session.CreateCorrelationId(tickerIndex)) else: subscriptions.Add(ticker, constants.fields, session.CreateCorrelationId(tickerIndex)) session.Subscribe(subscriptions) endTime = time() + 2 while True: PumpWaitingMessages() if endTime < time(): break if __name__ == "__main__": aBloombergSource = bloombergSource() constants.py: ADMIN = 1 AUTHORIZATION_STATUS = 11 BLPSERVICE_STATUS = 9 PARTIAL_RESPONSE = 6 PUBLISHING_DATA = 13 REQUEST_STATUS = 4 RESOLUTION_STATUS = 12 RESPONSE = 5 SESSION_STATUS = 2 SUBSCRIPTION_DATA = 8 SUBSCRIPTION_STATUS = 3 TIMEOUT = 10 TOKEN_STATUS = 15 TOPIC_STATUS = 14 UNKNOWN = -1 fields = ['BID'] tickers = ['AUD Curncy'] interval = '' #'interval=5.0' For historical data I used this simple script: import win32com.client session = win32com.client.Dispatch('blpapicom.Session') session.QueueEvents = True session.Start() started = session.OpenService('//blp/refdata') dataService = session.GetService('//blp/refdata') request = dataService.CreateRequest('HistoricalDataRequest') request.GetElement('securities').AppendValue('5 HK Equity') request.GetElement('fields').AppendValue('PX_LAST') request.Set('periodicitySelection', 'DAILY') request.Set('startDate', '20090119') request.Set('endDate', '20090130') cid = session.SendRequest(request) ADMIN = 1 AUTHORIZATION_STATUS = 11 BLPSERVICE_STATUS = 9 PARTIAL_RESPONSE = 6 PUBLISHING_DATA = 13 REQUEST_STATUS = 4 RESOLUTION_STATUS = 12 RESPONSE = 5 SESSION_STATUS = 2 SUBSCRIPTION_DATA = 8 SUBSCRIPTION_STATUS = 3 TIMEOUT = 10 TOKEN_STATUS = 15 TOPIC_STATUS = 14 UNKNOWN = -1 stayHere = True while stayHere: event = session.NextEvent(); if event.EventType == PARTIAL_RESPONSE or event.EventType == RESPONSE: iterator = event.CreateMessageIterator() iterator.Next() message = iterator.Message securityData = message.GetElement('securityData') securityName = securityData.GetElement('security') fieldData = securityData.GetElement('fieldData') returnList = [[0 for col in range(fieldData.GetValue(row).NumValues+1)] for row in range(fieldData.NumValues)] for row in range(fieldData.NumValues): rowField = fieldData.GetValue(row) for col in range(rowField.NumValues+1): colField = rowField.GetElement(col) returnList[row][col] = colField.Value stayHere = False break element = None iterator = None message = None event = None session = None print returnList A: For it to work you need to install Bloomberg Desktop v3 API SDK, I did that, restarted my machine, seems to work. Without the restart it just crashed. If you use Com explorer, you will see the bloomberg elements are now present
Asynchronous data through Bloomberg's new data API (COM v3) with Python?
Does anyone know how to get asynchronous data through Bloomberg's new data API (COM v3) with Python? I found this code below on wilmott.com and it works just fine, but it's for the old API version. Does anyone know the corresponding code for the new version? from win32com.client import DispatchWithEvents from pythoncom import PumpWaitingMessages, Empty, Missing from time import time class BBCommEvent: def OnData(self, Security, cookie, Fields, Data, Status): print 'OnData: ' + `Data` def OnStatus(self, Status, SubStatus, StatusDescription): print 'OnStatus' class TestAsync: def __init__(self): clsid = '{F2303261-4969-11D1-B305-00805F815CBF}' progid = 'Bloomberg.Data.1' print 'connecting to BBComm' blp = DispatchWithEvents(clsid, BBCommEvent) blp.AutoRelease = False blp.Subscribe('EUR Curncy', 1, 'LAST_PRICE', Results = Empty) blp.Flush() end_time = time() + 5 while 1: PumpWaitingMessages() if end_time < time(): print 'timed out' break if __name__ == "__main__": ta = TestAsync()
[ "I finally figured it out. I did a fair bit of combrowse.py detective work, and I compared with the JAVA, C, C++, and .NET examples in the BBG API download. Interestingly enough the Bloomberg Helpdesk people knew pretty much null when it came to these things, or perhaps I was just talking to the wrong person.\nHere is my code.\nasynchronousHandler.py:\nimport win32com.client\nfrom pythoncom import PumpWaitingMessages\nfrom time import time, strftime\nimport constants\n\nclass EventHandler:\n def OnProcessEvent(self, result):\n event = win32com.client.gencache.EnsureDispatch(result) \n if event.EventType == constants.SUBSCRIPTION_DATA:\n self.getData(event)\n elif event.EventType == constants.SUBSCRIPTION_STATUS:\n self.getStatus(event)\n else:\n self.getMisc(event)\n def getData(self, event):\n iterator = event.CreateMessageIterator()\n while iterator.Next():\n message = iterator.Message \n dataString = ''\n for fieldIndex, field in enumerate(constants.fields): \n if message.AsElement.HasElement(field):\n element = message.GetElement(field)\n if element.IsNull:\n theValue = ''\n else:\n theValue = ', Value: ' + str(element.Value) \n dataString = dataString + ', (Type: ' + element.Name + theValue + ')'\n print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + dataString\n def getMisc(self, event):\n iterator = event.CreateMessageIterator()\n while iterator.Next():\n message = iterator.Message\n print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString\n def getStatus(self, event):\n iterator = event.CreateMessageIterator()\n while iterator.Next():\n message = iterator.Message\n if message.AsElement.HasElement('reason'):\n element = message.AsElement.GetElement('reason')\n print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + ', Category: ' + element.GetElement('category').Value + ', Description: ' + element.GetElement('description').Value \n if message.AsElement.HasElement('exceptions'):\n element = message.AsElement.GetElement('exceptions')\n exceptionString = ''\n for n in range(element.NumValues):\n exceptionInfo = element.GetValue(n)\n fieldId = exceptionInfo.GetElement('fieldId')\n reason = exceptionInfo.GetElement('reason')\n exceptionString = exceptionString + ', (Field: ' + fieldId.Value + ', Category: ' + reason.GetElement('category').Value + ', Description: ' + reason.GetElement('description').Value + ') ' \n print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + exceptionString\n\nclass bloombergSource:\n def __init__(self):\n session = win32com.client.DispatchWithEvents('blpapicom.Session' , EventHandler)\n session.Start()\n started = session.OpenService('//blp/mktdata')\n subscriptions = session.CreateSubscriptionList()\n for tickerIndex, ticker in enumerate(constants.tickers):\n if len(constants.interval) > 0:\n subscriptions.AddEx(ticker, constants.fields, constants.interval, session.CreateCorrelationId(tickerIndex))\n else:\n subscriptions.Add(ticker, constants.fields, session.CreateCorrelationId(tickerIndex)) \n session.Subscribe(subscriptions)\n endTime = time() + 2\n while True:\n PumpWaitingMessages()\n if endTime < time(): \n break \n\nif __name__ == \"__main__\":\n aBloombergSource = bloombergSource()\n\nconstants.py:\nADMIN = 1\nAUTHORIZATION_STATUS = 11\nBLPSERVICE_STATUS = 9\nPARTIAL_RESPONSE = 6\nPUBLISHING_DATA = 13\nREQUEST_STATUS = 4\nRESOLUTION_STATUS = 12\nRESPONSE = 5\nSESSION_STATUS = 2\nSUBSCRIPTION_DATA = 8\nSUBSCRIPTION_STATUS = 3\nTIMEOUT = 10\nTOKEN_STATUS = 15\nTOPIC_STATUS = 14\nUNKNOWN = -1\nfields = ['BID']\ntickers = ['AUD Curncy']\ninterval = '' #'interval=5.0'\n\nFor historical data I used this simple script:\nimport win32com.client\n\nsession = win32com.client.Dispatch('blpapicom.Session')\nsession.QueueEvents = True\nsession.Start()\nstarted = session.OpenService('//blp/refdata')\ndataService = session.GetService('//blp/refdata')\nrequest = dataService.CreateRequest('HistoricalDataRequest')\nrequest.GetElement('securities').AppendValue('5 HK Equity')\nrequest.GetElement('fields').AppendValue('PX_LAST')\nrequest.Set('periodicitySelection', 'DAILY')\nrequest.Set('startDate', '20090119')\nrequest.Set('endDate', '20090130')\ncid = session.SendRequest(request)\nADMIN = 1\nAUTHORIZATION_STATUS = 11\nBLPSERVICE_STATUS = 9\nPARTIAL_RESPONSE = 6\nPUBLISHING_DATA = 13\nREQUEST_STATUS = 4\nRESOLUTION_STATUS = 12\nRESPONSE = 5\nSESSION_STATUS = 2\nSUBSCRIPTION_DATA = 8\nSUBSCRIPTION_STATUS = 3\nTIMEOUT = 10\nTOKEN_STATUS = 15\nTOPIC_STATUS = 14\nUNKNOWN = -1\nstayHere = True\nwhile stayHere:\n event = session.NextEvent();\n if event.EventType == PARTIAL_RESPONSE or event.EventType == RESPONSE:\n iterator = event.CreateMessageIterator()\n iterator.Next()\n message = iterator.Message\n securityData = message.GetElement('securityData')\n securityName = securityData.GetElement('security')\n fieldData = securityData.GetElement('fieldData')\n returnList = [[0 for col in range(fieldData.GetValue(row).NumValues+1)] for row in range(fieldData.NumValues)]\n for row in range(fieldData.NumValues):\n rowField = fieldData.GetValue(row)\n for col in range(rowField.NumValues+1):\n colField = rowField.GetElement(col)\n returnList[row][col] = colField.Value\n stayHere = False\n break\nelement = None\niterator = None\nmessage = None\nevent = None\nsession = None\nprint returnList\n\n", "For it to work you need to install Bloomberg Desktop v3 API SDK, I did that, restarted my machine, seems to work. Without the restart it just crashed.\nIf you use Com explorer, you will see the bloomberg elements are now present\n" ]
[ 19, 0 ]
[]
[]
[ "asynchronous", "bloomberg", "python", "win32com" ]
stackoverflow_0002005234_asynchronous_bloomberg_python_win32com.txt
Q: creating a numpy vector using 3 components I want to create a vector in numpy using 3 components Vx, Vy, Vz as sown below. Can anyone help? Thank you from numpy import cos, sin Vx = cos(alpha)* cos(beta) Vy = sin(alpha)*cos(beta) Vz = sin(beta) A: With NumPy, vectors (and matrices for that matter) are just Python arrays. As in from numpy import array myVector = array([Vx, Vy, Vz]) myMatrix = array([[Vx, Vy, Vz], [1,2,3]])
creating a numpy vector using 3 components
I want to create a vector in numpy using 3 components Vx, Vy, Vz as sown below. Can anyone help? Thank you from numpy import cos, sin Vx = cos(alpha)* cos(beta) Vy = sin(alpha)*cos(beta) Vz = sin(beta)
[ "With NumPy, vectors (and matrices for that matter) are just Python arrays. As in\nfrom numpy import array\nmyVector = array([Vx, Vy, Vz])\nmyMatrix = array([[Vx, Vy, Vz], [1,2,3]])\n\n" ]
[ 6 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002054360_numpy_python.txt
Q: Getting the first elements per row in an array in Python? Let's say i have an array of Tuples, s, in the form of: s = ((1, 23, 34),(2, 34, 44), (3, 444, 234)) and i want to return another Tuple, t, consisting of the first element per row: t = (1, 2, 3) Which would be the most efficient method to do this? I could of course just iterate through s, but is there any slicker way of doing it? A: No. t = tuple(x[0] for x in s) A: The list comprehension method given by Ignacio is the cleanest. Just for kicks, you could also do: zip(*s)[0] *s expands s into a list of arguments. So it is equivalent to zip( (1, 23, 34),(2, 34, 44), (3, 444, 234)) And zip returns n tuples where each tuple contains the nth item from each list. A: import itertools s = ((1, 23, 34),(2, 34, 44), (3, 444, 234)) print(next(itertools.izip(*s))) itertools.izip returns an iterator. The next function returns the next (and in this case, first) element from the iterator. In Python 2.x, zip returns a tuple. izip uses less memory since iterators do not generate their contents until needed. In Python 3, zip returns an iterator.
Getting the first elements per row in an array in Python?
Let's say i have an array of Tuples, s, in the form of: s = ((1, 23, 34),(2, 34, 44), (3, 444, 234)) and i want to return another Tuple, t, consisting of the first element per row: t = (1, 2, 3) Which would be the most efficient method to do this? I could of course just iterate through s, but is there any slicker way of doing it?
[ "No.\nt = tuple(x[0] for x in s)\n\n", "The list comprehension method given by Ignacio is the cleanest.\nJust for kicks, you could also do:\nzip(*s)[0]\n\n*s expands s into a list of arguments. So it is equivalent to \nzip( (1, 23, 34),(2, 34, 44), (3, 444, 234))\n\nAnd zip returns n tuples where each tuple contains the nth item from each list.\n", "import itertools\ns = ((1, 23, 34),(2, 34, 44), (3, 444, 234))\nprint(next(itertools.izip(*s)))\n\nitertools.izip returns an iterator. The next function returns the next (and in this case, first) element from the iterator. \nIn Python 2.x, zip returns a tuple.\nizip uses less memory since iterators do not generate their contents until needed.\nIn Python 3, zip returns an iterator.\n" ]
[ 23, 5, 1 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0002054416_python_tuples.txt
Q: find corresponding key,values and return? I have a dictionary cities = {1:'Kompong Som', 2: 'Kompong Thom', 3: 'Phnom Penh'} tags = {1: 'school', 2: 'public', 3: 'private'} kwargs = {'city': '2', 'tag': '3'}#should be improve I want to get output like this : kwargs = {'city': 'Kompong Thom', 'tag': 'private'} EDIT passed from URL keyword = customer_type=&last_contact=&tag=2,3&city=3&sale_volume=&acc_creation=&last_sale=&key_comm= in this case tag=2,3&city=3 maybe in other case tag=2&city=1,2,3 or tag=1,2,3&city=1,2,3 def present_filter(self, list_result, keyword): #@todo: the present filter should be friendly with user . if len(list_result) > 0: keywords = eval(json.dumps(keyword)) new_keywords = {} for key,value in keywords.items(): if value != '' : new_keywords[key] = value return new_keywords # Now new_keywords is {'city': '3', 'tag': '2,3'} # I WANT TO BE LIKE THIS #new_keywords is {'city': 'Phnom Penh', 'tag': 'public,private'} else: return '' A: def translate(cities, tags, kwargs): return {'city': cities[int(kwargs['city'])], 'tag': tags[int(kwargs['tag'])]} There's no clear way (from your question) to automate the keyname-to-auxiliary dictionary choice, so I've just hardcoded the keys and aux dict to use for each; if that's not what you want, please edit your question to clarify what it is that you want!-) Edit: so given this new and different spec from the OP: # Now new_keywords is {'city': '3', 'tag': '2,3'} # I WANT TO BE LIKE THIS #new_keywords is {'city': 'Phnom Penh', 'tag': 'public,private'} the solution becomes: def commaplay(adict, value): return ','.join(adict[int(x)] for x in value.split(',')) def translate(cities, tags, kwargs): return {'city': commaplay(cities, kwargs['city']), 'tag': commaplay(tags, kwargs['tag'])} Of course, if the OP completely changes their specs again, the solution will change once more in response (wouldn't it be just incredibly great if people said what they meant, and meant what they said, instead of whirling things around all the time?!-). A: You could put cities and tags in a helper dictionary to make it more easy to select the correct values using the kwargs keys: choices = { 'city': cities, 'tag': tags } result = {} for k, v in kwargs: result[k] = choices[k][int(v)]
find corresponding key,values and return?
I have a dictionary cities = {1:'Kompong Som', 2: 'Kompong Thom', 3: 'Phnom Penh'} tags = {1: 'school', 2: 'public', 3: 'private'} kwargs = {'city': '2', 'tag': '3'}#should be improve I want to get output like this : kwargs = {'city': 'Kompong Thom', 'tag': 'private'} EDIT passed from URL keyword = customer_type=&last_contact=&tag=2,3&city=3&sale_volume=&acc_creation=&last_sale=&key_comm= in this case tag=2,3&city=3 maybe in other case tag=2&city=1,2,3 or tag=1,2,3&city=1,2,3 def present_filter(self, list_result, keyword): #@todo: the present filter should be friendly with user . if len(list_result) > 0: keywords = eval(json.dumps(keyword)) new_keywords = {} for key,value in keywords.items(): if value != '' : new_keywords[key] = value return new_keywords # Now new_keywords is {'city': '3', 'tag': '2,3'} # I WANT TO BE LIKE THIS #new_keywords is {'city': 'Phnom Penh', 'tag': 'public,private'} else: return ''
[ "def translate(cities, tags, kwargs):\n return {'city': cities[int(kwargs['city'])],\n 'tag': tags[int(kwargs['tag'])]}\n\nThere's no clear way (from your question) to automate the keyname-to-auxiliary dictionary choice, so I've just hardcoded the keys and aux dict to use for each; if that's not what you want, please edit your question to clarify what it is that you want!-)\nEdit: so given this new and different spec from the OP:\n # Now new_keywords is {'city': '3', 'tag': '2,3'}\n # I WANT TO BE LIKE THIS\n #new_keywords is {'city': 'Phnom Penh', 'tag': 'public,private'}\n\nthe solution becomes:\ndef commaplay(adict, value):\n return ','.join(adict[int(x)] for x in value.split(','))\n\ndef translate(cities, tags, kwargs):\n return {'city': commaplay(cities, kwargs['city']),\n 'tag': commaplay(tags, kwargs['tag'])}\n\nOf course, if the OP completely changes their specs again, the solution will change once more in response (wouldn't it be just incredibly great if people said what they meant, and meant what they said, instead of whirling things around all the time?!-).\n", "You could put cities and tags in a helper dictionary to make it more easy to select the correct values using the kwargs keys:\nchoices = {\n 'city': cities,\n 'tag': tags\n}\n\nresult = {}\nfor k, v in kwargs:\n result[k] = choices[k][int(v)]\n\n" ]
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002054490_python.txt
Q: How to disable shell interception of control characters? I'm writing a curses application in Python under UNIX. I want to enable the user to use C-Y to yank from a kill ring a la Emacs. The trouble is, of course, that C-Y is caught by my shell which then sends SIGTSTP to my process. In addition, C-Z also results in SIGTSTP being sent, so catching the signal means that C-Y and C-Z are not distinguishable (though even without this the only solutions I can think of are extremely hackish). I know what I'm asking is possible (in C if not in Python), since Emacs does it. How can I disable the shell's special handling of certain control characters sent from the keyboard and have the characters in question appear on the process' stdin? A: See the termios module, and the termios(3) man page. A: For basic functionality, use tty. For example, calling tty.setraw(sys.stdin) will put standard input's terminal into raw mode. For the more general case, Python comes with a termios library, but you probably need some experience with termios to know how to use it. Alternatively, a cheap way is to shell out to stty, which is a command-line interface to termios.
How to disable shell interception of control characters?
I'm writing a curses application in Python under UNIX. I want to enable the user to use C-Y to yank from a kill ring a la Emacs. The trouble is, of course, that C-Y is caught by my shell which then sends SIGTSTP to my process. In addition, C-Z also results in SIGTSTP being sent, so catching the signal means that C-Y and C-Z are not distinguishable (though even without this the only solutions I can think of are extremely hackish). I know what I'm asking is possible (in C if not in Python), since Emacs does it. How can I disable the shell's special handling of certain control characters sent from the keyboard and have the characters in question appear on the process' stdin?
[ "See the termios module, and the termios(3) man page.\n", "For basic functionality, use tty. For example, calling tty.setraw(sys.stdin) will put standard input's terminal into raw mode.\nFor the more general case, Python comes with a termios library, but you probably need some experience with termios to know how to use it.\nAlternatively, a cheap way is to shell out to stty, which is a command-line interface to termios.\n" ]
[ 2, 1 ]
[]
[]
[ "curses", "python", "signals", "unix" ]
stackoverflow_0002054626_curses_python_signals_unix.txt
Q: evolution plugin for crm integration via webservices I have built a webservice into my companies self developed CRM system that we are in the process of integrating Outlook to the CRM for calendar sync and recording of emails related to clients. I want to build a plugin for the gnome evolution mail client as I use it for my work mail/calendar as I primarily run Linux. I am familiar with both C/C++ and to some extent Python but haven't done anything towards either evolution plugins or webservices connections in either so I am looking for some help. What language would be best to build an evolution plugin that can connect to webservices? Is there a simple "Hello world" style evolution plugin example somewhere I can use to get started? A: I would start with the architecture of Evolution. Then I would look into EPlugins and start off with this. An example for writing a plugin would be this. You will need some familiarity with XML. Hope this helps.
evolution plugin for crm integration via webservices
I have built a webservice into my companies self developed CRM system that we are in the process of integrating Outlook to the CRM for calendar sync and recording of emails related to clients. I want to build a plugin for the gnome evolution mail client as I use it for my work mail/calendar as I primarily run Linux. I am familiar with both C/C++ and to some extent Python but haven't done anything towards either evolution plugins or webservices connections in either so I am looking for some help. What language would be best to build an evolution plugin that can connect to webservices? Is there a simple "Hello world" style evolution plugin example somewhere I can use to get started?
[ "I would start with the architecture of Evolution. Then I would look into EPlugins and start off with this. An example for writing a plugin would be this. You will need some familiarity with XML. \nHope this helps.\n" ]
[ 1 ]
[]
[]
[ "c", "email", "linux", "python" ]
stackoverflow_0002027300_c_email_linux_python.txt
Q: How to import models in other projects in Django Is it possible to import models from apps in different Django projects? I hope to move some common models in a base projects from which every child projects can share the same data in these common models. Edit I have to place from baseproject.appname.models import basemodel before os.environ['DJANGO_SETTINGS_MODULE'] = 'childproject.settings' from django.conf import settings in child project to access the data in base model correctly. A: Yes. You can turn a project-specific app into a standard Python package by moving it to site-packages (or wherever your Python install expects its modules) and breaking any links from it to other apps in the project. You can then import it as you would any Python module, in any project.
How to import models in other projects in Django
Is it possible to import models from apps in different Django projects? I hope to move some common models in a base projects from which every child projects can share the same data in these common models. Edit I have to place from baseproject.appname.models import basemodel before os.environ['DJANGO_SETTINGS_MODULE'] = 'childproject.settings' from django.conf import settings in child project to access the data in base model correctly.
[ "Yes. You can turn a project-specific app into a standard Python package by moving it to site-packages (or wherever your Python install expects its modules) and breaking any links from it to other apps in the project. You can then import it as you would any Python module, in any project.\n" ]
[ 3 ]
[]
[]
[ "django", "model", "python" ]
stackoverflow_0002054898_django_model_python.txt
Q: How to stop "warnings" when using vim omni-completion with python? I am trying vim's python omni-completion script, it works, but I got problem. After I start vim, the 1st time I press to ask vim to complete python code, many warning shown up. That's because some python libs in my project use md5, which will trigger a warning message in python 2.6 That's very ignoring, how to stop vim/python from issuing warning? A: If you have a top level routine which imports the 3rd party library, you can insert this import warnings warnings.simplefilter("ignore",DeprecationWarning) to ignore all deprecation warnings (which is what the md5 warning is). Check the warnings module for the details on more sophisticated filtering.
How to stop "warnings" when using vim omni-completion with python?
I am trying vim's python omni-completion script, it works, but I got problem. After I start vim, the 1st time I press to ask vim to complete python code, many warning shown up. That's because some python libs in my project use md5, which will trigger a warning message in python 2.6 That's very ignoring, how to stop vim/python from issuing warning?
[ "If you have a top level routine which imports the 3rd party library, you can insert this\nimport warnings\nwarnings.simplefilter(\"ignore\",DeprecationWarning)\n\nto ignore all deprecation warnings (which is what the md5 warning is).\nCheck the warnings module for the details on more sophisticated filtering.\n" ]
[ 1 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0002054942_python_vim.txt
Q: How to provide a default value for base class attribute from subclass in Django? Scenario: class BaseClass(models.Model): base_field = models.CharField(max_length=15, default=None) class SubClass(BaseClass): # TODO set default value if base_field's value is None ... ie. I need to be able to load a fixture into the database, providing a default value only if the base_field is None. Any help greatly appreciated! (note: BaseClass is not abstract) A: You could override the save method, check if base_field is set, otherwise set it to the default value.
How to provide a default value for base class attribute from subclass in Django?
Scenario: class BaseClass(models.Model): base_field = models.CharField(max_length=15, default=None) class SubClass(BaseClass): # TODO set default value if base_field's value is None ... ie. I need to be able to load a fixture into the database, providing a default value only if the base_field is None. Any help greatly appreciated! (note: BaseClass is not abstract)
[ "You could override the save method, check if base_field is set, otherwise set it to the default value.\n" ]
[ 3 ]
[]
[]
[ "django", "django_inheritance", "django_models", "python" ]
stackoverflow_0002054831_django_django_inheritance_django_models_python.txt
Q: How do I send email with django-registration? How do I send email with django-registration? A: django-registration sends an email to the user, e.g. when he or she registers. The process is as follows (if this was your question ...)*: The user has filled out and submitted the registration form ... in views.py:187 new_user = backend.register(request, **form.cleaned_data) in e.g. backends/default/__init__.py:78 new_user = RegistrationProfile.objects.create_inactive_user(username, email, password, site) in models.py:79 if send_email: registration_profile.send_activation_email(site) and then in models.py:207 def send_activation_email(self, site): ... self.user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL) The last method call goes into django.contrib.auth, especially django.contrib.auth.models.User.email_user P.S. Also, it's crude, but in general a search on the codebase, e.g. with grep or similar tools can show you things like this. *changeset 073835a4269f
How do I send email with django-registration?
How do I send email with django-registration?
[ "django-registration sends an email to the user, e.g. when he or she registers. The process is as follows (if this was your question ...)*:\n\nThe user has filled out and submitted the registration form ...\nin views.py:187\nnew_user = backend.register(request, **form.cleaned_data)\n\nin e.g. backends/default/__init__.py:78\nnew_user = RegistrationProfile.objects.create_inactive_user(username, email,\n password, site)\n\nin models.py:79\nif send_email:\n registration_profile.send_activation_email(site)\n\nand then in models.py:207\ndef send_activation_email(self, site):\n ...\n self.user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL)\n\n\nThe last method call goes into django.contrib.auth, especially django.contrib.auth.models.User.email_user\nP.S. Also, it's crude, but in general a search on the codebase, e.g. with grep or similar tools can show you things like this.\n*changeset 073835a4269f\n" ]
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002054785_django_python.txt
Q: is there a way to view the source of a module from within the python console? if I'm in the python console and I want to see how a particular module works, is there an easy way to dump the source? A: Some of the methods of inspect module are well-suited for this purpose: import module import inspect src = inspect.getsource(module) A: Using IPython, you can do this: In [1]: import pyparsing In [2]: pyparsing.Word?? ...and the source will be displayed, if possible. I guess this must use inspect under the hood, but the added convenience of ? / ?? is fantastic. A: Maybe print open('mymodule.py').read() ? See file.read().
is there a way to view the source of a module from within the python console?
if I'm in the python console and I want to see how a particular module works, is there an easy way to dump the source?
[ "Some of the methods of inspect module are well-suited for this purpose:\nimport module\nimport inspect\nsrc = inspect.getsource(module)\n\n", "Using IPython, you can do this:\nIn [1]: import pyparsing\nIn [2]: pyparsing.Word??\n\n...and the source will be displayed, if possible. I guess this must use inspect under the hood, but the added convenience of ? / ?? is fantastic.\n", "Maybe\nprint open('mymodule.py').read()\n\n?\nSee file.read().\n" ]
[ 41, 8, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002055110_python.txt
Q: is there a way to have a python application run invisibly? I have a cherrypy application that I want to control over http with a simple gui. The problem is I don't want both the cherrypy window and the gui running at the same time. Is there a way I can make the cherrypy applications window visible? Its being written for windows, which probably makes a difference A: Use pythonw.exe rather than python.exe It will start without a console window. If you're using py2exe, you need to change your setup file to not use a console from distutils.core import setup import py2exe setup(windows=[{"script":"hello.py"}])
is there a way to have a python application run invisibly?
I have a cherrypy application that I want to control over http with a simple gui. The problem is I don't want both the cherrypy window and the gui running at the same time. Is there a way I can make the cherrypy applications window visible? Its being written for windows, which probably makes a difference
[ "Use pythonw.exe rather than python.exe It will start without a console window.\nIf you're using py2exe, you need to change your setup file to not use a console\nfrom distutils.core import setup\nimport py2exe\nsetup(windows=[{\"script\":\"hello.py\"}])\n\n" ]
[ 2 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0002055458_cherrypy_python.txt
Q: Django: Unexpectedly persistent module variables I noticed a strange behaviour today: It seems that, in the following example, the config.CLIENT variable stays persistent accross requests – even if the view gets passed an entirely different client_key, the query that gets the client is only executed once (per many requests), and then the config.CLIENT variable stays assigned. It does not seem to be a database caching issue. It happens with mod_python as well as with the test server (the variable is reassigned when the test server is restarted). What am I missing here? #views.py from my_app import config def get_client(client_key=None): if config.CLIENT == None: config.CLIENT = get_object_or_404(Client, key__exact=client_key, is_active__exact=True) return config.CLIENT def some_view(request, client_key): client = get_client(client_key) ... return some_response # config.py CLIENT = None A: Multiple requests are processed by the same process and global variables like your CLIENT live as long, as process does. You shouldn't rely on global variables, when processing requests - use either local ones, when you need to keep a variable for the time of building response or put data into the database, when something must persist across multiple requests. If you need to keep some value through the request you can either add it to thread locals (here you should some examples, that adds user info to locals) or simply pass it as a variable into other functions. A: OK, just to make it slightly clearer (and in response to the comment by Felix), I'm posting the code that does what I needed. The whole problem arose from a fundamental misunderstanding on my part and I'm sorry for any confusion I might have caused. import config # This will be called once per request/view def init_client(client_key): config.CLIENT = get_object_or_404(Client, key__exact=client_key, is_active__exact=True) # This might be called from other modules that are unaware of requests, views etc def get_client(): return config.CLIENT
Django: Unexpectedly persistent module variables
I noticed a strange behaviour today: It seems that, in the following example, the config.CLIENT variable stays persistent accross requests – even if the view gets passed an entirely different client_key, the query that gets the client is only executed once (per many requests), and then the config.CLIENT variable stays assigned. It does not seem to be a database caching issue. It happens with mod_python as well as with the test server (the variable is reassigned when the test server is restarted). What am I missing here? #views.py from my_app import config def get_client(client_key=None): if config.CLIENT == None: config.CLIENT = get_object_or_404(Client, key__exact=client_key, is_active__exact=True) return config.CLIENT def some_view(request, client_key): client = get_client(client_key) ... return some_response # config.py CLIENT = None
[ "Multiple requests are processed by the same process and global variables like your CLIENT live as long, as process does. You shouldn't rely on global variables, when processing requests - use either local ones, when you need to keep a variable for the time of building response or put data into the database, when something must persist across multiple requests.\nIf you need to keep some value through the request you can either add it to thread locals (here you should some examples, that adds user info to locals) or simply pass it as a variable into other functions.\n", "OK, just to make it slightly clearer (and in response to the comment by Felix), I'm posting the code that does what I needed. The whole problem arose from a fundamental misunderstanding on my part and I'm sorry for any confusion I might have caused.\nimport config\n\n# This will be called once per request/view\ndef init_client(client_key):\n config.CLIENT = get_object_or_404(Client, key__exact=client_key, is_active__exact=True)\n\n# This might be called from other modules that are unaware of requests, views etc \ndef get_client():\n return config.CLIENT\n\n" ]
[ 6, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002050320_django_python.txt
Q: is there any difference between 'a.b.a' and 'b.b.a' class a(object): class b: a='aaa' print a.b.a#print 'aaa' b=a() print b.b.a#print 'aaa' A: No. To create instance variables, you need to explicitly prefix them with self., in the constructor method __init__(self). In your code, you're simply assigning in the class scope, and those variables can be reached both ways. A: Running your code and then a.b.a is b.b.a gives the result of True, which indicates that they are, indeed, referring to the same object - the class variable a of inner class b. A: Either ways, you are accessing: "outerclass/object.innerclass/object.member".
is there any difference between 'a.b.a' and 'b.b.a'
class a(object): class b: a='aaa' print a.b.a#print 'aaa' b=a() print b.b.a#print 'aaa'
[ "No.\nTo create instance variables, you need to explicitly prefix them with self., in the constructor method __init__(self).\nIn your code, you're simply assigning in the class scope, and those variables can be reached both ways.\n", "Running your code and then a.b.a is b.b.a gives the result of True, which indicates that they are, indeed, referring to the same object - the class variable a of inner class b.\n", "Either ways, you are accessing: \"outerclass/object.innerclass/object.member\".\n" ]
[ 5, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002055604_python.txt
Q: python memory del list[:] vs list = [] In python I have noticed that if you do mylist = [] for i in range(0,100000000): mylist.append('something here to take memory') mylist = [] it would seem the second call mylist = [] would remove the reference and it would get collected but, as I watch them memory it does not. when I use del mylist[:] it almost deletes everything but a few megs (just looking at the process) when I use del mylist[:] gc.collect() I would seem to return to the same amount of memory from before the list was created so.... why does mylist = [] not work??? Nothing else is referencing it as far as I can tell A: How do you measure that? I've made a small test that does not confirm your results. Here is the source: import meminfo, gc, commands page_size = int(commands.getoutput("getconf PAGESIZE")) def stat(message): s = meminfo.proc_stat() print "My memory usage %s: RSS: %dkb, VSIZE: %dkb" % ( message, s['rss']*page_size/1024, s['vsize']/1024) mylist = [] stat("before allocating a big list") for i in range(0,3000000): mylist.append('something here to take memory') stat("after allocating big list") ### uncomment one of these: mylist = [] # del mylist[:] stat("after dropping a big list") gc.collect() stat("after gc.collect()") gc.collect() stat("after second gc.collect()") gc.collect() stat("after third gc.collect()") The meminfo module used is here: http://gist.github.com/276090 These are the results with mylist=[]: My memory usage before allocating a big list: RSS: 3396kb, VSIZE: 7324kb My memory usage after allocating big list: RSS: 50700kb, VSIZE: 55084kb My memory usage after dropping a big list: RSS: 38980kb, VSIZE: 42824kb My memory usage after gc.collect(): RSS: 38980kb, VSIZE: 42824kb My memory usage after second gc.collect(): RSS: 38980kb, VSIZE: 42824kb My memory usage after third gc.collect(): RSS: 38980kb, VSIZE: 42824kb This are the results with del mylist[:]: My memory usage before allocating a big list: RSS: 3392kb, VSIZE: 7324kb My memory usage after allocating big list: RSS: 50696kb, VSIZE: 55084kb My memory usage after dropping a big list: RSS: 38976kb, VSIZE: 42824kb My memory usage after gc.collect(): RSS: 38976kb, VSIZE: 42824kb My memory usage after second gc.collect(): RSS: 38976kb, VSIZE: 42824kb My memory usage after third gc.collect(): RSS: 38976kb, VSIZE: 42824kb Python may allocate memory for its own heap, but it does not necessarily free it immediately after garbage collection.
python memory del list[:] vs list = []
In python I have noticed that if you do mylist = [] for i in range(0,100000000): mylist.append('something here to take memory') mylist = [] it would seem the second call mylist = [] would remove the reference and it would get collected but, as I watch them memory it does not. when I use del mylist[:] it almost deletes everything but a few megs (just looking at the process) when I use del mylist[:] gc.collect() I would seem to return to the same amount of memory from before the list was created so.... why does mylist = [] not work??? Nothing else is referencing it as far as I can tell
[ "How do you measure that?\nI've made a small test that does not confirm your results.\nHere is the source:\nimport meminfo, gc, commands\n\npage_size = int(commands.getoutput(\"getconf PAGESIZE\"))\n\ndef stat(message):\n s = meminfo.proc_stat()\n print \"My memory usage %s: RSS: %dkb, VSIZE: %dkb\" % (\n message, s['rss']*page_size/1024, s['vsize']/1024)\nmylist = []\n\nstat(\"before allocating a big list\")\nfor i in range(0,3000000):\n mylist.append('something here to take memory')\n\nstat(\"after allocating big list\")\n### uncomment one of these:\nmylist = []\n# del mylist[:]\nstat(\"after dropping a big list\")\ngc.collect()\nstat(\"after gc.collect()\")\ngc.collect()\nstat(\"after second gc.collect()\")\ngc.collect()\nstat(\"after third gc.collect()\")\n\nThe meminfo module used is here: http://gist.github.com/276090\nThese are the results with mylist=[]:\nMy memory usage before allocating a big list: RSS: 3396kb, VSIZE: 7324kb\nMy memory usage after allocating big list: RSS: 50700kb, VSIZE: 55084kb\nMy memory usage after dropping a big list: RSS: 38980kb, VSIZE: 42824kb\nMy memory usage after gc.collect(): RSS: 38980kb, VSIZE: 42824kb\nMy memory usage after second gc.collect(): RSS: 38980kb, VSIZE: 42824kb\nMy memory usage after third gc.collect(): RSS: 38980kb, VSIZE: 42824kb\n\nThis are the results with del mylist[:]:\nMy memory usage before allocating a big list: RSS: 3392kb, VSIZE: 7324kb\nMy memory usage after allocating big list: RSS: 50696kb, VSIZE: 55084kb\nMy memory usage after dropping a big list: RSS: 38976kb, VSIZE: 42824kb\nMy memory usage after gc.collect(): RSS: 38976kb, VSIZE: 42824kb\nMy memory usage after second gc.collect(): RSS: 38976kb, VSIZE: 42824kb\nMy memory usage after third gc.collect(): RSS: 38976kb, VSIZE: 42824kb\n\nPython may allocate memory for its own heap, but it does not necessarily free it immediately after garbage collection.\n" ]
[ 9 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0002055107_memory_python.txt