From steve at pearwood.info Tue Feb 1 00:13:30 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Feb 2011 10:13:30 +1100 Subject: [Tutor] search list with regex In-Reply-To: References: <261691.47525.qm@web130202.mail.mud.yahoo.com> Message-ID: <4D47421A.2050202@pearwood.info> Alan Gauld wrote: > > "Elwin Estle" wrote > >> parse various text files and my standard method is to >> slurp the whole thing up into a string variable, then >> break it up into a list that I can then work on > > If you read it with readlines() Python will do all of > that for you... Very true, and it's a good tool to have... but an even better tool to have in your tool box is to learn about lazy processing. Often, you don't need to slurp the whole file into one big list. Any time you can process each line independently of the others, you should consider lazy processing: read one line, process it, and move on to the next. Instead of: fp = open(filename) lines = fp.lines() # could be huge! for line in lines: process(line) this is faster and more efficient: fp = open(filename) for line in fp: process(line) It doesn't read all the lines in one go, so it can handle much bigger files. -- Steven From steve at pearwood.info Tue Feb 1 00:22:35 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Feb 2011 10:22:35 +1100 Subject: [Tutor] search list with regex In-Reply-To: <832803.30471.qm@web130207.mail.mud.yahoo.com> References: <832803.30471.qm@web130207.mail.mud.yahoo.com> Message-ID: <4D47443B.3050602@pearwood.info> Elwin Estle wrote: > Tcl's list search command has the option to search for a list element > that matches a given regex. Is there something similar in python? Not using regexes. > If not, it seems like it should be fairly trivial for me to write my > own (just wondering if I would be re-inventing the wheel). If all you want to do is match an exact string, then lists already have this: >>> ['fe', 'fi', 'fo', 'fum'].index('fo') 2 If you want to match the start of the item: def find_prefix(alist, prefix): for i, item in enumerate(alist): if item.startswith(prefix): return i raise ValueError('not found') Or match a substring: def find_substring(alist, substr): for i, item in enumerate(alist): if substr in item: return i raise ValueError('not found') If all you want is *exact* matches, these will be much faster than a regex solution. If you want case-insensitive exact matches: def find_exact(alist, target, insensitive=False): if insensitive: return alist.index(target) target = target.lower() for i, item in enumerate(alist): if item.lower() == target: return i raise ValueError('not found') To match with a regex, something like this should work: import re def find_re(alist, prefix): for i, item in enumerate(alist): if re.search(prefix, item): return i raise ValueError('not found') or use re.match to match a prefix instead. -- Steven From vic_prof at hotmail.com Tue Feb 1 01:18:46 2011 From: vic_prof at hotmail.com (Victor Binns) Date: Mon, 31 Jan 2011 19:18:46 -0500 Subject: [Tutor] Need Help in installing MySQLdb-Python Message-ID: I have Python 2.6.3 I went to the following link http://pypi.python.org/pypi/ Found - file (MySQL-python 1.2.3) clicked on file - clicked on (MySQL-python-1.2.3.tar.gz) unzipped the file in a created folder clicked on the file called setup.py following ERROR: Traceback (most recent call last): File "C:\Users\victor\Desktop\mysql-python\MySQL-python-1.2.3\setup.py", line 15, in metadata, options = get_config() File "C:\Users\victor\Desktop\mysql-python\MySQL-python-1.2.3\setup_windows.py", line 7, in get_config serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, options['registry_key']) WindowsError: [Error 2] The system cannot find the file specified I read the READ ME file I do not understand it ... I need some step by step on how to install this. ---------------------------------- What I am trying to do is create a window in which I input data which is stored and updated on MySQL. MySQL is on a paid server (Yahoo). any books or documentation or help would be greatly appreciated. Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 1 01:39:24 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Feb 2011 00:39:24 -0000 Subject: [Tutor] Need Help in installing MySQLdb-Python References: Message-ID: "Victor Binns" wrote > I have Python 2.6.3 Congratulatons SqlLite should already be installed as part of the standard library. Try: >>> import sqlite3 as sql > clicked on the file called setup.py I usually run setup manually rarther than double click... > serverKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, > > options['registry_key']) > WindowsError: [Error 2] The system cannot find the file specified > > I read the READ ME file > > I do not understand it ... :-) Try importing sqlite as above, you may find you don;t need to install anything extra! For a quick tutorial on using Sqlite from Python try the Databases topic in my tutorioal (Version 2 only for now) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From Garry.Willgoose at newcastle.edu.au Tue Feb 1 03:38:10 2011 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Tue, 01 Feb 2011 13:38:10 +1100 Subject: [Tutor] OS dependence of line separators Message-ID: <69250BAD-AE4C-4053-948C-5859F7E3D992@newcastle.edu.au> I have a code that needs to run on all platforms and generate text output files that can be read on other platforms. I'm a bit confused about how Python handles the age-old end of line character/s problem. I'm familiar with '\n' and '\r\n' dependence of Unix and Windows respectively. Also I'm familiar that the Python manual recommends that you use '\n' as the line terminator when writing a file for a file that is to read on that same platform and not to use '\r\n' explicitly on Windows. Also os.linesep gives the line terminator for your current OS even thought the manual says not to use the value when writing files. So the question is what does python do on windows when writing a text file ... does it recognise that '\n' needs to be converted to '\r\n' and substitute it as its writing. Does this mean that if I have an option in my code that sets EOL to '\r\n' (I intend to ask the user what platform he's needs to generate the file for) when I need to write to a windows file that when on a UNIX machine '\r\n' will be output in the file but when I'm on a Windows machine '\r\r\n' will be output? If so then I need to find what os.linesep and check what its value is before I set what value I give to EOL. Or is this the case where I need to set 'b' option when opening the new file ... which, ughh, requires me to explicitly convert all numbers to strings before I write them. ==================================================================== Prof Garry Willgoose, email: garry.willgoose at newcastle.edu.au; g.willgoose at telluricresearch.com email-for-life: garry.willgoose at alum.mit.edu personal webpage: www.telluricresearch.com/garry ==================================================================== "Do not go where the path may lead, go instead where there is no path and leave a trail" Ralph Waldo Emerson ==================================================================== From vic_prof at hotmail.com Tue Feb 1 06:38:13 2011 From: vic_prof at hotmail.com (Victor Binns) Date: Tue, 1 Feb 2011 00:38:13 -0500 Subject: [Tutor] Need help on Setup.py Message-ID: I have been trying to add some of the extras with python such as pywin32 and others. when i click on setup.py it does not work. I need help on the problem. Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 1 09:04:25 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Feb 2011 08:04:25 -0000 Subject: [Tutor] Need help on Setup.py References: Message-ID: "Victor Binns" wrote > I have been trying to add some of the extras with python > such as pywin32 and others. > when i click on setup.py it does not work. I need help on the > problem. "It does not work" is pretty vague, can you give more specifics? How are you running it? What error messages do you get? What is the end state - is anything installed and if so where? Also, is there a reason you are using setup.py for pywin32? That is normally installed as a binary installer. See here: http://sourceforge.net/projects/pywin32/files/pywin32/Build%20214/ There is an exe file for most Python versions... Although I just noticed that a zip file including the source seems to be the default option if you just hit the big geen button... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ladymcse2000 at gmail.com Tue Feb 1 09:44:30 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Tue, 1 Feb 2011 00:44:30 -0800 Subject: [Tutor] Formatting a string Message-ID: Quick question to the group to solve an immediate problem and then if anyone has a dead simple reference on formatting strings it would be greatly appreciated as I'm finding this to be pretty confusing. Basically, I need to format a string as an example: "He is {what}.format("{wild}") I want to insert wild in place of what and output the resulting text WITH the curly braces. This is not the actual code but is the idea of what I need to do. Thanks all, Becky -------------- next part -------------- An HTML attachment was scrubbed... URL: From tommy.kaas at kaasogmulvad.dk Tue Feb 1 09:54:17 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Tue, 1 Feb 2011 09:54:17 +0100 Subject: [Tutor] Need Help in installing MySQLdb-Python In-Reply-To: References: Message-ID: <006e01cbc1ed$9ba542a0$d2efc7e0$@kaasogmulvad.dk> Fra: tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org [mailto:tutor-bounces+tommy.kaas=kaasogmulvad.dk at python.org] P? vegne af Victor Binns Sendt: 1. februar 2011 01:19 Til: Tutor python Emne: [Tutor] Need Help in installing MySQLdb-Python I have Python 2.6.3 I went to the following link http://pypi.python.org/pypi/ Found - file (MySQL-python 1.2.3) I had similar problems last week. The windows installer file placed at this site helped. You just have to pick the right version. http://www.lfd.uci.edu/~gohlke/pythonlibs/ Tommy -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Tue Feb 1 12:33:38 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 01 Feb 2011 12:33:38 +0100 Subject: [Tutor] Formatting a string In-Reply-To: References: Message-ID: <4D47EF92.6050304@free.fr> Hello, >>> "He is {what}".format(what="{wild}") 'He is {wild}' Regards Karim On 02/01/2011 09:44 AM, Becky Mcquilling wrote: > Quick question to the group to solve an immediate problem and then if > anyone has a dead simple reference on formatting strings it would be > greatly appreciated as I'm finding this to be pretty confusing. > > Basically, I need to format a string as an example: > > " > > I want to insert wild in place of what and output the resulting text > WITH the curly braces. This is not the actual code but is the idea of > what I need to do. > > Thanks all, > > Becky > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajarncolin at gmail.com Tue Feb 1 13:29:43 2011 From: ajarncolin at gmail.com (col speed) Date: Tue, 1 Feb 2011 19:29:43 +0700 Subject: [Tutor] decimal module and precision In-Reply-To: References: <201101311426.27525.eike.welk@gmx.net> Message-ID: You can always change the precision in decimal. Just an idea.... On 31 January 2011 22:23, Richard D. Moores wrote: > > Which is accurate to only 16 digits; my Windows Vista calculator gives > 2.9231329473018093516404474158812 for 23.45**.34 > > And using mpmath with Python 2.6 does exactly as poorly: > >>> from mpmath import mp, mpf > >>> mp.dps=32;mp.pretty=True > >>> mpf(23.45)**mpf(.34) > 2.9231329473018095467750783681372 > > So it seems I shouldn't use d(), or my revised d(), or mpmath for > maximum precision, which seems to be at least 32 when using the > decimal module the standard way. > > > It would probably be a good idea, if the Python compiler would issue a > warning > > when it encounters a `float` constant with excessive precision. > > Well, it sure would have helped me! > > Thanks, Eike. > > Dick > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajarncolin at gmail.com Tue Feb 1 13:35:32 2011 From: ajarncolin at gmail.com (col speed) Date: Tue, 1 Feb 2011 19:35:32 +0700 Subject: [Tutor] Formatting a string In-Reply-To: <4D47EF92.6050304@free.fr> References: <4D47EF92.6050304@free.fr> Message-ID: You're missing a "." that if your computer is the same as mine, looks like something left behind by a mosquito On 1 February 2011 18:33, Karim wrote: > > Hello, > > >>> "He is {what}".format(what="{wild}") > 'He is {wild}' > > Regards > Karim > > > On 02/01/2011 09:44 AM, Becky Mcquilling wrote: > > Quick question to the group to solve an immediate problem and then if > anyone has a dead simple reference on formatting strings it would be greatly > appreciated as I'm finding this to be pretty confusing. > > Basically, I need to format a string as an example: > > " > > I want to insert wild in place of what and output the resulting text WITH > the curly braces. This is not the actual code but is the idea of what I > need to do. > > Thanks all, > > Becky > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Tue Feb 1 14:39:39 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 01 Feb 2011 14:39:39 +0100 Subject: [Tutor] Formatting a string In-Reply-To: References: <4D47EF92.6050304@free.fr> Message-ID: <4D480D1B.4080201@free.fr> Complete test copy & paste: karim at Requiem4Dream:~$ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> "He is {what}".format(what="{wild}") 'He is {wild}' >>> I don't get the missing "." ?! Regards Karim On 02/01/2011 01:35 PM, col speed wrote: > You're missing a "." that if your computer is the same as mine, looks > like something left behind by a mosquito > > On 1 February 2011 18:33, Karim > wrote: > > > Hello, > > >>> "He is {what}".format(what="{wild}") > 'He is {wild}' > > Regards > Karim > > > On 02/01/2011 09:44 AM, Becky Mcquilling wrote: >> Quick question to the group to solve an immediate problem and >> then if anyone has a dead simple reference on formatting strings >> it would be greatly appreciated as I'm finding this to be pretty >> confusing. >> >> Basically, I need to format a string as an example: >> >> " >> >> I want to insert wild in place of what and output the resulting >> text WITH the curly braces. This is not the actual code but is >> the idea of what I need to do. >> >> Thanks all, >> >> Becky >> >> >> _______________________________________________ >> Tutor maillist -Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Feb 1 15:40:45 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 1 Feb 2011 16:40:45 +0200 Subject: [Tutor] Need help on Setup.py In-Reply-To: References: Message-ID: Hi Victor, On 1 February 2011 07:38, Victor Binns wrote: > I have been trying to add some of the extras with python such as pywin32 > and others. > > when i click on setup.py it does not work. > > I need help on the problem. > > This is because setup.py is not intended to just be run without paramters/arguments. This is explained in the readme, which states: "'setup.py' is a standard distutils build script. You probably want to: % setup.py install or % setup.py --help As for Python itself, these extensions require MSVC7 for Python 2.4 and later, otherwise MSVC6. Some extensions require a recent "Platform SDK" from Microsoft, and in general, the latest service packs should be installed, but run 'setup.py' without any arguments to see specific information about dependencies. A vanilla MSVC installation should be able to build most extensions and list any extensions that could not be built due to missing libraries - if the build actually fails with your configuration, please log a bug via http://sourceforge.net/projects/pywin32.@ " Notice, this implies that pywin32 includes C modules..., which means that to install from pywin32 from sources you'll also need a C compiler (Microsoft Visual Studio I guess.) This is, I strongly suspect, not what you intended at all, so for PyWin32 you really want to just download a Windows .exe installer package and install that, as Alan suggested. In general, if you're installing pure Python packages (e.g. no C modules), "setup.py install" is a perfectly acceptable way to install such packages/modules. If there's native Windows intsaller packages available that's also of course fine (and probably easier for Windows users due to being more familiar.) Regards, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 1 16:08:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 1 Feb 2011 15:08:18 -0000 Subject: [Tutor] Formatting a string References: Message-ID: "Becky Mcquilling" wrote > Basically, I need to format a string as an example: > > "He is {what}.format("{wild}") > > I want to insert wild in place of what and output the resulting text > WITH > the curly braces. >>> what = 'wild' >>> "Here is {what}".format(what=what) 'Here is wild' >>> "Here is {what}".format(what='wild') 'Here is wild' >>> "Here is {{what}}".format(what='wild') 'Here is {what}' >>> "Here is {what}".format(what='{wild}') 'Here is {wild}' >>> Take your pick :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ladymcse2000 at gmail.com Tue Feb 1 18:45:10 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Tue, 1 Feb 2011 09:45:10 -0800 Subject: [Tutor] Formatting a string In-Reply-To: References: Message-ID: Thanks, as always. It all works. Becky On Tue, Feb 1, 2011 at 7:08 AM, Alan Gauld wrote: > "Becky Mcquilling" wrote > > > Basically, I need to format a string as an example: >> >> "He is {what}.format("{wild}") >> >> I want to insert wild in place of what and output the resulting text WITH >> the curly braces. >> > > what = 'wild' >>>> "Here is {what}".format(what=what) >>>> >>> 'Here is wild' > >> "Here is {what}".format(what='wild') >>>> >>> 'Here is wild' > >> "Here is {{what}}".format(what='wild') >>>> >>> 'Here is {what}' > >> "Here is {what}".format(what='{wild}') >>>> >>> 'Here is {wild}' > >> >>>> > Take your pick :-) > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrysalis_reborn at yahoo.com Tue Feb 1 22:05:10 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Tue, 1 Feb 2011 13:05:10 -0800 (PST) Subject: [Tutor] tkinter nested class question Message-ID: <373038.83721.qm@web130204.mail.mud.yahoo.com> ...at least I think it would be nested. Anyway, I have several "widget groups" that I want to create inside a frame, which is inside a class. I started to just do them with copying and pasting, and changing the values for each one (the first one is commented out, I left it in so you could see what I am after), but thought maybe I could make a class for one widget group. ...and it works, sort of. When I call the widget group class inside the main class, it shows up, but appears to be using the root window instead of the frame, which doesn't surprise me, since there is no connection between the widget group and the frame I want them to appear in. But the question is, how to make that connection? Here is the code. I want "self.rev_stuff" to show up inside self.ck_header_frame. Am I right in guessing that it has to do either with the Header_item class being an object, or I need to do something in its def __init__ ? from Tkinter import * class Header_item(object): def __init__(self, lab_text = '', lab_width = 5, ent_width = 5, grid_row = 1, grid_col = 1): self.container = Frame() self.info_label = Label(self.container, text = lab_text, width = lab_width) self.info_ent = Entry(self.container, width = ent_width) self.info_label.pack(side = 'left') self.info_ent.pack(side = 'left') self.container.grid(row = grid_row, column = grid_col) class Checksheet(Frame): def __init__(self, master, rows): rows += 2 self.ck_header_frame = Frame() self.ck_header_frame.grid(row = 1, column = 1, padx = 5, pady = 5) self.feature_block = Frame() self.feature_block.grid(row = 2, column = 1, padx = 5, pady = 5) """ self.f_rev_frame = Frame(self.ck_header_frame) self.f_rev_lab = Label(self.ck_header_frame, text = 'FORM REV:', width = 12) self.f_rev_ent = Entry(self.ck_header_frame, width = 12) self.f_rev_lab.pack(side = 'left') self.f_rev_ent.pack(side = 'left') self.f_rev_frame.grid(row = 1, column = 2) """ self.rev_stuff = Header_item(lab_text = 'FORM REV:', lab_width = 12, ent_width = 12, grid_row = 1, grid_col = 2) features_header = [] features_header.append(('NO.', 5)) features_header.append(('CofC', 5)) features_header.append(('FEATURE DESCRIPTION', 50)) features_header.append(('FREQ.', 12)) features_header.append(('GAGES', 12)) column_count = 1 self.feat_hdr = dict() self.feat_num = dict() self.feat_class = dict() self.feat_desc = dict() self.feat_freq = dict() self.feat_gages = dict() for _column, item in enumerate(features_header): _column += 1 col_name, _width = item self.feat_hdr[_column] = Label(self.feature_block, text = col_name, width = _width, relief = 'groove') self.feat_hdr[_column].grid(row = 1, column = _column) for col_name, _width in features_header: if col_name == 'NO.': for i in range(2, rows): self.feat_num[i] = Entry(self.feature_block, width = _width, relief = 'sunken') self.feat_num[i].grid(row = i, column = 1) elif col_name == 'CofC': for i in range(2, rows): self.feat_class[i] = Entry(self.feature_block, width = _width, relief = 'sunken') self.feat_class[i].grid(row = i, column = 2) elif col_name == 'FEATURE DESCRIPTION': for i in range(2, rows): self.feat_desc[i] = Entry(self.feature_block, width = _width, relief = 'sunken') self.feat_desc[i].grid(row = i, column = 3) elif col_name == 'FREQ.': for i in range(2, rows): self.feat_freq[i] = Entry(self.feature_block, width = _width, relief = 'sunken') self.feat_freq[i].grid(row = i, column = 4) elif col_name == 'GAGES': for i in range(2, rows): self.feat_gages[i] = Entry(self.feature_block, width = _width, relief = 'sunken') self.feat_gages[i].grid(row = i, column = 5) root = Tk() checksheet = Checksheet(root, 5) root.mainloop() From coolankur2006 at gmail.com Tue Feb 1 22:24:52 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Wed, 2 Feb 2011 02:54:52 +0530 Subject: [Tutor] Alternate button hit problem in tkinter Message-ID: Hey I am developing a zero-cross game from the basics of the tkinter. I want something like this- We have 4 buttons like 1 2 3 4 i want the output should change on the alternate button hit. Like inorder i hit- Button return 1 1 3 0 2 1 4 0 Basically i want to change the output of the button alternatively. like for example take this scenario- Button return 2 1 4 0 1 1 3 0 It depends on the user which button it hits first but i want the output to be different for alternate button pick. i tried to think upon this very much but unable to finally come up with any idea. Cn anyone suggest me a way out. Thanks in Advance. Ankur Aggarwal -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Feb 1 22:34:11 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 1 Feb 2011 15:34:11 -0600 Subject: [Tutor] Alternate button hit problem in tkinter In-Reply-To: References: Message-ID: On Tue, Feb 1, 2011 at 3:24 PM, ANKUR AGGARWAL wrote: > Hey > I am developing a zero-cross game from the basics of the tkinter. I want > something like this- > > We have 4 buttons like 1 2 3 4 > i want the output should change on the alternate button hit. Like inorder i > hit- > Button return > 1 1 > 3 0 > 2 1 > 4 0 > > Basically i want to change the output of the button alternatively. like for > example take this scenario- > > Button return > 2 1 > 4 0 > 1 1 > 3 0 > > It depends on the user which button it hits first but i want the output to > be different for alternate button pick. > i tried to think upon this very much but unable to finally come up with any > idea. Cn anyone suggest me a way out. > Thanks in Advance. > Ankur Aggarwal > def one_or_zero(): x = 0 while True: x = not x yield x Something like that? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bigjohnexpress at gmail.com Tue Feb 1 21:40:39 2011 From: bigjohnexpress at gmail.com (John Simon) Date: Tue, 1 Feb 2011 15:40:39 -0500 Subject: [Tutor] Composing lists from both items and other lists Message-ID: I'm looking for a way to flatten lists inside a list literal, kind of like this: >>> start = '(' >>> end = ')' >>> items = ['abc', '+', 'def'] >>> [start, *items, end] ['(', 'abc', '+', 'def', ')'] Of course, the star doesn't work there. Is there any easy, syntactically-lightweight way to get that output? Thanks, John -------------- next part -------------- An HTML attachment was scrubbed... URL: From scarolan at gmail.com Wed Feb 2 00:19:13 2011 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 1 Feb 2011 17:19:13 -0600 Subject: [Tutor] Help with range of months spanning across years Message-ID: I have a function that accepts four arguments, namely startmonth, startyear, endmonth, and endyear. For example: startmonth = 8 startyear = 2009 endmonth = 1 endyear = 2010 What would be the most straightforward way to create a list of year/month pairs from start to end? I want to end up with a list of tuples like this: mylist = [(2009, 8), (2009, 9), (2009, 10), (2009, 11), (2009, 12), (2010, 1)] From kb1pkl at aim.com Wed Feb 2 00:21:15 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 01 Feb 2011 18:21:15 -0500 Subject: [Tutor] Composing lists from both items and other lists In-Reply-To: References: Message-ID: <4D48956B.3030902@aim.com> On 02/01/2011 03:40 PM, John Simon wrote: > I'm looking for a way to flatten lists inside a list literal, kind of like > this: > >>>> start = '(' >>>> end = ')' >>>> items = ['abc', '+', 'def'] >>>> [start, *items, end] > ['(', 'abc', '+', 'def', ')'] > > Of course, the star doesn't work there. Is there any easy, > syntactically-lightweight way to get that output? > > Thanks, > John > Look into list comprehensions: http://docs.python.org/tutorial/datastructures.html#list-comprehensions You could use: [start, [item for item in items], end] But then you will have a nested list, which probably doesn't lend itself to what you want. I myself don't know how to get rid of that, maybe some of the gurus on this list know how. From andreengels at gmail.com Wed Feb 2 00:23:12 2011 From: andreengels at gmail.com (Andre Engels) Date: Wed, 2 Feb 2011 00:23:12 +0100 Subject: [Tutor] Composing lists from both items and other lists In-Reply-To: References: Message-ID: On Tue, Feb 1, 2011 at 9:40 PM, John Simon wrote: > I'm looking for a way to flatten lists inside a list literal, kind of like > this: > >>>> start = '(' >>>> end = ')' >>>> items = ['abc', '+', 'def'] >>>> [start, *items, end] > ['(', 'abc', '+', 'def', ')'] > Of course, the star doesn't work there. Is there any easy, > syntactically-lightweight way to get that output? Is: [start] + items + [end] lightweight enough? -- Andr? Engels, andreengels at gmail.com From kb1pkl at aim.com Wed Feb 2 00:39:47 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 01 Feb 2011 18:39:47 -0500 Subject: [Tutor] Composing lists from both items and other lists In-Reply-To: References: Message-ID: <4D4899C3.2060506@aim.com> On 02/01/2011 06:23 PM, Andre Engels wrote: > On Tue, Feb 1, 2011 at 9:40 PM, John Simon wrote: >> I'm looking for a way to flatten lists inside a list literal, kind of like >> this: >> >>>>> start = '(' >>>>> end = ')' >>>>> items = ['abc', '+', 'def'] >>>>> [start, *items, end] >> ['(', 'abc', '+', 'def', ')'] >> Of course, the star doesn't work there. Is there any easy, >> syntactically-lightweight way to get that output? > > Is: > > [start] + items + [end] > > lightweight enough? > That's what I was looking for. The simplest things sometimes go right over my head... Ignore my other post, but list comprehensions are a useful thing to know. From hugo.yoshi at gmail.com Wed Feb 2 01:02:17 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 2 Feb 2011 01:02:17 +0100 Subject: [Tutor] Help with range of months spanning across years In-Reply-To: References: Message-ID: On Wed, Feb 2, 2011 at 12:19 AM, Sean Carolan wrote: > I have a function that accepts four arguments, namely startmonth, > startyear, endmonth, and endyear. ?For example: > > startmonth = 8 > startyear = 2009 > endmonth = 1 > endyear = 2010 > > What would be the most straightforward way to create a list of > year/month pairs from start to end? ?I want to end up with a list of > tuples like this: > > mylist = [(2009, 8), (2009, 9), (2009, 10), (2009, 11), (2009, 12), (2010, 1)] > This sounds somewhat like homework. If it is, that's fine, mention it, and we will help you. But we won't do your homework for you, so keep that in mind. That said, you can do this rather straightforwardly with two nested for loops and the range() or xrange(), one for the year and one for the month. The only problem here is that endmonth < startmonth in some cases, like the example you gave above. In that case, you can adjust endmonth so the range function will give the right amount of months, then correct in the final output to get the right numbers. Go and code something up, try stuff out, and come back and post what you get. We'll give you tips on how to improve on it. Hugo P.S.: There is also a solution using the itertools package that is possibly more succinct, but also less clear. You can investigate if you'd like, see the documentation of the itertools.product function. From bigjohnexpress at gmail.com Wed Feb 2 01:22:17 2011 From: bigjohnexpress at gmail.com (John Simon) Date: Tue, 1 Feb 2011 19:22:17 -0500 Subject: [Tutor] Composing lists from both items and other lists Message-ID: Andre Engels gmail.com> writes > Is: > > [start] + items + [end] > > lightweight enough? Oh man, duh. I knew it was something simple. Thanks :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 2 01:58:03 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Feb 2011 00:58:03 -0000 Subject: [Tutor] tkinter nested class question References: <373038.83721.qm@web130204.mail.mud.yahoo.com> Message-ID: "Elwin Estle" wrote > from Tkinter import * > > class Header_item(object): > > def __init__(self, lab_text = '', lab_width = 5, ent_width = 5, > grid_row = 1, grid_col = 1): > self.container = Frame() You haven't specified a parent object for the Frame. I suspect the default parent will be the root object... > class Checksheet(Frame): > def __init__(self, master, rows): > rows += 2 > self.ck_header_frame = Frame() And again here Also, although you inherit from Frame you do not call its init function leaving the parent object un initialised - thats never a good idea in a GUI framework(nor in any framework for that matter) Remember that its the oparent argument that connects all the widgets together so that the event passing etc works properly. Creating parentless widgets is asking for problems and odd behaviour. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Feb 2 02:02:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Feb 2011 01:02:58 -0000 Subject: [Tutor] Alternate button hit problem in tkinter References: Message-ID: "Wayne Werner" wrote > def one_or_zero(): > x = 0 > while True: > x = not x > yield x In case its not obvious how this iis used in a GUI context... So for your exampler crweate a state variable somewhere in your GUI (x in Waynes example) and toggle its value from your button handler and return the result. The easiest way to do that is to use a single function, like Wayne's, and call it from all of your handlers. HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Feb 2 02:07:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Feb 2011 01:07:17 -0000 Subject: [Tutor] Help with range of months spanning across years References: Message-ID: "Hugo Arts" wrote >> What would be the most straightforward way to create a list of >> year/month pairs from start to end? I want to end up with a list of >> tuples like this: >> >> mylist = [(2009, 8), (2009, 9), (2009, 10), (2009, 11), (2009, 12), >> (2010, 1)] >> > That said, you can do this rather straightforwardly with two nested > for loops and the range() or xrange(), one for the year and one for > the month. Or if you want to be able to use it across historic times (taking account of calendar irregularities etc) then you can get the data from the datetime module... It just depends how open ended your lists need to be. For months and years you are probably ok with a simple loop approach as Hugo suggests, but if you ever need to go to days or weeks then datetime would be safer.. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From chrysalis_reborn at yahoo.com Wed Feb 2 02:14:55 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Tue, 1 Feb 2011 17:14:55 -0800 (PST) Subject: [Tutor] Help with range of months spanning across years In-Reply-To: Message-ID: <917795.16981.qm@web130202.mail.mud.yahoo.com> --- On Tue, 2/1/11, Sean Carolan wrote: > From: Sean Carolan > Subject: [Tutor] Help with range of months spanning across years > To: Tutor at python.org > Date: Tuesday, February 1, 2011, 6:19 PM > I have a function that accepts four > arguments, namely startmonth, > startyear, endmonth, and endyear.? For example: > > startmonth = 8 > startyear = 2009 > endmonth = 1 > endyear = 2010 > > What would be the most straightforward way to create a list > of > year/month pairs from start to end?? I want to end up > with a list of > tuples like this: > > mylist = [(2009, 8), (2009, 9), (2009, 10), (2009, 11), > (2009, 12), (2010, 1)] --- On Tue, 2/1/11, Sean Carolan wrote: > From: Sean Carolan > Subject: [Tutor] Help with range of months spanning across years > To: Tutor at python.org > Date: Tuesday, February 1, 2011, 6:19 PM > I have a function that accepts four > arguments, namely startmonth, > startyear, endmonth, and endyear. For example: > > startmonth = 8 > startyear = 2009 > endmonth = 1 > endyear = 2010 > > What would be the most straightforward way to create a list > of > year/month pairs from start to end? I want to end up > with a list of > tuples like this: > > mylist = [(2009, 8), (2009, 9), (2009, 10), (2009, 11), > (2009, 12), (2010, 1)] Well, I noticed someone else's reply to this, about it potentially being homework, so I won't post any code. I tinkered with your problem and have a solution, but I didn't use nested for loops as someone else suggested. My solution works, so long as the end year isn't the same as the start year, tho with a bit of fiddling, one could add some conditional code to take care of that. I would suggest thinking about the situation with the first year/month pair in the date range, and the last year/date...vs any years in the middle. What is different? What is the same? From ian.douglas at iandouglas.com Wed Feb 2 02:30:22 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Tue, 01 Feb 2011 17:30:22 -0800 Subject: [Tutor] Help with range of months spanning across years In-Reply-To: <917795.16981.qm@web130202.mail.mud.yahoo.com> References: <917795.16981.qm@web130202.mail.mud.yahoo.com> Message-ID: <4D48B3AE.5070803@iandouglas.com> It bugs me that so many people are quick to jump on the "we wont' do your homework" bandwagon -- I was accused of the same thing when I posted a question to the list myself. I've been programming professionally for many years but learning Python in my spare time... I sent this reply to Sean privately, but frankly I'm so annoyed at the 'homework' replies, I figured I'd just post it here. I'm still very junior to Python, but this seems to work for me using recursion. I'm sure there's a much more elegant way of doing this, but like I said, I'm still pretty new to the language. def makelist(startmonth,startyear,endmonth,endyear): mylist = [] if (startyear == endyear): for month in range (startmonth,endmonth+1): mylist += [(startyear,month)] else: for month in range (startmonth,13): mylist += [(startyear,month)] mylist += makelist(1,startyear+1, endmonth, endyear) return mylist ; print makelist(8,2009,1,2010) I'd love to hear any replies from the experts on the list on how to make this more efficient in Python 'cause I'm still learning myself. On 02/01/2011 05:14 PM, Elwin Estle wrote: > --- On Tue, 2/1/11, Sean Carolan wrote: > >> What would be the most straightforward way to create a list >> of >> year/month pairs from start to end? I want to end up >> with a list of >> tuples like this: >> >> mylist = [(2009, 8), (2009, 9), (2009, 10), (2009, 11), >> (2009, 12), (2010, 1)] -------------- next part -------------- An HTML attachment was scrubbed... URL: From scarolan at gmail.com Wed Feb 2 02:55:20 2011 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 1 Feb 2011 19:55:20 -0600 Subject: [Tutor] Help with range of months spanning across years In-Reply-To: References: Message-ID: > This sounds somewhat like homework. If it is, that's fine, mention it, > and we will help you. But we won't do your homework for you, so keep > that in mind. A reasonable assumption but this is actually going in a cgi tool that I'm using at work. The input comes from pull-down menus on a web page. Here's what I came up with, feel free to give suggestions on how this might be made more efficient: if startyear > endyear or (startyear == endyear and startmonth > endmonth): print 'Your start date must be earlier than the end date.' else: datelist = [] month = startmonth year = startyear while month != endmonth or year != endyear: datelist.append((year, month)) if month == 12: month = 1 year += 1 else: month += 1 datelist.append((year, month)) print datelist I was hoping there was some whiz-bang function that would just iterate through months if it was fed a start and end date. Can datetime or calendar do this? From hugo.yoshi at gmail.com Wed Feb 2 03:55:25 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 2 Feb 2011 03:55:25 +0100 Subject: [Tutor] Help with range of months spanning across years In-Reply-To: <4D48B3AE.5070803@iandouglas.com> References: <917795.16981.qm@web130202.mail.mud.yahoo.com> <4D48B3AE.5070803@iandouglas.com> Message-ID: On Wed, Feb 2, 2011 at 2:30 AM, ian douglas wrote: > It bugs me that so many people are quick to jump on the "we wont' do your > homework" bandwagon -- I was accused of the same thing when I posted a > question to the list myself. I've been programming professionally for many > years but learning Python in my spare time... I sent this reply to Sean > privately, but frankly I'm so annoyed at the 'homework' replies, I figured > I'd just post it here. > Okay, this has gotten rather long, but I'll post it anyway because I think the "we won't do your homework" response is valid and there's good reasoning behind it. It's not just homework. The thing is, the point of this list is to teach people how to program (in general, but in python specifically). When someone posts a question, responding with a lump of code and a crisp "This is how you do it" just isn't a very effective teaching method. More of the equivalent of giving a man a fish, as in the old saying. Another point, mentioned in Eric Raymond's "How to ask questions the smart way"[1], is that I generally dislike answering questions for people who don't appear to have put in any work in solving the problem themselves. It leaves us with little options to give pointers, and we're stuck with the lump of code mentioned above, or a few vague hints as to how to approach the problem. This isn't a place that solves your coding problems for free. But I'm happy to help you learn python. For those reasons, I *never* give out a straight answer, especially not to someone who doesn't show their own attempts. In those cases, I will tell them that I won't and why, give them some hints, and encourage them to try some things on their own and get back here, at which point we can help them further. That's what tutoring is all about after all. So, in short, we're not "accusing" you of trying to make us do your homework, and we're certainly not dismissing your questions. We're simply saying "show us what you have, and we'll give you tips. if you're totally at a loss, try doing so-and-so, or look at this and that documentation." [1]: http://www.catb.org/~esr/faqs/smart-questions.html, everybody should read this before posting to a mailing list, imho. > I'm still very junior to Python, but this seems to work for me using > recursion. I'm sure there's a much more elegant way of doing this, but like > I said, I'm still pretty new to the language. > > def makelist(startmonth,startyear,endmonth,endyear): > ??? mylist = [] > ??? if (startyear == endyear): > ??? ??? for month in range (startmonth,endmonth+1): > ??? ??? ??? mylist += [(startyear,month)] > ??? else: > ??? ??? for month in range (startmonth,13): > ??? ??? ??? mylist += [(startyear,month)] > ??? ??? mylist += makelist(1,startyear+1, endmonth, endyear) > ??? return mylist ; > > print makelist(8,2009,1,2010) > > I'd love to hear any replies from the experts on the list on how to make > this more efficient in Python 'cause I'm still learning myself. > Your solution feels rather lispy to me. I really like that. I actually had a simple iterative solution in mind when I wrote that first post, but while trying to write it now I'm running into some complications I hadn't considered before, mea culpa (I'm such a good armchair programmer ) In any case, you can replace the for loops with a list comprehensions, and factor them out into a single one since they're so similar. Let me write it out: def datelist(startyear, startmonth, endyear, endmonth): em = endmonth + 1 if startyear == endyear else 13 dates = [(startyear, m) for m in range(startmonth, em)] if startyear < endyear: dates += datelist(startyear + 1, 1, endyear, endmonth) return dates >>> print(datelist(2008, 8, 2009, 1)) [(2008, 8), (2008, 9), (2008, 10), (2008, 11), (2008, 12), (2009, 1)] Hugo From hugo.yoshi at gmail.com Wed Feb 2 04:11:52 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 2 Feb 2011 04:11:52 +0100 Subject: [Tutor] Help with range of months spanning across years In-Reply-To: References: Message-ID: On Wed, Feb 2, 2011 at 2:55 AM, Sean Carolan wrote: >> This sounds somewhat like homework. If it is, that's fine, mention it, >> and we will help you. But we won't do your homework for you, so keep >> that in mind. > > A reasonable assumption but this is actually going in a cgi tool that > I'm using at work. ?The input comes from pull-down menus on a web > page. I apologize for assuming homework. It's the tutor list, and I try to focus on effective teaching more than anything. No offense was meant. > Here's what I came up with, feel free to give suggestions on how this > might be made more efficient: > > [snip code] > > I was hoping there was some whiz-bang function that would just iterate > through months if it was fed a start and end date. ?Can datetime or > calendar do this? As far as I can tell from quickly going through documentation, no. At least, not with a quick and easy function. datetime can represent the dates just fine, and you can add days to that until you hit your end date, but adding months is harder. timedelta can't represent a month, which makes sense since they're not of constant length anyway. So using datetime is not really your best option. Calendar is more about displaying than doing calculations, making it even less useful. You can use your code or ian's (or my modification of ian's code) to your taste, I don't expect any measurable difference in efficiency. If it's really important, *measure*. But I suspect it isn't, unless you'll run it either on time spans of thousands of years or if it will be used by thousands of people at a time. Hugo From scarolan at gmail.com Wed Feb 2 05:00:29 2011 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 1 Feb 2011 22:00:29 -0600 Subject: [Tutor] Help with range of months spanning across years In-Reply-To: References: Message-ID: > As far as I can tell from quickly going through documentation, no. At > least, not with a quick and easy function. datetime can represent the > dates just fine, and you can add days to that until you hit your end > date, but adding months is harder. timedelta can't represent a month, > which makes sense since they're not of constant length anyway. So > using datetime is not really your best option. Calendar is more about > displaying than doing calculations, making it even less useful. Thank you, this is useful information. > > You can use your code or ian's (or my modification of ian's code) to > your taste, I don't expect any measurable difference in efficiency. If > it's really important, *measure*. But I suspect it isn't, unless > you'll run it either on time spans of thousands of years or if it will > be used by thousands of people at a time. Yes, the code runs quickly enough for our needs. Thanks again for the helpful suggestions. From rdmoores at gmail.com Wed Feb 2 05:33:38 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 1 Feb 2011 20:33:38 -0800 Subject: [Tutor] decimal module and precision In-Reply-To: References: <201101311426.27525.eike.welk@gmx.net> Message-ID: On Tue, Feb 1, 2011 at 04:29, col speed wrote: > > You can always change the precision in decimal. Just an idea.... Not exactly sure what you mean. But I just tried using decimal to get 123.2345274523452345235432452345 ** 2.3 to 300 digits: >>> from decimal import Decimal as D >>> import decimal >>> decimal.getcontext().prec =300 >>> D('123.2345274523452345235432452345')**D('2.3') Decimal('64370.1512280246915272663511041234541758816386398199132394466583175597615075198590980955633694480202503045760664137267271735342845242951082979103782026356856312125096217781701992298765824436994198599115081342290327111836807693742546891271393004992808057677786573779518236419674381269758803681315430784') >>> len('64370.1512280246915272663511041234541758816386398199132394466583175597615075198590980955633694480202503045760664137267271735342845242951082979103782026356856312125096217781701992298765824436994198599115081342290327111836807693742546891271393004992808057677786573779518236419674381269758803681315430784') 301 >>> I also did this on WolframAlpha.com (except the len) and found that decimal and WA agree exactly! (I had come to believe that setting decimal.getcontext().prec to n meant that the result would be in n digits, but that the accuracy would be much less, for large n.) Here's a screen shot of the WA result: . The decimal module output ends with '15430784'; The 6th line of the WA output begins with "154307841' I also tried the same calculation with decimal.getcontext().prec =1840. WA's and decimal's results agreed exactly. Dick From ramjaju.mail at gmail.com Wed Feb 2 16:15:22 2011 From: ramjaju.mail at gmail.com (Sriram Jaju) Date: Wed, 2 Feb 2011 20:45:22 +0530 Subject: [Tutor] Need help on Setup.py Message-ID: What is pywin32 ? I mean what is its use ? -- Xcited 2 be Alive....Sriram -------------- next part -------------- An HTML attachment was scrubbed... URL: From duretn at bellsouth.net Wed Feb 2 16:44:17 2011 From: duretn at bellsouth.net (Nevins Duret) Date: Wed, 02 Feb 2011 10:44:17 -0500 Subject: [Tutor] Tutor Digest, Vol 84, Issue 8 In-Reply-To: References: Message-ID: <4D497BD1.4060904@bellsouth.net> On 02/02/2011 06:00 AM, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Help with range of months spanning across years (Hugo Arts) > 2. Re: Help with range of months spanning across years (Hugo Arts) > 3. Re: Help with range of months spanning across years (Sean Carolan) > 4. Re: decimal module and precision (Richard D. Moores) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 2 Feb 2011 03:55:25 +0100 > From: Hugo Arts > To: ian douglas > Cc: Tutor at python.org > Subject: Re: [Tutor] Help with range of months spanning across years > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > On Wed, Feb 2, 2011 at 2:30 AM, ian douglas wrote: >> It bugs me that so many people are quick to jump on the "we wont' do your >> homework" bandwagon -- I was accused of the same thing when I posted a >> question to the list myself. I've been programming professionally for many >> years but learning Python in my spare time... I sent this reply to Sean >> privately, but frankly I'm so annoyed at the 'homework' replies, I figured >> I'd just post it here. >> > Okay, this has gotten rather long, but I'll post it anyway because I > think the "we won't do your homework" response is valid and there's > good reasoning behind it. > > It's not just homework. The thing is, the point of this list is to > teach people how to program (in general, but in python specifically). > When someone posts a question, responding with a lump of code and a > crisp "This is how you do it" just isn't a very effective teaching > method. More of the equivalent of giving a man a fish, as in the old > saying. > > Another point, mentioned in Eric Raymond's "How to ask questions the > smart way"[1], is that I generally dislike answering questions for > people who don't appear to have put in any work in solving the problem > themselves. It leaves us with little options to give pointers, and > we're stuck with the lump of code mentioned above, or a few vague > hints as to how to approach the problem. > > This isn't a place that solves your coding problems for free. But I'm > happy to help you learn python. For those reasons, I *never* give out > a straight answer, especially not to someone who doesn't show their > own attempts. In those cases, I will tell them that I won't and why, > give them some hints, and encourage them to try some things on their > own and get back here, at which point we can help them further. That's > what tutoring is all about after all. > > So, in short, we're not "accusing" you of trying to make us do your > homework, and we're certainly not dismissing your questions. We're > simply saying "show us what you have, and we'll give you tips. if > you're totally at a loss, try doing so-and-so, or look at this and > that documentation." > > [1]: http://www.catb.org/~esr/faqs/smart-questions.html, everybody > should read this before posting to a mailing list, imho. > >> I'm still very junior to Python, but this seems to work for me using >> recursion. I'm sure there's a much more elegant way of doing this, but like >> I said, I'm still pretty new to the language. >> >> def makelist(startmonth,startyear,endmonth,endyear): >> ??? mylist = [] >> ??? if (startyear == endyear): >> ??? ??? for month in range (startmonth,endmonth+1): >> ??? ??? ??? mylist += [(startyear,month)] >> ??? else: >> ??? ??? for month in range (startmonth,13): >> ??? ??? ??? mylist += [(startyear,month)] >> ??? ??? mylist += makelist(1,startyear+1, endmonth, endyear) >> ??? return mylist ; >> >> print makelist(8,2009,1,2010) >> >> I'd love to hear any replies from the experts on the list on how to make >> this more efficient in Python 'cause I'm still learning myself. >> > Your solution feels rather lispy to me. I really like that. I actually > had a simple iterative solution in mind when I wrote that first post, > but while trying to write it now I'm running into some complications I > hadn't considered before, mea culpa (I'm such a good armchair > programmer) > > In any case, you can replace the for loops with a list comprehensions, > and factor them out into a single one since they're so similar. Let me > write it out: > > def datelist(startyear, startmonth, endyear, endmonth): > em = endmonth + 1 if startyear == endyear else 13 > dates = [(startyear, m) for m in range(startmonth, em)] > if startyear< endyear: > dates += datelist(startyear + 1, 1, endyear, endmonth) > return dates > >>>> print(datelist(2008, 8, 2009, 1)) > [(2008, 8), (2008, 9), (2008, 10), (2008, 11), (2008, 12), (2009, 1)] > > Hugo > > > ------------------------------ > > Message: 2 > Date: Wed, 2 Feb 2011 04:11:52 +0100 > From: Hugo Arts > To: Sean Carolan > Cc: Tutor at python.org > Subject: Re: [Tutor] Help with range of months spanning across years > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > On Wed, Feb 2, 2011 at 2:55 AM, Sean Carolan wrote: >>> This sounds somewhat like homework. If it is, that's fine, mention it, >>> and we will help you. But we won't do your homework for you, so keep >>> that in mind. >> A reasonable assumption but this is actually going in a cgi tool that >> I'm using at work. ?The input comes from pull-down menus on a web >> page. > I apologize for assuming homework. It's the tutor list, and I try to > focus on effective teaching more than anything. No offense was meant. > >> Here's what I came up with, feel free to give suggestions on how this >> might be made more efficient: >> >> [snip code] >> >> I was hoping there was some whiz-bang function that would just iterate >> through months if it was fed a start and end date. ?Can datetime or >> calendar do this? > As far as I can tell from quickly going through documentation, no. At > least, not with a quick and easy function. datetime can represent the > dates just fine, and you can add days to that until you hit your end > date, but adding months is harder. timedelta can't represent a month, > which makes sense since they're not of constant length anyway. So > using datetime is not really your best option. Calendar is more about > displaying than doing calculations, making it even less useful. > > You can use your code or ian's (or my modification of ian's code) to > your taste, I don't expect any measurable difference in efficiency. If > it's really important, *measure*. But I suspect it isn't, unless > you'll run it either on time spans of thousands of years or if it will > be used by thousands of people at a time. > > Hugo > > > ------------------------------ > > Message: 3 > Date: Tue, 1 Feb 2011 22:00:29 -0600 > From: Sean Carolan > To: Hugo Arts > Cc: Tutor at python.org > Subject: Re: [Tutor] Help with range of months spanning across years > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > >> As far as I can tell from quickly going through documentation, no. At >> least, not with a quick and easy function. datetime can represent the >> dates just fine, and you can add days to that until you hit your end >> date, but adding months is harder. timedelta can't represent a month, >> which makes sense since they're not of constant length anyway. So >> using datetime is not really your best option. Calendar is more about >> displaying than doing calculations, making it even less useful. > Thank you, this is useful information. > >> You can use your code or ian's (or my modification of ian's code) to >> your taste, I don't expect any measurable difference in efficiency. If >> it's really important, *measure*. But I suspect it isn't, unless >> you'll run it either on time spans of thousands of years or if it will >> be used by thousands of people at a time. > Yes, the code runs quickly enough for our needs. Thanks again for the > helpful suggestions. > > > ------------------------------ > > Message: 4 > Date: Tue, 1 Feb 2011 20:33:38 -0800 > From: "Richard D. Moores" > To: col speed > Cc: Eike Welk, tutor at python.org > Subject: Re: [Tutor] decimal module and precision > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > On Tue, Feb 1, 2011 at 04:29, col speed wrote: >> You can always change the precision in decimal. Just an idea.... > Not exactly sure what you mean. But I just tried using decimal to get > 123.2345274523452345235432452345 ** 2.3 to 300 digits: > >>>> from decimal import Decimal as D >>>> import decimal >>>> decimal.getcontext().prec =300 >>>> D('123.2345274523452345235432452345')**D('2.3') > Decimal('64370.1512280246915272663511041234541758816386398199132394466583175597615075198590980955633694480202503045760664137267271735342845242951082979103782026356856312125096217781701992298765824436994198599115081342290327111836807693742546891271393004992808057677786573779518236419674381269758803681315430784') >>>> len('64370.1512280246915272663511041234541758816386398199132394466583175597615075198590980955633694480202503045760664137267271735342845242951082979103782026356856312125096217781701992298765824436994198599115081342290327111836807693742546891271393004992808057677786573779518236419674381269758803681315430784') > 301 > I also did this on WolframAlpha.com (except the len) and found that > decimal and WA agree exactly! (I had come to believe that setting > decimal.getcontext().prec to n meant that the result would be in n > digits, but that the accuracy would be much less, for large n.) > > Here's a screen shot of the WA result: > > . > > The decimal module output ends with '15430784'; The 6th line of the WA > output begins with "154307841' > > I also tried the same calculation with decimal.getcontext().prec > =1840. WA's and decimal's results agreed exactly. > > Dick > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 84, Issue 8 > ************************************ > Hello Python Collective, I would have to agree with you Ian. Coming from an art then computer animation visual effects background, it's not until recently that it became evident to me that in order to push the potential of this medium, I would definitely have to learn to code. I think the stigma of the "homework bandwagon" comes from the very nature of coding and it's secretive and cryptic undertones, it's something very personal in the sense that, although there is usually more than 1 way to solve a problem, there's always "THE MOST" and more efficient way IMHO, that some people are just not willing to share. And, of course, this most efficient way utilizes less memory and resources. This is why I always feel apprehensive to post so I purchased many books on python, and until I've gone through them and feel competent enough to post, then I'll post, which to me does no good. Thank you for your insight, it makes me feel a little bet more human and inspires me not to give up. Best Regards, Nevins Duret From malaclypse2 at gmail.com Wed Feb 2 17:53:31 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 2 Feb 2011 11:53:31 -0500 Subject: [Tutor] Homework and the Tutor list Message-ID: > ? ?I would have to agree with you Ian. ?Coming from an art then computer > animation visual effects background, it's not until recently that it became > evident to me that in order to push the potential of this medium, I would > definitely have to learn to code. ?I think the stigma of the "homework > bandwagon" comes from the very nature of coding and it's secretive and > cryptic undertones, it's something very personal in the sense that, although > there is usually more than 1 way to solve a problem, there's always "THE > MOST" and more efficient way IMHO, that some people are just not willing to > share. And, of course, this most efficient way utilizes less memory and > resources. ?This is why I always feel apprehensive to post so I purchased > many books on python, and until I've gone through them and feel competent > enough to post, then I'll post, which to me does no good. ?Thank you for > your insight, it makes me feel a little bet more human and inspires me not > to give up. I don't think that's true at all. I think people here are happy to help, including by posting working, efficient, code. What we try to avoid is having students come here with their assignments and have us do their schoolwork for them. I'm not sure how long you've been subscribed to the list, but this happens on a regular basis. If you're concerned that people will think you're looking for help with homework, just tell us up front that it's not a homework problem. If it *is* a homework problem, tell us that up front too, and people will still be happy to help, though less likely to post working code, and more likely to try and work with you to get you to figure out the solution on your own. In all cases, you are most likely to get useful help if you do a couple of things: Tell us what you're trying to accomplish and why, as clearly as you can. Post some code that tries to solve the problem, but doesn't work right. Ideally, post code that is self contained (so that other people can run it too), along with any error messages (including the full stack trace, if one is generated), and what your desired result is. Try to give us the big picture of what you're doing, as well as the details of the problem you're having. Sometimes we can point you to an entirely different approach that will work better. -- Jerry From ranceh at gmail.com Wed Feb 2 18:17:44 2011 From: ranceh at gmail.com (Rance Hall) Date: Wed, 2 Feb 2011 11:17:44 -0600 Subject: [Tutor] Homework and the Tutor list In-Reply-To: References: Message-ID: On Wed, Feb 2, 2011 at 10:53 AM, Jerry Hill wrote: > > I don't think that's true at all. ?I think people here are happy to > help, including by posting working, efficient, code. ?What we try to > avoid is having students come here with their assignments and have us > do their schoolwork for them. ?I'm not sure how long you've been > subscribed to the list, but this happens on a regular basis. > -- > Jerry I can't agree with Jerry's comments more, and I have been the benefactor of both sides of this unwritten rule. As a student, I came to discussion forums like this one with homework questions hoping for an easy answer, and didn't get one. Now that I am a college professor I'm quite glad I didn't get an easy answer, and I appreciate even more now the fact that forums like this one know a homework problem from a real one, and work to teach more than normal when it is needed. I haven't been involved with python long, and I had an abrupt start on this list as my first question question was not written with the protocol I normally use, I had not taken time off and gotten away from my frustrations and taken the time to write a clear concise non-judgmental question. The rest of this list chastised me, and still helped me. I deserved the critical words, and did not deserve the help. I got both. Thanks go to the long time readers and contributors of this list who have made it something valuable, and I hope that some day soon those of us who are still learning, will be able to begin to meaningfully contribute. From tom at advm2.com Wed Feb 2 15:51:24 2011 From: tom at advm2.com (Tom Brauch) Date: Wed, 2 Feb 2011 07:51:24 -0700 Subject: [Tutor] Defining Exceptions Message-ID: All, I am a python neophyte and not terrible well versed in programming (as will become obvious shortly) I have a script which is reading a serial device on a schedule. The device outputs a header at the beginning of every read. I have a data file which I am appending and would like to eliminate the header so that I end up with one master data file. A copy of the serial readout is: * > 6CSV Type Reports2 - Display All Data3 - Display New Data4 - Display Last Data5 - Display All Flow Stats6 - Display New Flow Stats7 - Display All 5-Min Flow8 - Display New 5-Min Flow9 - Display Error Log> 4 - Display CSV DataStation, 1Time,Conc(mg/m3),Qtot(m3),no(V),WS(MPS),no(V),RH(%),no(V),AT(C),E,U,M,I,L,R,N,F,P,D,C,T,02/02/11 08:00, 0.042, 0.701, 0.004, 0.1, 0.002, 7, 0.012, -18.0,0,0,0,0,0,0,0,0,0,0,0,0, I am only interested in the information following the T, in the header. I have tried to use an exception to have the script throw out all data prior to the T, in the header but I don't know how to define this excecption. My current script looks as follows: def cycle(ser,prefix): inRecovery=False resp=False # tm.sleep(30.0) ser.open() tm.sleep(2) ser.write('\n\r\n\r\n\r') resp=buffer_read(ser) ser.write('6') resp=buffer_read(ser) ser.write('3') resp=buffer_read(ser) lines = resp.split('\r\n') waste=lines.pop() while True: try: lines.remove(waste) except Exception: ?????? for x,row in enumerate(lines): lines[x]=row.split(',') if DEBUG: print lines f=open(prefix,'a') csvf = csv.writer(f) csvf.writerows(lines) f.close() ser.close() How do I define the exception so that I get only the data following the header? Thanks! Tomb -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Feb 2 18:58:58 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 02 Feb 2011 09:58:58 -0800 Subject: [Tutor] Defining Exceptions In-Reply-To: References: Message-ID: On 2/2/2011 6:51 AM Tom Brauch said... > All, > > I am a python neophyte and not terrible well versed in programming (as will > become obvious shortly) > > I have a script which is reading a serial device on a schedule. The device > outputs a header at the beginning of every read. I have a data file which I > am appending and would like to eliminate the header so that I end up with > one master data file. A copy of the serial readout is: > > * >> > 6CSV Type Reports2 - Display All Data3 - Display New Data4 - Display Last > Data5 - Display All Flow Stats6 - Display New Flow Stats7 - Display All > 5-Min Flow8 - Display New 5-Min Flow9 - Display Error Log> > 4 - Display CSV DataStation, > 1Time,Conc(mg/m3),Qtot(m3),no(V),WS(MPS),no(V),RH(%),no(V),AT(C),E,U,M,I,L,R,N,F,P,D,C,T,02/02/11 > 08:00, 0.042, 0.701, 0.004, 0.1, 0.002, 7, 0.012, > -18.0,0,0,0,0,0,0,0,0,0,0,0,0, > > I am only interested in the information following the T, in the header. I > have tried to use an exception to have the script throw out all data prior > to the T, in the header but I don't know how to define this excecption. My > current script looks as follows: > > def cycle(ser,prefix): > inRecovery=False > resp=False > # tm.sleep(30.0) > ser.open() > tm.sleep(2) > ser.write('\n\r\n\r\n\r') > resp=buffer_read(ser) > > ser.write('6') > resp=buffer_read(ser) > > ser.write('3') > resp=buffer_read(ser) > lines = resp.split('\r\n') > waste=lines.pop() pop changes lines by discarding the end of the list. So your subsequent remove fails because waste is no longer in the list. Perhaps waste is the data you're looking for? sprinkle some prints through here so you can see what values you're dealing with. That's a common technique to help figure out what's wrong. HTH, Emile > while True: > try: > lines.remove(waste) > except Exception: > ?????? > for x,row in enumerate(lines): > lines[x]=row.split(',') > if DEBUG: print lines > f=open(prefix,'a') > csvf = csv.writer(f) > csvf.writerows(lines) > f.close() > ser.close() > > How do I define the exception so that I get only the data following the > header? > > Thanks! > Tomb > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Wed Feb 2 19:30:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Feb 2011 18:30:05 -0000 Subject: [Tutor] Need help on Setup.py References: Message-ID: "Sriram Jaju" wrote > What is pywin32 ? > I mean what is its use ? It is a set of Python modules that gives access to the Windows API, including COM functions. Using it you can create native Windows GUIs from Python or, more usefully, integrate with Windows Operating System features and other Windows programs like Powerpoint or Outlook. It's pretty much essential if you want to interact with Windows at the OS level. (Although ctypes can also be used nowadays with a little bit extra effort) pywin also includes the PythonWin IDE - a Windows specific tool similar to IDLE (but much better). More details on the pywin web site. Also the author has an O'Reilly book (Python Programming on Win32) which covers many pywin features. HTH, Alan G. From davidheiserca at gmail.com Wed Feb 2 19:44:23 2011 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Wed, 2 Feb 2011 10:44:23 -0800 Subject: [Tutor] Defining Exceptions References: Message-ID: <68F2E6FFB080447B9AA55C2696696F5A@dheiser> It's difficult to see exactly what the data looks like as it is received. Where are the line breaks? At the commas? Is the "header" just the first line? Is "1Time" considered part of the header? Is everything after "1Time" considered "data"? I can see several simple alternatives to your method. I don't think you need the exception code. I think you can replace this: lines = resp.split('\r\n') waste=lines.pop() while True: try: lines.remove(waste) except Exception: ?????? with this: lines = resp.splitlines[:2] This part, I don't understand: for x,row in enumerate(lines): lines[x]=row.split(',') ----- Original Message ----- From: Tom Brauch To: tutor at python.org Sent: Wednesday, February 02, 2011 6:51 AM Subject: [Tutor] Defining Exceptions All, I am a python neophyte and not terrible well versed in programming (as will become obvious shortly) I have a script which is reading a serial device on a schedule. The device outputs a header at the beginning of every read. I have a data file which I am appending and would like to eliminate the header so that I end up with one master data file. A copy of the serial readout is: * > 6CSV Type Reports2 - Display All Data3 - Display New Data4 - Display Last Data5 - Display All Flow Stats6 - Display New Flow Stats7 - Display All 5-Min Flow8 - Display New 5-Min Flow9 - Display Error Log> 4 - Display CSV DataStation, 1Time,Conc(mg/m3),Qtot(m3),no(V),WS(MPS),no(V),RH(%),no(V),AT(C),E,U,M,I,L,R,N,F,P,D,C,T,02/02/11 08:00, 0.042, 0.701, 0.004, 0.1, 0.002, 7, 0.012, -18.0,0,0,0,0,0,0,0,0,0,0,0,0, I am only interested in the information following the T, in the header. I have tried to use an exception to have the script throw out all data prior to the T, in the header but I don't know how to define this excecption. My current script looks as follows: def cycle(ser,prefix): inRecovery=False resp=False # tm.sleep(30.0) ser.open() tm.sleep(2) ser.write('\n\r\n\r\n\r') resp=buffer_read(ser) ser.write('6') resp=buffer_read(ser) ser.write('3') resp=buffer_read(ser) lines = resp.split('\r\n') waste=lines.pop() while True: try: lines.remove(waste) except Exception: ?????? for x,row in enumerate(lines): lines[x]=row.split(',') if DEBUG: print lines f=open(prefix,'a') csvf = csv.writer(f) csvf.writerows(lines) f.close() ser.close() How do I define the exception so that I get only the data following the header? Thanks! Tomb ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 2 19:50:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 2 Feb 2011 18:50:37 -0000 Subject: [Tutor] Homework was: Re: Tutor Digest, Vol 84, Issue 8 References: <4D497BD1.4060904@bellsouth.net> Message-ID: Please do not send the entire digest message, As the instructions say below: "Nevins Duret" wrote >> Send Tutor mailing list submissions to >> tutor at python.org >> .... >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." >> And also edit out the messages that are not relevant to your reply. It saves a lot of frustration on the part of your readers. >> On Wed, Feb 2, 2011 at 2:30 AM, ian >> douglas wrote: >>> It bugs me that so many people are quick to jump on the "we wont' >>> do your >>> homework" bandwagon > ..., I would definitely have to learn to code. I think the stigma > of the "homework bandwagon" comes from the very nature of coding and > it's secretive and cryptic undertones, Nope, it comes from the high number of requests we get on the list from students who suddenly discover they have an assignment due and think they can post the assignment here and get somebody on the list to do it for them. Doing so is a waste of contributers time and does not help the student learn anything. This is why we have the policy. If students (or any other newbie) have made a decent stab at solving the problem we are more than happy to resolve specific issues and to suggest different strategies. Coding has no "secretive and cryptic" undertones in my experience it is simply a branch of mathematics and shares much of the same approaches to learning that traditional math does. ie. Lots of examples which you need to work through yourself before you can understand it. > sense that, although there is usually more than 1 way to solve a > problem, there's always "THE MOST" and more efficient way IMHO, that > some people are just not willing to share. There is very rarely a single most efficient way. And much of what is good in programming is subjective. How much do we bias towards readability versus sheer speed? It depends on the exact circumstances, and that's rarely clear on a mailing list. The good news is that it very rarely matters as much as posters think it does! ;-) > efficient way utilizes less memory and resources. And again this is yet another angle on the problem. Reducing memory usage may increase execution time or reduce readability. They don't call it software engineering for nothing - and engineering is all about choosing the "best" compromises based on the needs. > feel apprehensive to post so I purchased many books on python, IME, This forum is one of the most polite and friendly lists on the internet. You will rarely get insulted or savaged here, especially if you provide a good background to the question and its context. Compared to many other lists (try Perl!) we are all pussycats here! :-) > feel a little bet more human and inspires me not to give up. We are all human and trying to contribute our own little something. Sometimes we don't agree, but that's because we are human and there are rarely right and wrong answers, just opinions. And we all have different experience levels. And we are all volunteers who may have had a hard day, or be reading very late at night or early in the morning... Making allowances has to be done on both sides of the poster/replier fence. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ (and list moderator) From steve at pearwood.info Wed Feb 2 20:17:19 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Feb 2011 06:17:19 +1100 Subject: [Tutor] Help with range of months spanning across years In-Reply-To: <4D48B3AE.5070803@iandouglas.com> References: <917795.16981.qm@web130202.mail.mud.yahoo.com> <4D48B3AE.5070803@iandouglas.com> Message-ID: <4D49ADBF.1020808@pearwood.info> ian douglas wrote: > It bugs me that so many people are quick to jump on the "we wont' do > your homework" bandwagon -- I was accused of the same thing when I > posted a question to the list myself. I've been programming > professionally for many years but learning Python in my spare time... I > sent this reply to Sean privately, but frankly I'm so annoyed at the > 'homework' replies, I figured I'd just post it here. It's a fine line. Most people consider "homework" questions to be cheating, and don't want to either condone or assist cheaters in any way. The cost, though, is occasionally offending people who aren't cheating, but merely asking a question poorly, or happen to be asking something that *sounds* like homework, or just unlucky. Generally, if you want an answer to a question, you should demonstrate that you've tried to solve it yourself. Code, even broken code that doesn't work, and a clear description of the problem, go a long way to assuring people that *even if it is homework*, you've made a good attempt at the problem and are looking for *help* rather than somebody to do it for you. At which point somebody will almost certainly jump in an do it for you :) > I'm still very junior to Python, but this seems to work for me using > recursion. I'm sure there's a much more elegant way of doing this, but > like I said, I'm still pretty new to the language. > > def makelist(startmonth,startyear,endmonth,endyear): > mylist = [] > if (startyear == endyear): > for month in range (startmonth,endmonth+1): > mylist += [(startyear,month)] > else: > for month in range (startmonth,13): > mylist += [(startyear,month)] > mylist += makelist(1,startyear+1, endmonth, endyear) > return mylist ; > > print makelist(8,2009,1,2010) > > I'd love to hear any replies from the experts on the list on how to make > this more efficient in Python 'cause I'm still learning myself. Generally, you don't use recursion because it's efficient, 'cos it ain't. At least not in Python, which has a fairly naive recursion model. Some other languages can spot a particular kind of recursion, and optimise the bejeezus out of it. So leave recursion for the problems where (1) it makes solving the problem easy, and (2) the inefficiency doesn't matter. The *general* way of making recursion efficient is by converting it to iteration, if possible. In your case, recursion doesn't seem to really make the problem any easier to solve, but it probably doesn't hurt much. -- Steven From karim.liateni at free.fr Wed Feb 2 20:21:39 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 02 Feb 2011 20:21:39 +0100 Subject: [Tutor] RE module is working ? Message-ID: <4D49AEC3.7020900@free.fr> Hello, I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 consecutives double quotes: * *In Python interpreter:* $ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> expression = *' "" '* >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) Traceback (most recent call last): File "", line 1, in File "/home/karim/build/python/install/lib/python2.7/re.py", line 162, in subn return _compile(pattern, flags).subn(repl, string, count) File "/home/karim/build/python/install/lib/python2.7/re.py", line 278, in filter return sre_parse.expand_template(template, match) File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", line 787, in expand_template raise error, "unmatched group" sre_constants.error: unmatched group But if I remove '?' I get the following: >>> re.subn(r'([^\\])"', r'\1\\"', expression) (' \\"" ', 1) Only one substitution..._But this is not the same REGEX._ And the count=2 does nothing. By default all occurrence shoul be substituted. * *On linux using my good old sed command, it is working with my '?' (0-1 match):* *$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'* \"\" *Indeed what's the matter with RE module!?* *Any idea will be welcome! Regards Karim* * -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrysalis_reborn at yahoo.com Wed Feb 2 20:38:54 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Wed, 2 Feb 2011 11:38:54 -0800 (PST) Subject: [Tutor] update Tkinter text widget in realtime? Message-ID: <629683.83329.qm@web130221.mail.mud.yahoo.com> The guy who had the post about the "vowel search" exercise got me to thinking about matrices of letters, and thence to word search games, which I have made a time or two by hand and they are a pain. So I decided to try making a program that would put words into a word search. This is very basic, there's no checking to see if your word is going to go out of bounds (yet), but it works. So, just for the heck of it, I thought, what would happen if I put a word into the matrix, such that its first letter is in the center, and then it rotate around its insertion point. This sets up a Tkinter text widget and inserts the matrix into it. I figured I could just clear the widget by deleting everything in it, then putting a matrix, modified with the next rotation into it. No dice. The rotations are happening, but the text widget only materializes after the last rotation, and the final "frame" in the rotation is the only one it shows. I've run into this same sort of issue with Tcl/Tk, and never solved it there, either. Any ideas? The last 10-12 lines are the ones that do the rotation. I've tried moving the root.mainloop() statement up higher in the code. That causes the text widget to show up, but no matrix inside. from Tkinter import * from tkFont import * import random root = Tk() fixed_width = Font(family = 'Courier', size = 10) textbox = Text(root, font = fixed_width, width = 40, height = 20) textbox.pack() def blank_matrix(sizeX, sizeY, fillchar): sizeX += 1 sizeY += 1 letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' letter_matrix = [] for row in range(1,sizeY): line = [] for _column in range(1, sizeX): if fillchar == 'letters': letter = random.randrange(0, 26) line.append(letters[letter]) else: line.append(fillchar) letter_matrix.append(line) return letter_matrix def print_matrix(matrix): textbox.delete(1.0, END) for line in matrix: #print ' '.join(line) line = ' '.join(line) + '\n' textbox.insert(END, line) def insert_word(word, print_dir, x, y, matrix): word = word.upper() word = list(word) print_dirs = dict() print_dirs['e'] = (1,0) print_dirs['ne'] = (1,-1) print_dirs['n'] = (0,-1) print_dirs['nw'] = (-1,-1) print_dirs['w'] = (-1, 0) print_dirs['sw'] = (-1, 1) print_dirs['s'] = (0, 1) print_dirs['se'] = (1,1) x_plus, y_plus = print_dirs[print_dir] for i in range(0, len(word)): matrix[y + (i * y_plus)][x + (i * x_plus)] = word[i] return matrix directions = ['e', 'ne', 'n', 'nw', 'w', 'sw', 's', 'se'] for direction in directions: print direction matrix = blank_matrix(20, 20, '.') matrix = insert_word('test_word', direction, 10, 10, matrix) print_matrix(matrix) root.mainloop() I've also doctored the code to get a final matrix with all rotations included...so the rotations are for sure happening, but the text widget just isn't updating. This is what it looks like with all possible rotations, in case I'm not making sense. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . D . . . . . . . D . . . . . . . D . . . . R . . . . . . R . . . . . . R . . . . . . O . . . . . O . . . . . O . . . . . . . . W . . . . W . . . . W . . . . . . . . . . _ . . . _ . . . _ . . . . . . . . . . . . T . . T . . T . . . . . . . . . . . . . . S . S . S . . . . . . . . . . . . . . . . E E E . . . . . . . . . . D R O W _ T S E T E S T _ W O R D . . . . . . . . . . E E E . . . . . . . . . . . . . . . . S . S . S . . . . . . . . . . . . . . T . . T . . T . . . . . . . . . . . . _ . . . _ . . . _ . . . . . . . . . . W . . . . W . . . . W . . . . . . . . O . . . . . O . . . . . O . . . . . . R . . . . . . R . . . . . . R . . . . D . . . . . . . D . . . . . . . D . . . . . . . . . . . . . . . . . . . . . From steve at pearwood.info Wed Feb 2 21:11:41 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Feb 2011 07:11:41 +1100 Subject: [Tutor] Help with range of months [was Tutor Digest, Vol 84, Issue 8] In-Reply-To: <4D497BD1.4060904@bellsouth.net> References: <4D497BD1.4060904@bellsouth.net> Message-ID: <4D49BA7D.7060208@pearwood.info> Hi Nevins, I don't think I've seen you post here before. Welcome to the list! Before answering your comment (see below), I have to give you a gentle wrap on the knuckles. It's considered impolite to: (1) reply to a digest without changing the subject line from "Tutor Digest" to something more meaningful; and (2) reply to a digest without trimming (deleting) the 200+ lines that have nothing to do with your comment; both of which you have done. Nevins Duret wrote: [snip] > I think the stigma of > the "homework bandwagon" comes from the very nature of coding and it's > secretive and cryptic undertones, it's something very personal in the > sense that, although there is usually more than 1 way to solve a > problem, there's always "THE MOST" and more efficient way IMHO, that > some people are just not willing to share. I think you couldn't be more wrong to describe coding as "secretive and cryptic", and it is ironic that you are making this accusation on a mailing list crewed by volunteers who don't get a cent for donating their time and expertise to help others, using a programming language which has been donated for free to the programming community. Python is Open Source software -- not only is it free like "free beer", but it's also free like in "freedom of speech". If you want to see how secretive Python is, I suggest you go here: http://www.python.org/download/source/ and download every single line of code used by the Python interpreter and the entire standard library, and then read the licence: http://docs.python.org/license.html which grants you the freedom to do anything you like with it, virtually without restriction. You might find that source code cryptic (I know I would find parts of it so), but that's a function of ignorance, not an inherent characteristic of programming. Python is just one tiny part of the Free Software and Open Source movement(s), possibly and arguably best exemplified by the Free Software Foundation: http://www.fsf.org/ and the GNU project: http://www.gnu.org/philosophy/philosophy.html Of course there are always "some people", but with 7 billion people on the planet that applies to virtually anything. Speaking for myself, I have *never* withheld an answer to a question because I wanted to keep it to myself. I've *very occasionally* withheld answers because I thought the questioner was being a leach, taking without any possibility of giving back, or was rude and inconsiderate. I've frequently failed to answer because I'm busy and there are only so many hours in a day (so apologies to anyone waiting for a response from me who hasn't received one). -- Steven From alan.gauld at btinternet.com Thu Feb 3 02:17:13 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Feb 2011 01:17:13 -0000 Subject: [Tutor] update Tkinter text widget in realtime? References: <629683.83329.qm@web130221.mail.mud.yahoo.com> Message-ID: "Elwin Estle" wrote Caveat: I haven't studied this in detail so I might be missing something... > So, just for the heck of it, I thought, what would happen > if I put a word into the matrix, such that its first letter is > in the center, and then it rotate around its insertion point. > > This sets up a Tkinter text widget and inserts the matrix into it. > > I figured I could just clear the widget by deleting everything > in it, then putting a matrix, modified with the next rotation into > it. > > No dice. The rotations are happening, but the text widget > only materializes after the last rotation, and the final "frame" > in the rotation is the only one it shows. Tk is an event driven framework so it will only update between events. But I don't see any events in your code. You do the initial population of the matrix and add it to the text widget but then nothing happens... Where are the events that would cause the display to update? I'd expect to see a timer or similar mechanism forcing a redraw of the widgets. > Any ideas? The last 10-12 lines are the ones that do > the rotation. I've tried moving the root.mainloop() statement > up higher in the code. That causes the text widget to show > up, but no matrix inside. mainloop() starts the event loop. From that point on Tk is waiting for events to process. But since you have not defined any handlers all events are just ignored. You need to add an event handler (for a timer say) that will catch timeouts and update the Text widget. It can then set a new timer ready for the next update. > root = Tk() > > fixed_width = Font(family = 'Courier', size = 10) > textbox = Text(root, font = fixed_width, width = 40, height = 20) > textbox.pack() This sets up the UI widget but no event handlers.. > def blank_matrix(sizeX, sizeY, fillchar): .... > return letter_matrix This fills the matrix > def print_matrix(matrix): > textbox.delete(1.0, END) > for line in matrix: > #print ' '.join(line) > line = ' '.join(line) + '\n' > textbox.insert(END, line) This fills the widget > def insert_word(word, print_dir, x, y, matrix): > ... > return matrix More matrix filling > directions = ['e', 'ne', 'n', 'nw', 'w', 'sw', 's', 'se'] > for direction in directions: > print direction > matrix = blank_matrix(20, 20, '.') > matrix = insert_word('test_word', direction, 10, 10, matrix) > print_matrix(matrix) This goes through the loop once using the functions above but again creates no event handlers to update the GUI. > root.mainloop() Now we are waiting for events but without any handlers the events that do happen - and with no control widgets there will not be many - are ignored or defaulted (move, resize etc). > I've also doctored the code to get a final matrix with > all rotations included...so the rotations are for sure happening, > but the text widget just isn't updating. Because you are not telling it to update. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From smokeinourlights at gmail.com Thu Feb 3 03:00:47 2011 From: smokeinourlights at gmail.com (Doug Marvel) Date: Wed, 2 Feb 2011 21:00:47 -0500 Subject: [Tutor] print "Hello, World!" Message-ID: Hey folks, I'm Doug. I've been using computers since second grade, and I know a little about them. I am, however, completely new to programming. I don't even know what I know about it. I'd like some social interaction with this, but I can't go back to school until summer or fall of this year. I don't want to wait to start learning this as I feel like I'm already about a million years behind. I asked the Oracle (www.google.com) and after messing around with the Python Shell and getting a lot of error messages, I decided I need some remote help. Here's where I'm at: - I have downloaded and installed Python 2.6.4. Successfully, I think. - I am running Windows XP SP3 (though I'm going to see if I can do this on my laptop, which has Windows 7) - I have toyed around with some tutorials, but all they really taught me is that I need a teacher. I'm sure you guys are busy, but I read that the most basic questions are okay. As I'm sure there is at least one good resource on the net for people in my position, I'd like some suggestions on where to start. I plan on bothering you all as little as possible, but I am seriously hoping to make real progress between now and my first class. I have a feeling once I get a basic understanding, I'll run away with it. It's just very... big right now. So this list seems like a good thing, but tell me if I'm in the wrong place. I am hoping for a link to a somewhat comprehensive online resource that explains from the beginning in English, plain English, as this is the only language I speak. Something to get my foot in the door would be awesome. Cheers, Doug Marvel From kb1pkl at aim.com Thu Feb 3 03:27:33 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 02 Feb 2011 21:27:33 -0500 Subject: [Tutor] print "Hello, World!" In-Reply-To: References: Message-ID: <4D4A1295.7050304@aim.com> On 2/2/2011 9:00 PM, Doug Marvel wrote: > [snip] > > I am hoping for a link to a somewhat comprehensive online resource > that explains from the beginning in English, plain English, as this is > the only language I speak. Something to get my foot in the door would > be awesome. > > > Cheers, > Doug Marvel When I started out I used Alan Gauld's wonderful tutor: http://www.alan-g.me.uk/tutor/index.htm It references Python 2.3, but the same things apply for 2.6 as well. What I like about that site is that it doesn't skip anything, and goes into more advanced topics at the end. From waynejwerner at gmail.com Thu Feb 3 03:53:17 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 2 Feb 2011 20:53:17 -0600 Subject: [Tutor] print "Hello, World!" In-Reply-To: <4D4A1295.7050304@aim.com> References: <4D4A1295.7050304@aim.com> Message-ID: On Wed, Feb 2, 2011 at 8:27 PM, Corey Richardson wrote: > On 2/2/2011 9:00 PM, Doug Marvel wrote: > > [snip] > > > > I am hoping for a link to a somewhat comprehensive online resource > > that explains from the beginning in English, plain English, as this is > > the only language I speak. Something to get my foot in the door would > > be awesome. > > > > > > Cheers, > > Doug Marvel > > When I started out I used Alan Gauld's wonderful tutor: > http://www.alan-g.me.uk/tutor/index.htm > > It references Python 2.3, but the same things apply for 2.6 as well. > What I like about that site is that it doesn't skip anything, and goes > into more advanced topics at the end. I'll second his tutorial - it's great for the beginner *and* he also happens to contribute to/moderate this list. The best thing to do is pick a tutorial (like Alan's, perhaps) and start working through it. When you hit a wall, and can't figure out what something is doing, send an email. Often, just the act of trying to phrase your question will end out giving you the insight you need. I can't tell you how many dozens of emails I've started and then discarded because I ended out figuring it out on my own. If you show that you've worked on a problem, but you simply got stuck, you'll find that *many* people on this list will offer *tons* of good advice. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigenbakuda at yahoo.com Thu Feb 3 04:05:44 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Wed, 2 Feb 2011 19:05:44 -0800 (PST) Subject: [Tutor] print "Hello, World!" In-Reply-To: References: Message-ID: <99556.52199.qm@web130220.mail.mud.yahoo.com> Hey doug please don't be discouraged..., and be glad you didn't start in C++ like me... talk about being discouraged... But anyways, I just started as well. I've only been programming like 5 months. So I understand you very much :) Here are some of the better (more clear) tutorials I ran across in my short stint as a programmer. Here is the tutorial I used the most. How to think like a computer scientist (python version). This tells you stuff, then it gives you practice problems to reinforce what you just learned. (There are no answers to the problems, but this actually helped me learn a lot by researching the answers). http://openbookproject.net/thinkcs/python/english2e/index.html Bucky's youtube tutorials, in here he comments as he shows you some concepts then talks about them. He teaches python in normal english, its not technical at all, its very good :) http://www.youtube.com/user/thenewboston#p/c/0/4Mf0h3HphEA And I'm 26... so you are a million years ahead of me :) One piece of advice I can give is abuse google, almost any question you have has already been asked, learn from others who asked before you :) Oh yea, I once read that there are no intermediate tutorials in any programming language, because once you get past the basics, you only need to reference the "documentation" that comes with the language. I hope this helps. What is it about you... that intrigues me so? ________________________________ From: Doug Marvel To: tutor at python.org Sent: Wed, February 2, 2011 9:00:47 PM Subject: [Tutor] print "Hello, World!" Hey folks, I'm Doug. I've been using computers since second grade, and I know a little about them. I am, however, completely new to programming. I don't even know what I know about it. I'd like some social interaction with this, but I can't go back to school until summer or fall of this year. I don't want to wait to start learning this as I feel like I'm already about a million years behind. I asked the Oracle (www.google.com) and after messing around with the Python Shell and getting a lot of error messages, I decided I need some remote help. Here's where I'm at: - I have downloaded and installed Python 2.6.4. Successfully, I think. - I am running Windows XP SP3 (though I'm going to see if I can do this on my laptop, which has Windows 7) - I have toyed around with some tutorials, but all they really taught me is that I need a teacher. I'm sure you guys are busy, but I read that the most basic questions are okay. As I'm sure there is at least one good resource on the net for people in my position, I'd like some suggestions on where to start. I plan on bothering you all as little as possible, but I am seriously hoping to make real progress between now and my first class. I have a feeling once I get a basic understanding, I'll run away with it. It's just very... big right now. So this list seems like a good thing, but tell me if I'm in the wrong place. I am hoping for a link to a somewhat comprehensive online resource that explains from the beginning in English, plain English, as this is the only language I speak. Something to get my foot in the door would be awesome. Cheers, Doug Marvel _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Thu Feb 3 06:43:00 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 2 Feb 2011 23:43:00 -0600 Subject: [Tutor] byte array conversion question Message-ID: I have found that there are a couple of ways to convert a byte array to a string in Python. Is there any advantage or disadvantage to either method? my_bytes = b'this is a test' str(my_bytes,'utf-8') yields 'this is a test' my_bytes.decode('utf-8';) yeilds 'this is a test' --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From Eric.Lofgren at unc.edu Thu Feb 3 08:05:13 2011 From: Eric.Lofgren at unc.edu (Eric Lofgren) Date: Thu, 3 Feb 2011 02:05:13 -0500 Subject: [Tutor] System of ODEs Question Message-ID: So I'm in the process of learning Python, and have been working on a program to solve a very simple S-I-R model, used to study infectious diseases. Basically, it's just a smallish set of differential equations which need to be numerically integrated over time. Working off of a template program, I came up with the following: --- #Python implementation of continuous SIR model #Import Necessary Modules import numpy as np import pylab as pl import scipy.integrate as spi #Parameter Values S0 = 0.99999 I0 = 0.00001 R0 = 0.0 PopIn= (S0, I0, R0) beta=1.4547 gamma=1/7. t_end = 70 t_start = 1 t_step = 1 t_interval = np.arange(t_start, t_end, t_step) def eq_system(PopIn,x): '''Defining SIR System of Equations''' #Creating an array of equations Eqs= np.zeros((3)) Eqs[0]= -beta * PopIn[0]*PopIn[1] Eqs[1]= beta * PopIn[0]*PopIn[1] - gamma*PopIn[1] Eqs[2]= gamma*PopIn[1] return Eqs SIR = spi.odeint(eq_system, PopIn, t_interval) print SIR #Plot Everything #This is really ugly, but works for now pl.plot(SIR[:,0]) pl.plot(SIR[:,1]) pl.plot(SIR[:,2]) pl.show() --- The part that is confusing me is defining the function. Namely, it seems to need two arguments - the first needs to be the initial states of the population being modeled, but the second...it doesn't seem to matter what it is. Originally, I didn't include it at all, and the program was very, very unhappy - looking back at the example, it had a second argument, so I put one in, and magically, it worked. But it can be x, it can be t, it can be anything. Which raises the question: What is it *doing*? Honestly, I'm baffled - can anyone point me in the right direction? Thanks, Eric From davidheiserca at gmail.com Thu Feb 3 08:50:17 2011 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Wed, 2 Feb 2011 23:50:17 -0800 Subject: [Tutor] print "Hello, World!" References: Message-ID: Seven years ago, my story was similar. I started off with "The Python Quick Book" (Manning) and "Python - Visual Quickstart Guide" (Peachpit Press). Both are very easy to follow. I still pick up the "Quick" book once in a while for reference. This "Tutor" list helped a lot. I learned by trying out the things people offered as solutions to problems from people like you and me. Asking questions here is a way to help a lot of new Python programmers, and a few older ones, too. There are a lot more resources these days, too. Search on "Python" in YouTube. There are a lot of on-line tutorials, too. ----- Original Message ----- From: "Doug Marvel" To: Sent: Wednesday, February 02, 2011 6:00 PM Subject: [Tutor] print "Hello, World!" > Hey folks, > > I'm Doug. I've been using computers since second grade, and I know a > little about them. I am, however, completely new to programming. I > don't even know what I know about it. I'd like some social interaction > with this, but I can't go back to school until summer or fall of this > year. I don't want to wait to start learning this as I feel like I'm > already about a million years behind. I asked the Oracle > (www.google.com) and after messing around with the Python Shell and > getting a lot of error messages, I decided I need some remote help. > Here's where I'm at: > > - I have downloaded and installed Python 2.6.4. Successfully, I think. > - I am running Windows XP SP3 (though I'm going to see if I can do > this on my laptop, which has Windows 7) > - I have toyed around with some tutorials, but all they really taught > me is that I need a teacher. > > I'm sure you guys are busy, but I read that the most basic questions > are okay. As I'm sure there is at least one good resource on the net > for people in my position, I'd like some suggestions on where to > start. I plan on bothering you all as little as possible, but I am > seriously hoping to make real progress between now and my first class. > I have a feeling once I get a basic understanding, I'll run away with > it. It's just very... big right now. So this list seems like a good > thing, but tell me if I'm in the wrong place. > > I am hoping for a link to a somewhat comprehensive online resource > that explains from the beginning in English, plain English, as this is > the only language I speak. Something to get my foot in the door would > be awesome. > > > Cheers, > Doug Marvel > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From shahdharmit at gmail.com Thu Feb 3 09:11:04 2011 From: shahdharmit at gmail.com (Dharmit Shah) Date: Thu, 3 Feb 2011 13:41:04 +0530 Subject: [Tutor] print "Hello, World!" In-Reply-To: References: Message-ID: I'd also recommend using http://www.openbookproject.net/thinkcs/python/english2e/ . Currently I am learning from it. Once u are through with it u can read the book called Dive into Python. it's for experienced users. Google it. Hope that helps. On Thu, Feb 3, 2011 at 1:20 PM, wrote: > > Seven years ago, my story was similar. I started off with "The Python Quick > Book" (Manning) and "Python - Visual Quickstart Guide" (Peachpit Press). > Both are very easy to follow. I still pick up the "Quick" book once in a > while for reference. > > This "Tutor" list helped a lot. I learned by trying out the things people > offered as solutions to problems from people like you and me. > > Asking questions here is a way to help a lot of new Python programmers, and > a few older ones, too. > > There are a lot more resources these days, too. Search on "Python" in > YouTube. > > There are a lot of on-line tutorials, too. > > > ----- Original Message ----- From: "Doug Marvel" < > smokeinourlights at gmail.com> > To: > Sent: Wednesday, February 02, 2011 6:00 PM > Subject: [Tutor] print "Hello, World!" > > > Hey folks, >> >> I'm Doug. I've been using computers since second grade, and I know a >> little about them. I am, however, completely new to programming. I >> don't even know what I know about it. I'd like some social interaction >> with this, but I can't go back to school until summer or fall of this >> year. I don't want to wait to start learning this as I feel like I'm >> already about a million years behind. I asked the Oracle >> (www.google.com) and after messing around with the Python Shell and >> getting a lot of error messages, I decided I need some remote help. >> Here's where I'm at: >> >> - I have downloaded and installed Python 2.6.4. Successfully, I think. >> - I am running Windows XP SP3 (though I'm going to see if I can do >> this on my laptop, which has Windows 7) >> - I have toyed around with some tutorials, but all they really taught >> me is that I need a teacher. >> >> I'm sure you guys are busy, but I read that the most basic questions >> are okay. As I'm sure there is at least one good resource on the net >> for people in my position, I'd like some suggestions on where to >> start. I plan on bothering you all as little as possible, but I am >> seriously hoping to make real progress between now and my first class. >> I have a feeling once I get a basic understanding, I'll run away with >> it. It's just very... big right now. So this list seems like a good >> thing, but tell me if I'm in the wrong place. >> >> I am hoping for a link to a somewhat comprehensive online resource >> that explains from the beginning in English, plain English, as this is >> the only language I speak. Something to get my foot in the door would >> be awesome. >> >> >> Cheers, >> Doug Marvel >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Regards Dharmit Shah -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 3 10:04:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Feb 2011 09:04:00 -0000 Subject: [Tutor] print "Hello, World!" References: Message-ID: "Doug Marvel" wrote > - I have downloaded and installed Python 2.6.4. Successfully, I > think. > - I am running Windows XP SP3 (though I'm going to see if I can do > this on my laptop, which has Windows 7) > - I have toyed around with some tutorials, but all they really > taught > me is that I need a teacher. :-) You don't say which tutorials you've looked at but there are a whole set especially for non programmers on the Python web site (including mine). They all have slightly different styles and approaches so I suggest you take a look at 2 or 3 and find one that suits you. Follow it and when you have questins bring them to this list and we will clarify things for you. > I'm sure you guys are busy, but I read that the most basic questions > are okay. Yes, thats what we are here for. > I have a feeling once I get a basic understanding, I'll run away > with > it. It's just very... big right now. So this list seems like a good > thing, but tell me if I'm in the wrong place. Yes, absolutely. Roll your sleeves up, dive in and experiment a lot. Then ask questions. Its the best way to learn. > I am hoping for a link to a somewhat comprehensive online resource > that explains from the beginning in English, plain English, You can try mine, it starts with the basic concepts and takes you through to writing some basic but real-world programs. It does assume you know computer basics but you sound as if you do. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From karim.liateni at free.fr Thu Feb 3 10:57:41 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 03 Feb 2011 10:57:41 +0100 Subject: [Tutor] RE module is working ? In-Reply-To: <4D49AEC3.7020900@free.fr> References: <4D49AEC3.7020900@free.fr> Message-ID: <4D4A7C15.7040602@free.fr> Hello, Any news on this topic?O:-) Regards Karim On 02/02/2011 08:21 PM, Karim wrote: > > Hello, > > I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 > consecutives double quotes: > > * *In Python interpreter:* > > $ python > Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) > [GCC 4.4.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> expression = *' "" '* > >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) > Traceback (most recent call last): > File "", line 1, in > File "/home/karim/build/python/install/lib/python2.7/re.py", line > 162, in subn > return _compile(pattern, flags).subn(repl, string, count) > File "/home/karim/build/python/install/lib/python2.7/re.py", line > 278, in filter > return sre_parse.expand_template(template, match) > File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", > line 787, in expand_template > raise error, "unmatched group" > sre_constants.error: unmatched group > > But if I remove '?' I get the following: > > >>> re.subn(r'([^\\])"', r'\1\\"', expression) > (' \\"" ', 1) > > Only one substitution..._But this is not the same REGEX._ And the > count=2 does nothing. By default all occurrence shoul be substituted. > > * *On linux using my good old sed command, it is working with my > '?' (0-1 match):* > > *$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'* > \"\" > > *Indeed what's the matter with RE module!?* > > *Any idea will be welcome! > > Regards > Karim* > * > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Feb 3 11:43:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Feb 2011 21:43:50 +1100 Subject: [Tutor] RE module is working ? In-Reply-To: <4D49AEC3.7020900@free.fr> References: <4D49AEC3.7020900@free.fr> Message-ID: <4D4A86E6.3000901@pearwood.info> Karim wrote: > > Hello, > > I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 > consecutives double quotes: You don't have to escape quotes. Just use the other sort of quote: >>> print '""' "" > * *In Python interpreter:* > > $ python > Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) > [GCC 4.4.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> expression = *' "" '* No, I'm sorry, that's incorrect -- that gives a syntax error in every version of Python I know of, including version 2.7: >>> expression = *' "" '* File "", line 1 expression = *' "" '* ^ SyntaxError: invalid syntax So what are you really running? > >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) Likewise here. *r'...' is a syntax error, as is expression*) I don't understand what you are running or why you are getting the results you are. > *Indeed what's the matter with RE module!?* There are asterisks all over your post! Where are they coming from? What makes you think the problem is with the RE module? We have a saying in English: "The poor tradesman blames his tools." Don't you think it's more likely that the problem is that you are using the module wrongly? I don't understand what you are trying to do, so I can't tell you how to do it. Can you give an example of what you want to start with, and what you want to end up with? NOT Python code, just literal text, like you would type into a letter. E.g. ABC means literally A followed by B followed by C. \" means literally backslash followed by double-quote -- Steven From steve at pearwood.info Thu Feb 3 12:05:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Feb 2011 22:05:33 +1100 Subject: [Tutor] byte array conversion question In-Reply-To: References: Message-ID: <4D4A8BFD.2000401@pearwood.info> Bill Allen wrote: > I have found that there are a couple of ways to convert a byte array to a > string in Python. Is there any advantage or disadvantage to either method? > > my_bytes = b'this is a test' > > str(my_bytes,'utf-8') yields 'this is a test' > my_bytes.decode('utf-8';) yeilds 'this is a test' Not so far as I know. The decode method is a *tiny* bit faster: >>> from timeit import Timer >>> t1 = Timer("str(my_bytes,'utf-8')", "my_bytes = b'this is a test'") >>> t2 = Timer("my_bytes.decode('utf-8')", "my_bytes = b'this is a test'") >>> min(t1.repeat()) 0.670975923538208 >>> min(t2.repeat()) 0.5184659957885742 Those figures are in seconds, for one million calls. So the actual speed difference is about 0.1 of a microsecond, almost always too trivial to care about. -- Steven From alan.gauld at btinternet.com Thu Feb 3 12:07:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Feb 2011 11:07:06 -0000 Subject: [Tutor] print "Hello, World!" References: <99556.52199.qm@web130220.mail.mud.yahoo.com> Message-ID: "michael scott" wrote > already been asked, learn from others who asked before you :) Oh > yea, I once > read that there are no intermediate tutorials in any programming > language, > because once you get past the basics, you only need to reference the > "documentation" that comes with the language. Thats very nearly true. There are intermediate level tutorials for a few languages but more generally you get subject specific tutorials on things like parsing, web programming, GUI programming, databases, networking, stats and scientific programming etc etc. So there are usually intermediate level tutorials to suit they are rarely full language tutorials. I try to cover that off with the advanced topics and "Python in practice" topics at the end of my tutorial. But again they are focused on specific topic areas (OS, database, networks, web). -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From izzaddin.ruhulessin at gmail.com Thu Feb 3 12:11:42 2011 From: izzaddin.ruhulessin at gmail.com (C.Y. Ruhulessin) Date: Thu, 3 Feb 2011 12:11:42 +0100 Subject: [Tutor] 'Installing' Python at runtime? (Civilization) Message-ID: Hi all, When I load up Civilization IV, a Firaxis game, the loading screen tells me "Loading Python". However, I can't seem to find out where it installs python (and Python wasn't installed before I installed it myself), so I *assume *that it 'installs' and loads Python at runtime. For an application that I am designing, i'd like to achieve the same functionality, so the end users don't have to bother installing Python themselves. Can anybody shed their lights on how one would program this? kind regards, Izz ad-Din -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Thu Feb 3 12:45:59 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 03 Feb 2011 12:45:59 +0100 Subject: [Tutor] RE module is working ? In-Reply-To: <4D4A86E6.3000901@pearwood.info> References: <4D49AEC3.7020900@free.fr> <4D4A86E6.3000901@pearwood.info> Message-ID: <4D4A9577.6080107@free.fr> Hello Steven, I am perhaps a poor tradesman but I have to blame my thunderbird tool :-P . Because expression = *' "" '* is in fact fact expression = ' "" '. The bold appear as stars I don't know why. I need to have escapes for passing it to another language (TCL interpreter). So I will rewrite it not _in bold_: $ python Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> expression = ' "" ' >>> re.subn(r'([^\\])?"', r'\1\\"', expression) But if I remove '?' I get the following: >>> re.subn(r'([^\\])"', r'\1\\"', expression) (' \\"" ', 1) * On linux using my good old sed command, it is working with my '?' (0-1 match): $ echo ' "" ' | sed 's/\([^\\]\)\?"/\1\\"/g'* * \"\" For me linux/unix sed utility is trusty and is the reference. Regards Karim On 02/03/2011 11:43 AM, Steven D'Aprano wrote: > Karim wrote: >> >> Hello, >> >> I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 >> consecutives double quotes: > > You don't have to escape quotes. Just use the other sort of quote: > > >>> print '""' > "" > > >> * *In Python interpreter:* >> >> $ python >> Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) >> [GCC 4.4.3] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> expression = *' "" '* > > No, I'm sorry, that's incorrect -- that gives a syntax error in every > version of Python I know of, including version 2.7: > > >>> expression = *' "" '* > File "", line 1 > expression = *' "" '* > ^ > SyntaxError: invalid syntax > > > So what are you really running? > > > >> >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) > > Likewise here. *r'...' is a syntax error, as is expression*) > > I don't understand what you are running or why you are getting the > results you are. > > > > *Indeed what's the matter with RE module!?* > > There are asterisks all over your post! Where are they coming from? > > What makes you think the problem is with the RE module? > > We have a saying in English: > > "The poor tradesman blames his tools." > > Don't you think it's more likely that the problem is that you are > using the module wrongly? > > I don't understand what you are trying to do, so I can't tell you how > to do it. Can you give an example of what you want to start with, and > what you want to end up with? NOT Python code, just literal text, like > you would type into a letter. > > E.g. ABC means literally A followed by B followed by C. > \" means literally backslash followed by double-quote > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From enalicho at gmail.com Thu Feb 3 12:48:05 2011 From: enalicho at gmail.com (Noah Hall) Date: Thu, 3 Feb 2011 11:48:05 +0000 Subject: [Tutor] 'Installing' Python at runtime? (Civilization) In-Reply-To: References: Message-ID: On Thu, Feb 3, 2011 at 11:11 AM, C.Y. Ruhulessin wrote: > For an application that I am designing, i'd like to achieve the same > functionality, so the end users don't have to bother installing Python > themselves. > Can anybody shed their lights on how one would program this? > kind regards, There are applications, such as http://www.py2exe.org/ and http://www.pyinstaller.org/ that you can use to achieve the same thing. From karim.liateni at free.fr Thu Feb 3 12:56:29 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 03 Feb 2011 12:56:29 +0100 Subject: [Tutor] RE module is working ? In-Reply-To: <4D4A9577.6080107@free.fr> References: <4D49AEC3.7020900@free.fr> <4D4A86E6.3000901@pearwood.info> <4D4A9577.6080107@free.fr> Message-ID: <4D4A97ED.6010407@free.fr> I forget something. There is no issue with python and double quotes. But I need to give it to TCL script but as TCL is shit string is only delimited by double quotes. Thus I need to escape it to not have syntax error whith nested double quotes. Regards The poor tradesman On 02/03/2011 12:45 PM, Karim wrote: > > Hello Steven, > > I am perhaps a poor tradesman but I have to blame my thunderbird tool > :-P . > Because expression = *' "" '* is in fact fact expression = ' "" '. > The bold appear as stars I don't know why. I need to have escapes for > passing it to another language (TCL interpreter). > So I will rewrite it not _in bold_: > > $ python > Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) > [GCC 4.4.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> expression = ' "" ' > > >>> re.subn(r'([^\\])?"', r'\1\\"', expression) > > But if I remove '?' I get the following: > > >>> re.subn(r'([^\\])"', r'\1\\"', expression) > (' \\"" ', 1) > > * On linux using my good old sed command, it is working with my > '?' (0-1 match): > > $ echo ' "" ' | sed 's/\([^\\]\)\?"/\1\\"/g'* > * \"\" > > For me linux/unix sed utility is trusty and is the reference. > > Regards > Karim > > > On 02/03/2011 11:43 AM, Steven D'Aprano wrote: >> Karim wrote: >>> >>> Hello, >>> >>> I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 >>> consecutives double quotes: >> >> You don't have to escape quotes. Just use the other sort of quote: >> >> >>> print '""' >> "" >> >> >>> * *In Python interpreter:* >>> >>> $ python >>> Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) >>> [GCC 4.4.3] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> expression = *' "" '* >> >> No, I'm sorry, that's incorrect -- that gives a syntax error in every >> version of Python I know of, including version 2.7: >> >> >>> expression = *' "" '* >> File "", line 1 >> expression = *' "" '* >> ^ >> SyntaxError: invalid syntax >> >> >> So what are you really running? >> >> >> >>> >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) >> >> Likewise here. *r'...' is a syntax error, as is expression*) >> >> I don't understand what you are running or why you are getting the >> results you are. >> >> >> > *Indeed what's the matter with RE module!?* >> >> There are asterisks all over your post! Where are they coming from? >> >> What makes you think the problem is with the RE module? >> >> We have a saying in English: >> >> "The poor tradesman blames his tools." >> >> Don't you think it's more likely that the problem is that you are >> using the module wrongly? >> >> I don't understand what you are trying to do, so I can't tell you how >> to do it. Can you give an example of what you want to start with, and >> what you want to end up with? NOT Python code, just literal text, >> like you would type into a letter. >> >> E.g. ABC means literally A followed by B followed by C. >> \" means literally backslash followed by double-quote >> >> >> >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Thu Feb 3 13:02:43 2011 From: izzaddin.ruhulessin at gmail.com (C.Y. Ruhulessin) Date: Thu, 3 Feb 2011 13:02:43 +0100 Subject: [Tutor] 'Installing' Python at runtime? (Civilization) In-Reply-To: References: Message-ID: Thanks, will check it out! 2011/2/3 Noah Hall > On Thu, Feb 3, 2011 at 11:11 AM, C.Y. Ruhulessin > wrote: > > For an application that I am designing, i'd like to achieve the same > > functionality, so the end users don't have to bother installing Python > > themselves. > > Can anybody shed their lights on how one would program this? > > kind regards, > > > There are applications, such as http://www.py2exe.org/ and > http://www.pyinstaller.org/ that you can use to achieve the same > thing. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Feb 3 14:15:34 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Feb 2011 14:15:34 +0100 Subject: [Tutor] RE module is working ? References: <4D49AEC3.7020900@free.fr> Message-ID: Karim wrote: > I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 > consecutives double quotes: > > * *In Python interpreter:* > > $ python > Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) > [GCC 4.4.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> expression = *' "" '* > >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) > Traceback (most recent call last): > File "", line 1, in > File "/home/karim/build/python/install/lib/python2.7/re.py", line > 162, in subn > return _compile(pattern, flags).subn(repl, string, count) > File "/home/karim/build/python/install/lib/python2.7/re.py", line > 278, in filter > return sre_parse.expand_template(template, match) > File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", > line 787, in expand_template > raise error, "unmatched group" > sre_constants.error: unmatched group > > But if I remove '?' I get the following: > > >>> re.subn(r'([^\\])"', r'\1\\"', expression) > (' \\"" ', 1) > > Only one substitution..._But this is not the same REGEX._ And the > count=2 does nothing. By default all occurrence shoul be substituted. > > * *On linux using my good old sed command, it is working with my '?' > (0-1 match):* > > *$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'* > \"\" > > *Indeed what's the matter with RE module!?* You should really fix the problem with your email program first; afterwards it's probably a good idea to try and explain your goal clearly, in plain English. Yes. What Steven said ;) Now to your question as stated: if you want to escape two consecutive double quotes that can be done with s = s.replace('""', '\"\"') but that's probably *not* what you want. Assuming you want to escape two consecutive double quotes and make sure that the first one isn't already escaped, this is my attempt: >>> def sub(m): ... s = m.group() ... return r'\"\"' if s == '""' else s ... >>> print re.compile(r'[\\].|""').sub(sub, r'\\\"" \\"" \"" "" \\\" \\" \"') \\\"" \\\"\" \"" \"\" \\\" \\" \" Compare that with $ echo '\\\"" \\"" \"" "" \\\" \\" \"' | sed 's/\([^\\]\)\?"/\1\\"/g' \\\"\" \\"\" \"\" \"\" \\\\" \\\" \\" Concerning the exception and the discrepancy between sed and python's re, I suggest that you ask it again on comp.lang.python aka the python-list mailing list where at least one regex guru will read it. Peter From rafadurancastaneda at gmail.com Thu Feb 3 14:34:28 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Thu, 3 Feb 2011 14:34:28 +0100 Subject: [Tutor] question about locale.setlocale Message-ID: Hi all, I'm new in Python, so I'm reading 3.1 tutorial and now I've got a question about locale.setlocale function. I've tryed in python idle this: import locale locale.setlocale(locale.LC_ALL, 'English_United States.1252') and i got: Traceback (most recent call last): File "", line 1, in locale.setlocale(locale.LC_ALL,'English_United States.1252') File "/usr/lib/python3.1/locale.py", line 527, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting After that I checked locale.py trying to know which locale settings are supported I found: def setlocale(category, value=None): """ setlocale(integer,string=None) -> string. Activates/queries locale processing. """ if value not in (None, '', 'C'): raise Error('_locale emulation only supports "C" locale') return 'C' So here I can use only default (es_ES.utf8) and C locales, but how can I use any other locale? Bye -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Feb 3 15:44:07 2011 From: emile at fenx.com (Emile van Sebille) Date: Thu, 03 Feb 2011 06:44:07 -0800 Subject: [Tutor] Defining Exceptions In-Reply-To: <629683.83329.qm@web130221.mail.mud.yahoo.com> References: <629683.83329.qm@web130221.mail.mud.yahoo.com> Message-ID: Hi Tom, First, you sent this only to me -- be sure to reply all so that the group can participate. On 2/2/2011 10:25 AM Tom Brauch said... > Thanks, Emile. > > If I replace the question marks in my script with break it throws out > everything before the break (<) and gives me the header starting at 4 - > Display. > > Knowing that it works to that point I was hoping to be able to tell the > script to throw out everything before the "T," at the end of the header in > which case I get only the data. > > How do I define "T," so that python recognizes it? Is it an iteration? You need to understand the structures you're working with. lines is a list that you created with "lines = resp.split('\r\n')" -- add a line immediately after this that reads : "for ii in lines: print ii" (or print(ii) if you're on v3+ are you?) -- that'll show you what you've got. Paste the results in your reply. If the line you're interested in literally is the only one that has ',T,' in it, you could keep the part after that more easily with something like: ... ser.write('3') resp=buffer_read(ser) waste,goodlines = resp.split(",T,") ... and go from there using goodlines. HTH, Emile > > Sorry I can't ask more intelligent questions but I'm truly just getting > started. > > Thanks again! > Tom > > > On Wed, Feb 2, 2011 at 10:58 AM, Emile van Sebille wrote: > >> On 2/2/2011 6:51 AM Tom Brauch said... >> >> All, >>> >>> I am a python neophyte and not terrible well versed in programming (as >>> will >>> become obvious shortly) >>> >>> I have a script which is reading a serial device on a schedule. The >>> device >>> outputs a header at the beginning of every read. I have a data file which >>> I >>> am appending and would like to eliminate the header so that I end up with >>> one master data file. A copy of the serial readout is: >>> >>> * >>> >>>> >>>> 6CSV Type Reports2 - Display All Data3 - Display New Data4 - Display >>> Last >>> Data5 - Display All Flow Stats6 - Display New Flow Stats7 - Display All >>> 5-Min Flow8 - Display New 5-Min Flow9 - Display Error Log> >>> 4 - Display CSV DataStation, >>> >>> 1Time,Conc(mg/m3),Qtot(m3),no(V),WS(MPS),no(V),RH(%),no(V),AT(C),E,U,M,I,L,R,N,F,P,D,C,T,02/02/11 >>> 08:00, 0.042, 0.701, 0.004, 0.1, 0.002, 7, 0.012, >>> -18.0,0,0,0,0,0,0,0,0,0,0,0,0, >>> >>> I am only interested in the information following the T, in the header. I >>> have tried to use an exception to have the script throw out all data prior >>> to the T, in the header but I don't know how to define this excecption. >>> My >>> current script looks as follows: >>> >>> def cycle(ser,prefix): >>> inRecovery=False >>> resp=False >>> # tm.sleep(30.0) >>> ser.open() >>> tm.sleep(2) >>> ser.write('\n\r\n\r\n\r') >>> resp=buffer_read(ser) >>> >>> ser.write('6') >>> resp=buffer_read(ser) >>> >>> ser.write('3') >>> resp=buffer_read(ser) >>> lines = resp.split('\r\n') >>> waste=lines.pop() >>> >> >> pop changes lines by discarding the end of the list. So your subsequent >> remove fails because waste is no longer in the list. >> >> Perhaps waste is the data you're looking for? >> >> sprinkle some prints through here so you can see what values you're dealing >> with. That's a common technique to help figure out what's wrong. >> >> HTH, >> >> Emile >> >> >> while True: >>> try: >>> lines.remove(waste) >>> except Exception: >>> ?????? >>> for x,row in enumerate(lines): >>> lines[x]=row.split(',') >>> if DEBUG: print lines >>> f=open(prefix,'a') >>> csvf = csv.writer(f) >>> csvf.writerows(lines) >>> f.close() >>> ser.close() >>> >>> How do I define the exception so that I get only the data following the >>> header? >>> >>> Thanks! >>> Tomb >>> >>> From smokeinourlights at gmail.com Thu Feb 3 16:28:37 2011 From: smokeinourlights at gmail.com (Doug Marvel) Date: Thu, 3 Feb 2011 10:28:37 -0500 Subject: [Tutor] print "Hello, World!" In-Reply-To: References: <99556.52199.qm@web130220.mail.mud.yahoo.com> Message-ID: Holy wow! I'm going to go through all of these and see what sort of understanding I can absorb. I'm super excited that a helpful community exists for this, but I'm more excited to start learning. So I'm going to go do that now. I'm starting with Alan Gauld's tutorial, but like I said, I'm going to check out all of them, until I build some confidence. So far, this one seems to run at my speed. I'll be back, for certain. It took me twenty minutes to figure out how to get the ">>>" to come up in DOS after typing 'python'. hahaha It's good to meet all of you, and thanks again. Doug On Thu, Feb 3, 2011 at 6:07 AM, Alan Gauld wrote: > "michael scott" wrote > >> already been asked, learn from others who asked before you :) Oh yea, I >> once >> read that there are no intermediate tutorials in any programming language, >> because once you get past the basics, you only need to reference the >> "documentation" that comes with the language. > > Thats very nearly true. There are intermediate level tutorials for a few > languages but more generally you get subject specific tutorials on > things like parsing, web programming, GUI programming, databases, > networking, stats and scientific programming etc etc. > > So there are usually intermediate level tutorials to suit they are rarely > full language tutorials. > > I try to cover that off with the advanced topics and "Python in practice" > topics at the end of my tutorial. But again they are focused on specific > topic areas (OS, database, networks, web). > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From patty at cruzio.com Thu Feb 3 18:18:24 2011 From: patty at cruzio.com (Patty) Date: Thu, 3 Feb 2011 09:18:24 -0800 Subject: [Tutor] Changing Python icon - 2.6 and 3.2 Message-ID: <0322ACB2B4B040FAAF092CCDFC0CAD29@mycomputer> Hello Folks - I have Python 2.6.6 on my Windows 7 system and installed Python 3.2. Now I want to be able to differentiate between the versions and the icon for each version of Python is the same. I figured I would change the the four application files in the C:\Python26 directory - python; python26; pythonw; pythonw26 - and give them new picture icons. But when I select any of these files and choose 'properties', there is no option to change the application icon. I looked online but the questions were not exactly the same as this one and pertained to earlier versions of Python anyway. I discovered this when I was trying to associate a folder with 2.6 based programs so that it would always execute the programs with the python 2.6 .exe. And both Pythons come up as a choice with no details indicating which is which, except a lucky guess. It does appear that I can change the actual name of the application (the field with the name allows me to edit) but that is not what I wanted to do, also unsure if that would cause a problem in other parts of the application down the road if I was changing names like that. Thanks for suggestions - Patty -------------- next part -------------- An HTML attachment was scrubbed... URL: From subscriptions at cagttraining.com Thu Feb 3 18:29:13 2011 From: subscriptions at cagttraining.com (Bill Felton) Date: Thu, 3 Feb 2011 12:29:13 -0500 Subject: [Tutor] Changing Python icon - 2.6 and 3.2 In-Reply-To: <0322ACB2B4B040FAAF092CCDFC0CAD29@mycomputer> References: <0322ACB2B4B040FAAF092CCDFC0CAD29@mycomputer> Message-ID: I haven't tried this on Windows 7 yet, but what I did on my Mac was to create shortcuts and rename those. I generally launch from shortcuts, so this leaves the app names alone but gives me the information I need to launch what I intend. You should be able to do something similar on Windows. regards, Bill On Feb 3, 2011, at 12:18 PM, Patty wrote: > Hello Folks - I have Python 2.6.6 on my Windows 7 system and installed Python 3.2. Now I want to be able to differentiate between the versions and the icon for each version of Python is the same. I figured I would change the the four application files in the C:\Python26 directory - python; python26; pythonw; pythonw26 - and give them new picture icons. But when I select any of these files and choose 'properties', there is no option to change the application icon. I looked online but the questions were not exactly the same as this one and pertained to earlier versions of Python anyway. I discovered this when I was trying to associate a folder with 2.6 based programs so that it would always execute the programs with the python 2.6 .exe. And both Pythons come up as a choice with no details indicating which is which, except a lucky guess. > > It does appear that I can change the actual name of the application (the field with the name allows me to edit) but that is not what I wanted to do, also unsure if that would cause a problem in other parts of the application down the road if I was changing names like that. > > Thanks for suggestions - > Patty > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From patty at cruzio.com Thu Feb 3 18:38:11 2011 From: patty at cruzio.com (Patty) Date: Thu, 3 Feb 2011 09:38:11 -0800 Subject: [Tutor] print "Hello, World!" References: <99556.52199.qm@web130220.mail.mud.yahoo.com> Message-ID: <5D0D40F584334C62BFE5A2B92ABD1EE4@mycomputer> Hello Doug - My very first document I read - before I took an online course - was "A Quick, Painless Tutorial on the Python Language" by Norman Matloff from UC Davis. My copy is dated May 1, 2009 but I think he has updated it -- looks like May 2010. Here is the link, you may also want to query for other links like this for Matloff because I saw a few others while looking this up for you. It is free. http://html-pdf-converter.com/pdf/a-quick-painless-tutorial-on-the-python-language.html I also liked Alan Gauld's tutorial and the videos made by Google - taught by Nick Parlante - Here is the link: http://code.google.com/edu/languages/google-python-class/ I was not really happy with the actual course I took. You can contact me offline about this. Regards, Patty ----- Original Message ----- From: "Doug Marvel" To: ; Sent: Thursday, February 03, 2011 7:28 AM Subject: Re: [Tutor] print "Hello, World!" Holy wow! I'm going to go through all of these and see what sort of understanding I can absorb. I'm super excited that a helpful community exists for this, but I'm more excited to start learning. So I'm going to go do that now. I'm starting with Alan Gauld's tutorial, but like I said, I'm going to check out all of them, until I build some confidence. So far, this one seems to run at my speed. I'll be back, for certain. It took me twenty minutes to figure out how to get the ">>>" to come up in DOS after typing 'python'. hahaha It's good to meet all of you, and thanks again. Doug On Thu, Feb 3, 2011 at 6:07 AM, Alan Gauld wrote: > "michael scott" wrote > >> already been asked, learn from others who asked before you :) Oh yea, I >> once >> read that there are no intermediate tutorials in any programming >> language, >> because once you get past the basics, you only need to reference the >> "documentation" that comes with the language. > > Thats very nearly true. There are intermediate level tutorials for a few > languages but more generally you get subject specific tutorials on > things like parsing, web programming, GUI programming, databases, > networking, stats and scientific programming etc etc. > > So there are usually intermediate level tutorials to suit they are rarely > full language tutorials. > > I try to cover that off with the advanced topics and "Python in practice" > topics at the end of my tutorial. But again they are focused on specific > topic areas (OS, database, networks, web). > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From marc.tompkins at gmail.com Thu Feb 3 19:22:32 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 3 Feb 2011 10:22:32 -0800 Subject: [Tutor] Changing Python icon - 2.6 and 3.2 In-Reply-To: <0322ACB2B4B040FAAF092CCDFC0CAD29@mycomputer> References: <0322ACB2B4B040FAAF092CCDFC0CAD29@mycomputer> Message-ID: On Thu, Feb 3, 2011 at 9:18 AM, Patty wrote: > Hello Folks - I have Python 2.6.6 on my Windows 7 system and installed > Python 3.2. Now I want to be able to differentiate between the versions and > the icon for each version of Python is the same. I figured I would change > the the four application files in the C:\Python26 directory - python; > python26; pythonw; pythonw26 - and give them new picture icons. But when > I select any of these files and choose 'properties', there is no option to > change the application icon. I looked online but the questions were not > exactly the same as this one and pertained to earlier versions of Python > anyway. I discovered this when I was trying to associate a folder with 2.6 > based programs so that it would always execute the programs with the python > 2.6 .exe. And both Pythons come up as a choice with no details indicating > which is which, except a lucky guess. > > It does appear that I can change the actual name of the application (the > field with the name allows me to edit) but that is not what I wanted to do, > also unsure if that would cause a problem in other parts of the application > down the road if I was changing names like that. > Windows EXEs are generally built with one or more icon images packaged inside them; at build time, the developer chooses which one s/he wants to be the regular display icon. As an end user, you generally cannot choose which of the built-in images Windows will choose to display when you look at the EXE in a directory listing - Windows sticks with the developer's choice. However, when you create a shortcut - or modify one that's already been created - you have free choice of which icon you want to use. Typically when you click the "Change Icon" button, you'll see the icons that are contained in the EXE itself, but you can choose any other icon image file on your computer - even icons that are contained in completely different EXEs. Unfortunately, none of that helps with what you're trying to do. You want to change the name/description that was registered with Default Programs when your versions of Python were installed... and as near as I can tell, the Python installers don't "register" with Default Programs at all. ("Default Programs" is the Vista/7/Longhorn version of... whatever you call this mess.) When an installer doesn't provide the information for registration, Windows defaults to the executable name (which is "python.exe" in both cases) and the executable's default icon (which, as you've noticed, hasn't changed between versions either.) This page describes the registry keys that could/should be set: http://msdn.microsoft.com/en-us/library/cc144154%28v=vs.85%29.aspx#post_install but I don't know whether messing with them by hand is likely to be either safe or effective. However, one thing you CAN do is to create shortcuts for the actual .py or .pyw files themselves, and in the shortcut's command line specify the path to the Python executable you want to use (e.g. "C:\Python26\pythonw.exe C:\Users\Patty\Desktop\PythonProj26\myprog.py".) If we're talking about just a few files, that could be doable. For more than about a dozen, it would be an unbelievable pain. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Thu Feb 3 19:47:22 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 03 Feb 2011 19:47:22 +0100 Subject: [Tutor] RE module is working ? In-Reply-To: References: <4D49AEC3.7020900@free.fr> Message-ID: <4D4AF83A.9030706@free.fr> On 02/03/2011 02:15 PM, Peter Otten wrote: > Karim wrote: > >> I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 >> consecutives double quotes: >> >> * *In Python interpreter:* >> >> $ python >> Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) >> [GCC 4.4.3] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> expression = *' "" '* >> >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) >> Traceback (most recent call last): >> File "", line 1, in >> File "/home/karim/build/python/install/lib/python2.7/re.py", line >> 162, in subn >> return _compile(pattern, flags).subn(repl, string, count) >> File "/home/karim/build/python/install/lib/python2.7/re.py", line >> 278, in filter >> return sre_parse.expand_template(template, match) >> File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", >> line 787, in expand_template >> raise error, "unmatched group" >> sre_constants.error: unmatched group >> >> But if I remove '?' I get the following: >> >> >>> re.subn(r'([^\\])"', r'\1\\"', expression) >> (' \\"" ', 1) >> >> Only one substitution..._But this is not the same REGEX._ And the >> count=2 does nothing. By default all occurrence shoul be substituted. >> >> * *On linux using my good old sed command, it is working with my '?' >> (0-1 match):* >> >> *$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'* >> \"\" >> >> *Indeed what's the matter with RE module!?* > You should really fix the problem with your email program first; Thunderbird issue with bold type (appears as stars) but I don't know how to fix it yet. > afterwards > it's probably a good idea to try and explain your goal clearly, in plain > English. I already did it. (cf the mails queue). But to resume I pass the expression string to TCL command which delimits string with double quotes only. Indeed I get error with nested double quotes => That's the key problem. > Yes. What Steven said ;) > > Now to your question as stated: if you want to escape two consecutive double > quotes that can be done with > > s = s.replace('""', '\"\"') > I have already done it as a workaround but I have to add another replacement before to consider all other cases. I want to make the original command work to suppress the workaround. > but that's probably *not* what you want. Assuming you want to escape two > consecutive double quotes and make sure that the first one isn't already > escaped, You hit it !:-) > this is my attempt: > >>>> def sub(m): > ... s = m.group() > ... return r'\"\"' if s == '""' else s > ... >>>> print re.compile(r'[\\].|""').sub(sub, r'\\\"" \\"" \"" "" \\\" \\" \"') That is not the thing I want. I want to escape any " which are not already escaped. The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have made regex on unix since 15 years). For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"' '?' is not accepted Why? character which should not be an antislash with 0 or 1 occurence. This is quite simple. I am a poor tradesman but I don't deny evidence. Regards Karim > \\\"" \\\"\" \"" \"\" \\\" \\" \" > > Compare that with > > $ echo '\\\"" \\"" \"" "" \\\" \\" \"' | sed 's/\([^\\]\)\?"/\1\\"/g' > \\\"\" \\"\" \"\" \"\" \\\\" \\\" \\" > > Concerning the exception and the discrepancy between sed and python's re, I > suggest that you ask it again on comp.lang.python aka the python-list > mailing list where at least one regex guru will read it. > > Peter > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From dgoering at gmail.com Thu Feb 3 20:24:24 2011 From: dgoering at gmail.com (David Goering) Date: Thu, 03 Feb 2011 20:24:24 +0100 Subject: [Tutor] Ideas and good examples Message-ID: <4D4B00E8.4040208@gmail.com> Hello, this is my first message here... and come to think of it my first Message in a Mailing List what so ever. So a moment of epic historical importance :) Anyway I decided I wanted to learn Python as I didn't really know any scripting language yet and I have heard great things about Python. I already have some experience in Java and minor experience in C languages... so I think I will pick up on the syntax pretty quickly (just have to get used to not using braces and indent my code correctly :D ) Anyhow my programming knowledge is based off classes and less off of practically using them a lot... So I have implemented various algorithms etc. but haven't written many full programs from beginning to end. And that is basically my question / problem. I don't have many good ideas and I don't really have a lot of experience with going from an idea to a full scale program. So I guess I have two questions: 1) Does anyone have ideas for small - mid ranged projects where I could quickly pick up on the pitfalls of Python but that is also useful in some way ? I had a small idea where I could write a program to sync two folders mp3 files based on filename and ID3 Tags with a GUI to control it, but would love to hear other ideas. 2) Is there some tutorial out there that really leads you from scratch to a full blown program (with GUI or Database connection or whatever) with Code documentation etc. just to see how one could approach it Anyway, I have already learned a lot from leeching off the mailing list, so thanks for that. Greetings from Germany, David From tim at johnsons-web.com Thu Feb 3 20:19:51 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 3 Feb 2011 10:19:51 -0900 Subject: [Tutor] Namespace variables vs. instantiation keywords - best practices Message-ID: <20110203191951.GC21227@johnsons-web.com> FYI: Python 2.6.5 on Linux. FYI: I am a web programmer of 24 years experience programming, 9 with python, but have never had the advantage of working with a senior programmer as a mentor. I am investigating the best practices of instantiating an object with a large amount of options. I would also request that when the reader sees me using terminology that is not pythonic that I be corrected. That will help me to better communicate my practices and researching this topic via search engines. I'm redesigning a large system to an MVC architecture. To make a long story short, I and clients have chosen *not* to adapt this system to an existing framework such as django, but to develop and original framework with an eye towards integrating with something like django in the future. # Bootstrapping: An executable script imports a 'site module' that sets up a project-specific environment. # Managing content I have developed a view (template) module for which most of the heavy lifting is done. The interface to the class looks like this: def __init__(self,**kw): ## Consider that all code examples are pseudo-code """ tmpl.py Purpose - python templating features Author - Me - Me at mydomain.com """ ## I will use two public module variables as an example: ## default variables in the module namespace templatepath = "templates" ## default value projectname = "" ## must be intialized ## Object variables in the class namespace ## Initialized from the public module variables self.templatepath = templatepath self.prj = projectname ## Intialization loop. Defaults can be 'overridden' for k in kw: if k in self.__dict__: self.__dict__[k] = kw[k] else : ## raise exception #instantiation code might look like this: content = LoadView(prj="myproject",templatepath="views") # or kws = {"prj":"myproject","templatepath":"views"} content = LoadView(**kws) # OR (project config file) kws = load.config("myconfig","tmpl_kws") kws.update({"prj":"myproject","templatepath":"views"}) kws = {"prj":"myproject","templatepath":"views"} # OR - use the site module - example site module code follows: ## Import the module containing the `LoadView' class import tmpl ## set the module namespace variables. tmpl.projectname = MyProject tmpl.templatepath = TemplatePath ## Calling module settings follow..... I've received some very helpful comments in the past by senior members of this ML and perhaps this topic may help other as well as myself TIA -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From oberoc at gmail.com Thu Feb 3 20:53:41 2011 From: oberoc at gmail.com (Tino Dai) Date: Thu, 3 Feb 2011 14:53:41 -0500 Subject: [Tutor] Ideas and good examples In-Reply-To: <4D4B00E8.4040208@gmail.com> References: <4D4B00E8.4040208@gmail.com> Message-ID: On Thu, Feb 3, 2011 at 2:24 PM, David Goering wrote: > Hello, > this is my first message here... and come to think of it my first Message > in a Mailing List what so ever. So a moment of epic historical importance :) > Anyway I decided I wanted to learn Python as I didn't really know any > scripting language yet and I have heard great things about Python. > I already have some experience in Java and minor experience in C > languages... so I think I will pick up on the syntax pretty quickly (just > have to get used to not using braces and indent my code correctly :D ) > Anyhow my programming knowledge is based off classes and less off of > practically using them a lot... So I have implemented various algorithms > etc. but haven't written many full programs from beginning to end. > And that is basically my question / problem. I don't have many good ideas > and I don't really have a lot of experience with going from an idea to a > full scale program. > So I guess I have two questions: > 1) Does anyone have ideas for small - mid ranged projects where I could > quickly pick up on the pitfalls of Python but that is also useful in some > way ? I had a small idea where I could write a program to sync two folders > mp3 files based on filename and ID3 Tags with a GUI to control it, but would > love to hear other ideas. > Start reading Dive into Python http://diveintopython.org/ . He has an example like that > 2) Is there some tutorial out there that really leads you from scratch to a > full blown program (with GUI or Database connection or whatever) with Code > documentation etc. just to see how one could approach it > Start with TKinter or a framework like Django. Please note that Django is out of scope for this list, but there are plenty of good resources out on the net. Finally you should check out Alan Gauld's page: http://www.freenetpages.co.uk/hp/alan.gauld/ and Kent Johnson page: http://personalpages.tds.net/~kent37/blog/ Welcome! Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Thu Feb 3 20:54:38 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 3 Feb 2011 10:54:38 -0900 Subject: [Tutor] Namespace variables vs. instantiation keywords - best practices In-Reply-To: <20110203191951.GC21227@johnsons-web.com> References: <20110203191951.GC21227@johnsons-web.com> Message-ID: <20110203195438.GD21227@johnsons-web.com> * Tim Johnson [110203 10:34]: > # OR (project config file) > kws = load.config("myconfig","tmpl_kws") > kws.update({"prj":"myproject","templatepath":"views"}) #Grr! The following line is wrong .. > kws = {"prj":"myproject","templatepath":"views"} Should be #content = LoadView(**kws) sorry -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From davea at ieee.org Thu Feb 3 23:20:29 2011 From: davea at ieee.org (Dave Angel) Date: Thu, 03 Feb 2011 17:20:29 -0500 Subject: [Tutor] RE module is working ? In-Reply-To: <4D4AF83A.9030706@free.fr> References: <4D49AEC3.7020900@free.fr> <4D4AF83A.9030706@free.fr> Message-ID: <4D4B2A2D.8050306@ieee.org> On 01/-10/-28163 02:59 PM, Karim wrote: > On 02/03/2011 02:15 PM, Peter Otten wrote: >> Karim wrote: >> (snip> >>> *Indeed what's the matter with RE module!?* >> You should really fix the problem with your email program first; > Thunderbird issue with bold type (appears as stars) but I don't know how > to fix it yet. The simple fix is not to try to add bold or colors on a text message. Python-tutor is a text list, not an html one. Thunderbird tries to accomodate you by adding the asterisks, which is fine if it's regular English. But in program code, it's obviously confuses things. While I've got you, can I urge you not to top-post? In this message, you correctly added your remarks after the part you were quoting. But many times you put your comments at the top, which is backwards. DaveA -- -- davea at ieee.org From karim.liateni at free.fr Thu Feb 3 23:27:38 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 03 Feb 2011 23:27:38 +0100 Subject: [Tutor] RE module is working ? In-Reply-To: <4D4B2A2D.8050306@ieee.org> References: <4D49AEC3.7020900@free.fr> <4D4AF83A.9030706@free.fr> <4D4B2A2D.8050306@ieee.org> Message-ID: <4D4B2BDA.4060201@free.fr> On 02/03/2011 11:20 PM, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, Karim wrote: >> On 02/03/2011 02:15 PM, Peter Otten wrote: >>> Karim wrote: >>> (snip> >>>> *Indeed what's the matter with RE module!?* >>> You should really fix the problem with your email program first; >> Thunderbird issue with bold type (appears as stars) but I don't know how >> to fix it yet. > > The simple fix is not to try to add bold or colors on a text message. > Python-tutor is a text list, not an html one. Thunderbird tries to > accomodate you by adding the asterisks, which is fine if it's regular > English. But in program code, it's obviously confuses things. > > While I've got you, can I urge you not to top-post? In this message, > you correctly added your remarks after the part you were quoting. But > many times you put your comments at the top, which is backwards. > > DaveA > Sorry Dave, I will try and do my best to avoid bold and top-post in the future. Regards Karim From karim.liateni at free.fr Fri Feb 4 00:23:19 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 04 Feb 2011 00:23:19 +0100 Subject: [Tutor] RE module is working ? In-Reply-To: <4D4AF83A.9030706@free.fr> References: <4D49AEC3.7020900@free.fr> <4D4AF83A.9030706@free.fr> Message-ID: <4D4B38E7.1090100@free.fr> On 02/03/2011 07:47 PM, Karim wrote: > On 02/03/2011 02:15 PM, Peter Otten wrote: >> Karim wrote: >> >>> I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 >>> consecutives double quotes: >>> >>> * *In Python interpreter:* >>> >>> $ python >>> Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) >>> [GCC 4.4.3] on linux2 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> expression = *' "" '* >>> >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*) >>> Traceback (most recent call last): >>> File "", line 1, in >>> File "/home/karim/build/python/install/lib/python2.7/re.py", line >>> 162, in subn >>> return _compile(pattern, flags).subn(repl, string, count) >>> File "/home/karim/build/python/install/lib/python2.7/re.py", line >>> 278, in filter >>> return sre_parse.expand_template(template, match) >>> File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", >>> line 787, in expand_template >>> raise error, "unmatched group" >>> sre_constants.error: unmatched group >>> >>> But if I remove '?' I get the following: >>> >>> >>> re.subn(r'([^\\])"', r'\1\\"', expression) >>> (' \\"" ', 1) >>> >>> Only one substitution..._But this is not the same REGEX._ And the >>> count=2 does nothing. By default all occurrence shoul be substituted. >>> >>> * *On linux using my good old sed command, it is working with >>> my '?' >>> (0-1 match):* >>> >>> *$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'* >>> \"\" >>> >>> *Indeed what's the matter with RE module!?* >> You should really fix the problem with your email program first; > Thunderbird issue with bold type (appears as stars) but I don't know > how to fix it yet. >> afterwards >> it's probably a good idea to try and explain your goal clearly, in plain >> English. > > I already did it. (cf the mails queue). But to resume I pass the > expression string to TCL command which delimits string with double > quotes only. > Indeed I get error with nested double quotes => That's the key problem. >> Yes. What Steven said ;) >> >> Now to your question as stated: if you want to escape two consecutive >> double >> quotes that can be done with >> >> s = s.replace('""', '\"\"') >> > I have already done it as a workaround but I have to add another > replacement before to consider all other cases. > I want to make the original command work to suppress the workaround. > > >> but that's probably *not* what you want. Assuming you want to escape two >> consecutive double quotes and make sure that the first one isn't already >> escaped, > > You hit it !:-) > >> this is my attempt: >> >>>>> def sub(m): >> ... s = m.group() >> ... return r'\"\"' if s == '""' else s >> ... >>>>> print re.compile(r'[\\].|""').sub(sub, r'\\\"" \\"" \"" "" \\\" >>>>> \\" \"') > > That is not the thing I want. I want to escape any " which are not > already escaped. > The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have > made regex on unix since 15 years). > > For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"' > '?' is not accepted Why? character which should not be an antislash > with 0 or 1 occurence. This is quite simple. > > I am a poor tradesman but I don't deny evidence. Recall: >>> re.subn(r'([^\\])?"', r'\1\\"', expression) Traceback (most recent call last): File "", line 1, in File "/home/karim/build/python/install/lib/python2.7/re.py", line 162, in subn return _compile(pattern, flags).subn(repl, string, count) File "/home/karim/build/python/install/lib/python2.7/re.py", line 278, in filter return sre_parse.expand_template(template, match) File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", line 787, in expand_template raise error, "unmatched group" sre_constants.error: unmatched group Found the solution: '?' needs to be inside parenthesis (saved pattern) because outside we don't know if the saved match argument will exist or not namely '\1'. >>> re.subn(r'([^\\]?)"', r'\1\\"', expression) (' \\"\\" ', 2) sed unix command is more permissive: sed 's/\([^\\]\)\?"/\1\\"/g' because '?' can be outside parenthesis (saved pattern but escaped for sed). \1 seems to not cause issue when matching is found. Perhaps it is created only when match occurs. MORALITY: 1) Behaviour of python is logic and I must understand what I do with it. 2) sed is a fantastic tool because it manages match value when missing. 3) I am a real poor tradesman Regards Karim > > Regards > Karim > >> \\\"" \\\"\" \"" \"\" \\\" \\" \" >> >> Compare that with >> >> $ echo '\\\"" \\"" \"" "" \\\" \\" \"' | sed 's/\([^\\]\)\?"/\1\\"/g' >> \\\"\" \\"\" \"\" \"\" \\\\" \\\" \\" >> >> Concerning the exception and the discrepancy between sed and python's >> re, I >> suggest that you ask it again on comp.lang.python aka the python-list >> mailing list where at least one regex guru will read it. >> >> Peter >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Feb 4 00:32:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 3 Feb 2011 23:32:39 -0000 Subject: [Tutor] RE module is working ? References: <4D49AEC3.7020900@free.fr> <4D4A86E6.3000901@pearwood.info> <4D4A9577.6080107@free.fr> Message-ID: "Karim" wrote > Because expression = *' "" '* is in fact fact expression = ' "" '. > The bold appear as stars I don't know why. Because in the days when email was always sent in plain ASCII text the way to show "bold" was to put asterisks around it. Underlining used _underscores_ like so... Obviously somebody decided that Thunderbird would stick with those conventions when translating HTML to text :-) Quite smart really :-) Alan G. From eike.welk at gmx.net Fri Feb 4 00:55:10 2011 From: eike.welk at gmx.net (Eike Welk) Date: Fri, 4 Feb 2011 00:55:10 +0100 Subject: [Tutor] System of ODEs Question In-Reply-To: References: Message-ID: <201102040056.47322.eike.welk@gmx.net> Hello Eric! On Thursday 03.02.2011 08:05:13 Eric Lofgren wrote: > def eq_system(PopIn,x): > '''Defining SIR System of Equations''' > #Creating an array of equations > Eqs= np.zeros((3)) > Eqs[0]= -beta * PopIn[0]*PopIn[1] > Eqs[1]= beta * PopIn[0]*PopIn[1] - gamma*PopIn[1] > Eqs[2]= gamma*PopIn[1] > return Eqs > > SIR = spi.odeint(eq_system, PopIn, t_interval) > print SIR > The part that is confusing me is defining the function. Namely, it seems to > need two arguments - the first needs to be the initial states of the > population being modeled, but the second...it doesn't seem to matter what > it is. Originally, I didn't include it at all, and the program was very, > very unhappy - looking back at the example, it had a second argument, so I > put one in, and magically, it worked. But it can be x, it can be t, it can > be anything. The meaning of the arguments of the system function (`eq_system` in your code) is as follows: 1. (`PopIn` in your code) the current state of the system 2. (`x` in your code) the current time The arguments can have any namem, you are free to choose what you think is most appropriate. The documentation is here: http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html In your system function the time is not used because the system is time invariant. But in a more advanced model you might use the time too, for example the virus particles might survive longer outside the human body in winter (`beta` a function of time). I think a good way to write system functions is like this: def sir_system(states, time): '''Defining SIR System of Equations''' s, i, r = states ds_dt = -beta * s * i di_dt = beta * s * i - gamma * i dr_dt = gamma * i return np.array([ds_dt, di_dt, dr_dt]) Eike. From alan.gauld at btinternet.com Fri Feb 4 01:00:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Feb 2011 00:00:02 -0000 Subject: [Tutor] 'Installing' Python at runtime? (Civilization) References: Message-ID: "C.Y. Ruhulessin" wrote > When I load up Civilization IV, a Firaxis game, the loading screen > tells me > "Loading Python". > > However, I can't seem to find out where it installs python It probably doesn't actually install Python it is simply loading the interpreter into memory. It probably uses Python as its macro language for configuration or customisation. To execute those scripts it will need to load a DLL containing the interpreter code. I don't know for sure but I'd guess that's what it means. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Feb 4 01:12:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Feb 2011 00:12:56 -0000 Subject: [Tutor] Ideas and good examples References: <4D4B00E8.4040208@gmail.com> Message-ID: "David Goering" wrote > 1) Does anyone have ideas for small - mid ranged projects where I > could quickly pick up on the pitfalls of Python but that is also > useful in some way ? Check the recent archives we had a very similar thread a week or two back. (And fairly regularly over the years!) > I had a small idea where I could write a program to sync two folders > mp3 files based on filename and ID3 Tags with a GUI to control it, > but would love to hear other ideas. Go for it, its as good as any to start with. The important thing is not getting the right project but just getting started on one. > 2) Is there some tutorial out there that really leads you from > scratch to a full blown program (with GUI or Database connection or > whatever) with Code documentation etc. just to see how one could > approach it Thats the intent of the Case Study at the end of my tutorial. It tries to pull together the threads of the tutor into a single, not too big, project It also includes a couple of false starts that worked then had to be taken out again. And the code evolves from a simple program to an OOP version to a GUI version. Its not partricularly pretty code but its deliberately done the way a typical newbie who had finished the tutor might go about things. If your library can get a copy of my book it has a second, much more methodical and "nicer", case study of a reusable games framework and 3 games built using it. It has a bit of design behind it with some diagrams and pseudo-code and a bit of prototyping at the >>> prompt work before diving into code. It is intended to show how an intermediate programmer might go about things. But due to some copyright complexities I can't put that one on the web site... :-( HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Feb 4 01:14:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Feb 2011 00:14:40 -0000 Subject: [Tutor] Ideas and good examples References: <4D4B00E8.4040208@gmail.com> Message-ID: "Tino Dai" wrote > Finally you should check out Alan Gauld's page: > http://www.freenetpages.co.uk/hp/alan.gauld/ That site has been locked for over 2 years. The new site has a lot of updates and, of course, a whole new rewrite of the tutor for v3! :-) See the sig... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mehgcap at gmail.com Fri Feb 4 01:41:17 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 3 Feb 2011 19:41:17 -0500 Subject: [Tutor] best practice: throw exception or set a flag? Message-ID: Hi all, I am wondering what the best way to do the following would be: throw an exception, or always return an object but set an error flag if something goes wrong? Here is an example: class c: def __init__(self): self.error=False def func(self, val): if val!=10: self.error=True someObj=c() someObj.func(5) if someObj.error: #do stuff OR: class c: def __init__(self): self.error=False def func(self, val): if val!=10: throw ValueError #I know the syntax is wrong someObj=c() try: someObj.func(5) except: #do stuff Which is the "standard" way when dealing with objects? Throw exceptions or always return an object, even if said object has an error and may therefore not have data beyond an error code and message? If I go the exception route, can I somehow put a message into the exception, maybe adding it as an attribute of my custom exception class? I assume so... except e: print e.message or something like that. I know I have research to do about the specifics of all this, but before I go off and look it all up I am wondering if it is the best way to go as far as standards and best coding practices. This is still that api wrapper, so I am not the only one who may end up using this file and I want to make it into something that is useable and does what people expect. TIA. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Fri Feb 4 01:57:21 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Feb 2011 11:57:21 +1100 Subject: [Tutor] print "Hello, World!" In-Reply-To: References: Message-ID: <4D4B4EF1.9020909@pearwood.info> Doug Marvel wrote: [...] > I am hoping for a link to a somewhat comprehensive online resource > that explains from the beginning in English, plain English, as this is > the only language I speak. Something to get my foot in the door would > be awesome. Another very important resource to use is the Python source code. As they say, "Use the Source, Luke!". The source code for the Python compiler itself is written in C, but Python comes with many standard library modules written in pure Python. They vary in size, complexity and clarity. Not all of them are "best practice", but none of them are truly bad. Under Linux, you can find the source code (usually) somewhere like this: /usr/lib/python2.5/ /usr/local/lib/python3.1/ You can find out where the source code lives this way: >>> import calendar >>> calendar.__file__ '/usr/local/lib/python3.1/calendar.py' or just use your operating system's Find Files utility to search for the file. Don't be concerned if some modules go completely over your head. They haven't been written for beginners. Nevertheless, they are a great way to see good quality Python code in action. If nothing else, you can read the comments and docstrings. However, let me give you a warning... unless you are an expert, it is *vital* that you treat these files as READ ONLY. If you start changing the files, you will confuse yourself greatly when things start mysteriously breaking, and everyone else says "It works for me when I try it". (Actually, even as an expert, you should be very wary about changing the standard library. If you do, it won't be *standard* any more, will it?) -- Steven From emile at fenx.com Fri Feb 4 01:58:33 2011 From: emile at fenx.com (Emile van Sebille) Date: Thu, 03 Feb 2011 16:58:33 -0800 Subject: [Tutor] best practice: throw exception or set a flag? In-Reply-To: References: Message-ID: On 2/3/2011 4:41 PM Alex Hall said... > Hi all, > I am wondering what the best way to do the following would be: throw > an exception, or always return an object but set an error flag if > something goes wrong? Here is an example: > > class c: > def __init__(self): > self.error=False > def func(self, val): > if val!=10: self.error=True > > someObj=c() > someObj.func(5) > if someObj.error: #do stuff > > OR: > > class c: > def __init__(self): > self.error=False > def func(self, val): > if val!=10: throw ValueError #I know the syntax is wrong > > someObj=c() > try: > someObj.func(5) > except: > #do stuff > > Which is the "standard" way when dealing with objects? Throw > exceptions or always return Yes, throw exceptions and always return the expected result. Expecting non-class (ie, external to the class) access to verify that the result is usable would be , I think, generally frowned upon. Emile From steve at pearwood.info Fri Feb 4 02:36:22 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Feb 2011 12:36:22 +1100 Subject: [Tutor] RE module is working ? In-Reply-To: <4D4AF83A.9030706@free.fr> References: <4D49AEC3.7020900@free.fr> <4D4AF83A.9030706@free.fr> Message-ID: <4D4B5816.6050708@pearwood.info> Karim wrote: >>> *Indeed what's the matter with RE module!?* >> You should really fix the problem with your email program first; > Thunderbird issue with bold type (appears as stars) but I don't know how > to fix it yet. A man when to a doctor and said, "Doctor, every time I do this, it hurts. What should I do?" The doctor replied, "Then stop doing that!" :) Don't add bold or any other formatting to things which should be program code. Even if it looks okay in *your* program, you don't know how it will look in other people's programs. If you need to draw attention to something in a line of code, add a comment, or talk about it in the surrounding text. [...] > That is not the thing I want. I want to escape any " which are not > already escaped. > The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have > made regex on unix since 15 years). Which regex? Perl regexes? sed or awk regexes? Extended regexes? GNU posix compliant regexes? grep or egrep regexes? They're all different. In any case, I am sorry, I don't think your regex does what you say. When I try it, it doesn't work for me. [steve at sylar ~]$ echo 'Some \"text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \\"text\" I wouldn't expect it to work. See below. By the way, you don't need to escape the brackets or the question mark: [steve at sylar ~]$ echo 'Some \"text"' | sed -re 's/([^\\])?"/\1\\"/g' Some \\"text\" > For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"' No it is not. The pattern you are matching does not do what you think it does. "Zero or one of not-backslash, followed by a quote" will match a single quote *regardless* of what is before it. This is true even in sed, as you can see above, your sed regex matches both quotes. \" will match, because the regular expression will match zero characters, followed by a quote. So the regex is correct. >>> match = r'[^\\]?"' # zero or one not-backslash followed by quote >>> re.search(match, r'aaa\"aaa').group() '"' Now watch what happens when you call re.sub: >>> match = r'([^\\])?"' # group 1 equals a single non-backslash >>> replace = r'\1\\"' # group 1 followed by \ followed by " >>> re.sub(match, replace, 'aaaa') # no matches 'aaaa' >>> re.sub(match, replace, 'aa"aa') # one match 'aa\\"aa' >>> re.sub(match, replace, '"aaaa') # one match, but there's no group 1 Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.1/re.py", line 166, in sub return _compile(pattern, flags).sub(repl, string, count) File "/usr/local/lib/python3.1/re.py", line 303, in filter return sre_parse.expand_template(template, match) File "/usr/local/lib/python3.1/sre_parse.py", line 807, in expand_template raise error("unmatched group") sre_constants.error: unmatched group Because group 1 was never matched, Python's re.sub raised an error. It is not a very informative error, but it is valid behaviour. If I try the same thing in sed, I get something different: [steve at sylar ~]$ echo '"Some text' | sed -re 's/([^\\])?"/\1\\"/g' \"Some text It looks like this version of sed defines backreferences on the right-hand side to be the empty string, in the case that they don't match at all. But this is not standard behaviour. The sed FAQs say that this behaviour will depend on the version of sed you are using: "Seds differ in how they treat invalid backreferences where no corresponding group occurs." http://sed.sourceforge.net/sedfaq3.html So you can't rely on this feature. If it works for you, great, but it may not work for other people. When you delete the ? from the Python regex, group 1 is always valid, and you don't get an exception. Or if you ensure the input always matches group 1, no exception: >>> match = r'([^\\])?"' >>> replace = r'\1\\"' >>> re.sub(match, replace, 'a"a"a"a') # group 1 always matches 'a\\"a\\"a\\"a' (It still won't do what you want, but that's a *different* problem.) Jamie Zawinski wrote: Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. How many hours have you spent trying to solve this problem using regexes? This is a *tiny* problem that requires an easy solution, not wrestling with a programming language that looks like line-noise. This should do what you ask for: def escape(text): """Escape any double-quote characters if and only if they aren't already escaped.""" output = [] escaped = False for c in text: if c == '"' and not escaped: output.append('\\') elif c == '\\': output.append('\\') escaped = True continue output.append(c) escaped = False return ''.join(output) Armed with this helper function, which took me two minutes to write, I can do this: >>> text = 'Some text with backslash-quotes \\" and plain quotes " together.' >>> print escape(text) Some text with backslash-quotes \" and plain quotes \" together. Most problems that people turn to regexes are best solved without regexes. Even Larry Wall, inventor of Perl, is dissatisfied with regex culture and syntax: http://dev.perl.org/perl6/doc/design/apo/A05.html -- Steven From dgoering at gmail.com Fri Feb 4 02:48:17 2011 From: dgoering at gmail.com (David Goering) Date: Fri, 04 Feb 2011 02:48:17 +0100 Subject: [Tutor] Ideas and good examples Message-ID: <4D4B5AE1.8040005@gmail.com> Hello, Thanks for the input so far. Alan I saw a Message about your website right after I sent away my question and it definetly looks like a good place to start... especially the sections from Advanced Topics onwards. It says v3 is Under Construction, how long do you expect it to be like this. Is it worth waiting or should I just go ahead with v2 ? Sorry if its a repeated question... I will sift through the Archives to find other ideas to similar questions. But anyway thanks so far, if someone still has new ideas or links they are always welcome :) -- David From sigzero at gmail.com Fri Feb 4 03:07:09 2011 From: sigzero at gmail.com (Robert) Date: Thu, 3 Feb 2011 21:07:09 -0500 Subject: [Tutor] Ideas and good examples References: <4D4B00E8.4040208@gmail.com> Message-ID: On 2011-02-03 19:14:40 -0500, Alan Gauld said: > "Tino Dai" wrote > >> Finally you should check out Alan Gauld's page: >> http://www.freenetpages.co.uk/hp/alan.gauld/ > > That site has been locked for over 2 years. The new > site has a lot of updates and, of course, a whole new > rewrite of the tutor for v3! :-) > > See the sig... That's awesome. I think I have the original book you did in storage (many moons ago). :-) -- Robert From steve at pearwood.info Fri Feb 4 03:11:52 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Feb 2011 13:11:52 +1100 Subject: [Tutor] best practice: throw exception or set a flag? In-Reply-To: References: Message-ID: <4D4B6068.8070606@pearwood.info> Alex Hall wrote: > Hi all, > I am wondering what the best way to do the following would be: throw > an exception, or always return an object but set an error flag if > something goes wrong? Raise an exception. Error flags are an anti-pattern -- a software idiom that you should not follow. The problem with flags is that callers will forget to check them, which leads to problems being revealed far away from where the problem was caused. That makes it *really* hard to debug. result = function(x) # fails and sets an error flag in result do_something_else() data = [1, 2, 'a', result, 'xyz'] # store another_function(data) # ... # ... # lots more code here # ... # ... x = data[3] do_something_with(x) which then blows up, because x is invalid but you haven't checked the error flag. The problem actually was with the *original* x, all the way back at the start, but that's been thrown away now, never to be seen again, which makes it hard to debug why it failed. A million, billion, trillion times worse is if you have a single global error flag! That's *disastrous*, because you MUST check the flag *immediately*, otherwise it can be cleared. x = function(100000000) # fails y = another_function(1000) if global_error_flag: # seems to be safe to use x process(x) # but it isn't, and this blows up the problem being that another_function makes a second call to function(), only this one succeeds and resets the global flag. If you do this, the ghost of a thousand programmers will drag your spirit off to the nether regions of Hell, where you will have to debug the Windows kernel using only the `ed` editor on a keyboard missing the letters "x", "s" and "1" for all of eternity. For those who don't know the `ed` editor, it is "the standard Unix editor": http://www.gnu.org/fun/jokes/ed.msg.html > Which is the "standard" way when dealing with objects? Throw > exceptions or always return an object, even if said object has an > error and may therefore not have data beyond an error code and > message? If I go the exception route, can I somehow put a message into > the exception, maybe adding it as an attribute of my custom exception > class? I assume so... > except e: > print e.message Most standard is to raise an exception. The syntax is: raise ValueError("any message you like") or use whatever error type suits your problem. You can even define your own exception types: class MyError(ValueError): pass Less common, but still reasonable, is to raise an error sentinel in place of the normal result. For example, re.match() and re.search() return None when there is nothing found, instead of a MatchObject. Another example, str.find() returns -1. The disadvantage of this is obvious: >>> string = "Nobody expects the Portuguese Inquisition!" >>> offset = string.find("Spanish") >>> print(string[offset:]) # expecting "Spanish Inquisition!" ! For special purposes, like mathematics, you can define error values that propagate through calculations. Python has half-hearted support for such "Not A Number" codes: >>> nan = float('nan') >>> nan + 1 # doesn't fail, but propagates nan >>> nan**2 nan >>> nan - 1000 nan as well as infinity. But you should consider this a very specialized solution (as well as a lot of work!!!). Another non-standard solution is to return a pair of values, a flag plus the value you actually want: flag, value = function(10000) if flag: do_something_with(value) else: process_error() > or something like that. I know I have research to do about the > specifics of all this, but before I go off and look it all up I am > wondering if it is the best way to go as far as standards and best > coding practices. This is still that api wrapper, so I am not the only > one who may end up using this file and I want to make it into > something that is useable and does what people expect. TIA. Then there is absolutely not even a shadow of a doubt: use exceptions. -- Steven From steve at pearwood.info Fri Feb 4 03:18:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Feb 2011 13:18:33 +1100 Subject: [Tutor] 'Installing' Python at runtime? (Civilization) In-Reply-To: References: Message-ID: <4D4B61F9.3000007@pearwood.info> Alan Gauld wrote: > > "C.Y. Ruhulessin" wrote > >> When I load up Civilization IV, a Firaxis game, the loading screen >> tells me >> "Loading Python". >> >> However, I can't seem to find out where it installs python > > It probably doesn't actually install Python it is simply loading > the interpreter into memory. That's what it says... it says "Loading Python", not installing it. It would include a version of Python when the game was installed, possibly embedded in the Civilization game itself. *Installing* Python each time you start the game would be silly. To find out where it is installed, use your operating system's Find Files utility to search for a file named "python". If you don't find it, that could mean they have renamed it something else, or it is embedded in the game where you can't get to it. > It probably uses Python as its macro language for configuration > or customisation. To execute those scripts it will need to load > a DLL containing the interpreter code. I don't know for sure > but I'd guess that's what it means. Many games use Python as a scripting language. (Lua is another popular choice.) The multiplayer game EVE maintains a special port of Python called "stackless". -- Steven From mehgcap at gmail.com Fri Feb 4 03:50:11 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 3 Feb 2011 21:50:11 -0500 Subject: [Tutor] best practice: throw exception or set a flag? In-Reply-To: <4D4B6068.8070606@pearwood.info> References: <4D4B6068.8070606@pearwood.info> Message-ID: Thanks to all for the answers. Sounds like exceptions are most definitely the way to go, and I will definitely put them in. In fact, this should make the wrapper a bit cleaner since I am not constantly checking for errors in variables and returning empty objects. Besides, I wouldn't want my soul stolen by angry programmers and doomed to working on Windows, let alone kernel debugging... :) Now, if it were Android, there might be something to the idea. On 2/3/11, Steven D'Aprano wrote: > Alex Hall wrote: >> Hi all, >> I am wondering what the best way to do the following would be: throw >> an exception, or always return an object but set an error flag if >> something goes wrong? > > Raise an exception. Error flags are an anti-pattern -- a software idiom > that you should not follow. > > The problem with flags is that callers will forget to check them, which > leads to problems being revealed far away from where the problem was > caused. That makes it *really* hard to debug. > > result = function(x) # fails and sets an error flag in result > do_something_else() > data = [1, 2, 'a', result, 'xyz'] # store > another_function(data) > # ... > # ... > # lots more code here > # ... > # ... > x = data[3] > do_something_with(x) > > which then blows up, because x is invalid but you haven't checked the > error flag. The problem actually was with the *original* x, all the way > back at the start, but that's been thrown away now, never to be seen > again, which makes it hard to debug why it failed. > > A million, billion, trillion times worse is if you have a single global > error flag! That's *disastrous*, because you MUST check the flag > *immediately*, otherwise it can be cleared. > > x = function(100000000) # fails > y = another_function(1000) > if global_error_flag: > # seems to be safe to use x > process(x) # but it isn't, and this blows up > > the problem being that another_function makes a second call to > function(), only this one succeeds and resets the global flag. If you do > this, the ghost of a thousand programmers will drag your spirit off to > the nether regions of Hell, where you will have to debug the Windows > kernel using only the `ed` editor on a keyboard missing the letters "x", > "s" and "1" for all of eternity. > > For those who don't know the `ed` editor, it is "the standard Unix editor": > > http://www.gnu.org/fun/jokes/ed.msg.html > > > >> Which is the "standard" way when dealing with objects? Throw >> exceptions or always return an object, even if said object has an >> error and may therefore not have data beyond an error code and >> message? If I go the exception route, can I somehow put a message into >> the exception, maybe adding it as an attribute of my custom exception >> class? I assume so... >> except e: >> print e.message > > Most standard is to raise an exception. The syntax is: > > raise ValueError("any message you like") > > or use whatever error type suits your problem. You can even define your > own exception types: > > class MyError(ValueError): > pass > > > Less common, but still reasonable, is to raise an error sentinel in > place of the normal result. For example, re.match() and re.search() > return None when there is nothing found, instead of a MatchObject. > Another example, str.find() returns -1. > > The disadvantage of this is obvious: > > >>> string = "Nobody expects the Portuguese Inquisition!" > >>> offset = string.find("Spanish") > >>> print(string[offset:]) # expecting "Spanish Inquisition!" > ! > > > For special purposes, like mathematics, you can define error values that > propagate through calculations. Python has half-hearted support for > such "Not A Number" codes: > > >>> nan = float('nan') > >>> nan + 1 # doesn't fail, but propagates > nan > >>> nan**2 > nan > >>> nan - 1000 > nan > > as well as infinity. But you should consider this a very specialized > solution (as well as a lot of work!!!). > > Another non-standard solution is to return a pair of values, a flag plus > the value you actually want: > > flag, value = function(10000) > if flag: > do_something_with(value) > else: > process_error() > > > >> or something like that. I know I have research to do about the >> specifics of all this, but before I go off and look it all up I am >> wondering if it is the best way to go as far as standards and best >> coding practices. This is still that api wrapper, so I am not the only >> one who may end up using this file and I want to make it into >> something that is useable and does what people expect. TIA. > > Then there is absolutely not even a shadow of a doubt: use exceptions. > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From japhy at pearachute.com Fri Feb 4 07:13:37 2011 From: japhy at pearachute.com (Japhy Bartlett) Date: Fri, 4 Feb 2011 01:13:37 -0500 Subject: [Tutor] 'Installing' Python at runtime? (Civilization) In-Reply-To: <4D4B61F9.3000007@pearwood.info> References: <4D4B61F9.3000007@pearwood.info> Message-ID: a common approach is to embed python in a compiled binary On Thu, Feb 3, 2011 at 9:18 PM, Steven D'Aprano wrote: > Alan Gauld wrote: >> >> "C.Y. Ruhulessin" wrote >> >>> When I load up Civilization IV, a Firaxis game, the loading screen tells >>> me >>> "Loading Python". >>> >>> However, I can't seem to find out where it installs python >> >> It probably doesn't actually install Python it is simply loading >> the interpreter into memory. > > That's what it says... it says "Loading Python", not installing it. It would > include a version of Python when the game was installed, possibly embedded > in the Civilization game itself. *Installing* Python each time you start the > game would be silly. > > To find out where it is installed, use your operating system's Find Files > utility to search for a file named "python". If you don't find it, that > could mean they have renamed it something else, or it is embedded in the > game where you can't get to it. > > >> It probably uses Python as its macro language for configuration >> or customisation. To execute those scripts it will need to load >> a DLL containing the interpreter code. I don't know for sure >> but I'd guess that's what it means. > > Many games use Python as a scripting language. (Lua is another popular > choice.) The multiplayer game EVE maintains a special port of Python called > "stackless". > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Feb 4 10:30:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Feb 2011 09:30:22 -0000 Subject: [Tutor] Ideas and good examples References: <4D4B5AE1.8040005@gmail.com> Message-ID: "David Goering" wrote > It says v3 is Under Construction, how long do you expect it to be > like this. The basic v3 tutor is all done except for the Case Study - which is currently about 75% complete. Its certainly usable. The Practical Python topics have not been started yet, but any v3 user who got that far should be able to adapt the v2 versions pretty easily, they are mostly about modules that haven't changed much. So apart from adding () to print and using input() instead of raw_input() they should be fine. In fact I'm thinking about putting a redirect link on those pages as a temporary measure... > Is it worth waiting or should I just go ahead with v2 ? v2 is still better supported than v3 on forums and in tutorials etc. And a few libraries have not been poprtted to v3 yet, but the number is reducing every week. My own view is that a beginner with no immediate specific project could probably start with v3. But if you are learning Python because you need it for a specific project then stick with v2 for now - its a lower risk option. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Feb 4 10:39:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 4 Feb 2011 09:39:39 -0000 Subject: [Tutor] best practice: throw exception or set a flag? References: Message-ID: "Alex Hall" wrote > I am wondering what the best way to do the following would be: throw > an exception, or always return an object but set an error flag if > something goes wrong? Here is an example: Throw an exception is the short general case answer... > class c: > def __init__(self): > self.error=False > def func(self, val): > if val!=10: self.error=True But note that neither of these methods returns "an object" - unless you count None as an object of course. > Which is the "standard" way when dealing with objects? Throw > exceptions or always return an object, even if said object has an > error and may therefore not have data beyond an error code and > message? I'm not sure what you have in mind here but remember that init() is an initialiser and not really a constructor so the object already exists when init() is called. init() does not return the object. And most methods do not return the object of which they are a part (in Python at least, in SmallTalk they do). But if you are using object in the general sense of a return value (since everything in Python is an object) then yes you should return an object and let the exception signal failure. > If I go the exception route, can I somehow put a message into > the exception, maybe adding it as an attribute of my custom > exception > class? Yes, or you can just pass a string to any exception when you raise it. Alan G. From __peter__ at web.de Fri Feb 4 11:15:12 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Feb 2011 11:15:12 +0100 Subject: [Tutor] RE module is working ? References: <4D49AEC3.7020900@free.fr> <4D4AF83A.9030706@free.fr> <4D4B38E7.1090100@free.fr> Message-ID: Karim wrote: > Recall: > > >>> re.subn(r'([^\\])?"', r'\1\\"', expression) > > Traceback (most recent call last): > File "", line 1, in > File "/home/karim/build/python/install/lib/python2.7/re.py", line > 162, in subn > return _compile(pattern, flags).subn(repl, string, count) > File "/home/karim/build/python/install/lib/python2.7/re.py", line > 278, in filter > return sre_parse.expand_template(template, match) > File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", > line 787, in expand_template > raise error, "unmatched group" > sre_constants.error: unmatched group > > > Found the solution: '?' needs to be inside parenthesis (saved pattern) > because outside we don't know if the saved match argument > will exist or not namely '\1'. > > >>> re.subn(r'([^\\]?)"', r'\1\\"', expression) > > (' \\"\\" ', 2) > > sed unix command is more permissive: sed 's/\([^\\]\)\?"/\1\\"/g' > because '?' can be outside parenthesis (saved pattern but escaped for > sed). \1 seems to not cause issue when matching is found. Perhaps it is > created only when match occurs. Thanks for reporting the explanation. From __peter__ at web.de Fri Feb 4 11:26:13 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Feb 2011 11:26:13 +0100 Subject: [Tutor] RE module is working ? References: <4D49AEC3.7020900@free.fr> <4D4AF83A.9030706@free.fr> Message-ID: Karim wrote: > That is not the thing I want. I want to escape any " which are not > already escaped. > The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have > made regex on unix since 15 years). Can the backslash be escaped, too? If so I don't think your regex does what you think it does. r'\\\"' # escaped \ followed by escaped " should not be altered, but: $ echo '\\\"' | sed 's/\([^\\]\)\?"/\1\\"/g' \\\\" # two escaped \ folloed by a " that is not escaped From mehgcap at gmail.com Fri Feb 4 14:03:28 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 4 Feb 2011 08:03:28 -0500 Subject: [Tutor] best practice: throw exception or set a flag? In-Reply-To: References: Message-ID: On 2/4/11, Alan Gauld wrote: > "Alex Hall" wrote > >> I am wondering what the best way to do the following would be: throw >> an exception, or always return an object but set an error flag if >> something goes wrong? Here is an example: > > Throw an exception is the short general case answer... > >> class c: >> def __init__(self): >> self.error=False >> def func(self, val): >> if val!=10: self.error=True > > But note that neither of these methods returns "an object" > - unless you count None as an object of course. There should have been a function below that which returned the object with or without the error attribute. > >> Which is the "standard" way when dealing with objects? Throw >> exceptions or always return an object, even if said object has an >> error and may therefore not have data beyond an error code and >> message? > > I'm not sure what you have in mind here but remember that > init() is an initialiser and not really a constructor so the object > already exists when init() is called. init() does not return the > object. Right, that second function should have done it, but I likely wrote it wrong (what I get for making up an example on the spot). > > And most methods do not return the object of which they > are a part (in Python at least, in SmallTalk they do). That seems like it would get rather confusing... > > But if you are using object in the general sense of a return > value (since everything in Python is an object) then yes > you should return an object and let the exception signal > failure. Will do, and I was talking about an object as in an instance of my class, not generally, though I do like Python's model of treating *everything* as an object. > > >> If I go the exception route, can I somehow put a message into >> the exception, maybe adding it as an attribute of my custom >> exception >> class? > > Yes, or you can just pass a string to any exception when you raise it. Good to know. For this, I wanted my own exception, so I made this: class ApiError(Exception): #for use with any bad requests from Bookshare's api def __init__(self, number, message): self.number=number self.message=message def __str__(self): return str(self.number)+": "+self.message > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From subscriptions at cagttraining.com Fri Feb 4 14:35:30 2011 From: subscriptions at cagttraining.com (Bill Felton) Date: Fri, 4 Feb 2011 08:35:30 -0500 Subject: [Tutor] best practice: throw exception or set a flag? In-Reply-To: References: Message-ID: <23F7CF1B-EE0E-448E-B405-681438075BF8@cagttraining.com> On Feb 4, 2011, at 8:03 AM, Alex Hall wrote: > On 2/4/11, Alan Gauld wrote: >> "Alex Hall" wrote >> >>> I am wondering what the best way to do the following would be: throw >>> an exception, or always return an object but set an error flag if >>> something goes wrong? Here is an example: >> >> Throw an exception is the short general case answer... >> >>> class c: >>> def __init__(self): >>> self.error=False >>> def func(self, val): >>> if val!=10: self.error=True >> >> But note that neither of these methods returns "an object" >> - unless you count None as an object of course. > There should have been a function below that which returned the object > with or without the error attribute. >> >>> Which is the "standard" way when dealing with objects? Throw >>> exceptions or always return an object, even if said object has an >>> error and may therefore not have data beyond an error code and >>> message? >> >> I'm not sure what you have in mind here but remember that >> init() is an initialiser and not really a constructor so the object >> already exists when init() is called. init() does not return the >> object. > Right, that second function should have done it, but I likely wrote it > wrong (what I get for making up an example on the spot). >> >> And most methods do not return the object of which they >> are a part (in Python at least, in SmallTalk they do). > That seems like it would get rather confusing... Um, not quite correct -- methods *without a specified return value* always return self, that is, the object which executed the method. This is useful, but is hardly the most common situation. It is used most often when a method modifies the receiver and the sender(s) is/are likely to be interested in the updated object itself rather than in one of the parameters to the method or some other object. However, it can be a source of error, as many methods which modify return self, but many common collection protocols return the argument rather than the modified collection. Just one of those things you need to learn, which all languages have ;-) cheers, Bill From alan.gauld at btinternet.com Fri Feb 4 14:48:36 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 4 Feb 2011 13:48:36 +0000 (GMT) Subject: [Tutor] best practice: throw exception or set a flag? In-Reply-To: References: Message-ID: <429194.85409.qm@web86702.mail.ird.yahoo.com> > > And most methods do not return the object of which they > > are a part (in Python at least, in SmallTalk they do). > That seems like it would get rather confusing... Actually, from an OOP point of view, its a very powerful default and I wish more Python methods did it. It allows you to chain operations together. Using Python notation: employee.updateName('fred).updateAddress(number=7).resetPassword() Using the Python idiom of not using a return value for updates you'd need to use 3 separate lines to do the updates... Of course 3 lines are easier to debug, but often chaining operations like this is useful. If the return value is not needed then you can just ignore it. But I often use 'return self' as a kind of default option in my own classes. Alan G. From emile at fenx.com Fri Feb 4 15:28:37 2011 From: emile at fenx.com (Emile van Sebille) Date: Fri, 04 Feb 2011 06:28:37 -0800 Subject: [Tutor] best practice: throw exception or set a flag? In-Reply-To: <23F7CF1B-EE0E-448E-B405-681438075BF8@cagttraining.com> References: <23F7CF1B-EE0E-448E-B405-681438075BF8@cagttraining.com> Message-ID: On 2/4/2011 5:35 AM Bill Felton said... > Um, not quite correct -- methods *without a specified return value* always return self, that is, the object which executed the method. Um, no. They return None. >>> class Test: ... def __init__(self):pass ... def test(self):pass ... >>> a=Test().test() >>> a >>> print a None >>> Emile From subscriptions at cagttraining.com Fri Feb 4 17:50:43 2011 From: subscriptions at cagttraining.com (Bill Felton) Date: Fri, 4 Feb 2011 11:50:43 -0500 Subject: [Tutor] best practice: throw exception or set a flag? In-Reply-To: References: <23F7CF1B-EE0E-448E-B405-681438075BF8@cagttraining.com> Message-ID: <2FE3F521-A221-4AA1-919E-77929A825C39@cagttraining.com> Um, yes, emphatically yes. You missed the context, which was Smalltalk, and it is terms of Smalltalk that my reply is couched. Yes, Python returns None. Smalltalk returns self by default. Given the dropped context, you are correct. Given the context meant, I am. regards, Bill On Feb 4, 2011, at 9:28 AM, Emile van Sebille wrote: > On 2/4/2011 5:35 AM Bill Felton said... > >> Um, not quite correct -- methods *without a specified return value* always return self, that is, the object which executed the method. > > Um, no. They return None. > > >>> class Test: > ... def __init__(self):pass > ... def test(self):pass > ... > >>> a=Test().test() > >>> a > >>> print a > None > >>> > > Emile > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From mehgcap at gmail.com Fri Feb 4 17:56:50 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 4 Feb 2011 11:56:50 -0500 Subject: [Tutor] best practice: throw exception or set a flag? In-Reply-To: <2FE3F521-A221-4AA1-919E-77929A825C39@cagttraining.com> References: <23F7CF1B-EE0E-448E-B405-681438075BF8@cagttraining.com> <2FE3F521-A221-4AA1-919E-77929A825C39@cagttraining.com> Message-ID: On 2/4/11, Bill Felton wrote: > Um, yes, emphatically yes. You missed the context, which was Smalltalk, and > it is terms of Smalltalk that my reply is couched. > Yes, Python returns None. > Smalltalk returns self by default. > Given the dropped context, you are correct. > Given the context meant, I am. I was following this until now... what is this smalltalk and drop? > > regards, > Bill > > On Feb 4, 2011, at 9:28 AM, Emile van Sebille wrote: > >> On 2/4/2011 5:35 AM Bill Felton said... >> >>> Um, not quite correct -- methods *without a specified return value* >>> always return self, that is, the object which executed the method. >> >> Um, no. They return None. >> >> >>> class Test: >> ... def __init__(self):pass >> ... def test(self):pass >> ... >> >>> a=Test().test() >> >>> a >> >>> print a >> None >> >>> >> >> Emile >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From subscriptions at cagttraining.com Fri Feb 4 18:02:59 2011 From: subscriptions at cagttraining.com (Bill Felton) Date: Fri, 4 Feb 2011 12:02:59 -0500 Subject: [Tutor] best practice: throw exception or set a flag? In-Reply-To: References: <23F7CF1B-EE0E-448E-B405-681438075BF8@cagttraining.com> <2FE3F521-A221-4AA1-919E-77929A825C39@cagttraining.com> Message-ID: <12C1B930-1005-45E1-9EFF-CFFA0906D42D@cagttraining.com> Smalltalk is an OO programming language that had some dominance in the late 80's through much of the 90s. It has proceeded to more or less commit suicide through a variety of mechanisms. By 'drop' I meant 'drop the context of the remarks', which in the original post was discussing Smalltalk's default method return. It isn't a major deal, overall, I think the most interesting remark has been Alan Gauld's musings immediately prior to Emile's to which I responded. Python defaults to None. Smalltalk defaults to self, which is always the object executing the code involved. Alan points out that this is extremely convenient and can reduce the code bulk involved when one wishes to string multiple operations together. It is stylistically possible in Python to set methods to return 'self' if/when that would be useful, but if it is not a language level feature, it becomes a convention that one can only rely on in ones own code. regards, Bill On Feb 4, 2011, at 11:56 AM, Alex Hall wrote: > On 2/4/11, Bill Felton wrote: >> Um, yes, emphatically yes. You missed the context, which was Smalltalk, and >> it is terms of Smalltalk that my reply is couched. >> Yes, Python returns None. >> Smalltalk returns self by default. >> Given the dropped context, you are correct. >> Given the context meant, I am. > I was following this until now... what is this smalltalk and drop? >> >> regards, >> Bill >> >> On Feb 4, 2011, at 9:28 AM, Emile van Sebille wrote: >> >>> On 2/4/2011 5:35 AM Bill Felton said... >>> >>>> Um, not quite correct -- methods *without a specified return value* >>>> always return self, that is, the object which executed the method. >>> >>> Um, no. They return None. >>> >>>>>> class Test: >>> ... def __init__(self):pass >>> ... def test(self):pass >>> ... >>>>>> a=Test().test() >>>>>> a >>>>>> print a >>> None >>>>>> >>> >>> Emile >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com; http://www.facebook.com/mehgcap From mehgcap at gmail.com Fri Feb 4 18:36:02 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 4 Feb 2011 12:36:02 -0500 Subject: [Tutor] best practice: throw exception or set a flag? In-Reply-To: <12C1B930-1005-45E1-9EFF-CFFA0906D42D@cagttraining.com> References: <23F7CF1B-EE0E-448E-B405-681438075BF8@cagttraining.com> <2FE3F521-A221-4AA1-919E-77929A825C39@cagttraining.com> <12C1B930-1005-45E1-9EFF-CFFA0906D42D@cagttraining.com> Message-ID: I see, thanks! On 2/4/11, Bill Felton wrote: > Smalltalk is an OO programming language that had some dominance in the late > 80's through much of the 90s. It has proceeded to more or less commit > suicide through a variety of mechanisms. > By 'drop' I meant 'drop the context of the remarks', which in the original > post was discussing Smalltalk's default method return. > It isn't a major deal, overall, I think the most interesting remark has been > Alan Gauld's musings immediately prior to Emile's to which I responded. > Python defaults to None. > Smalltalk defaults to self, which is always the object executing the code > involved. > Alan points out that this is extremely convenient and can reduce the code > bulk involved when one wishes to string multiple operations together. > It is stylistically possible in Python to set methods to return 'self' > if/when that would be useful, but if it is not a language level feature, it > becomes a convention that one can only rely on in ones own code. > > regards, > Bill > > On Feb 4, 2011, at 11:56 AM, Alex Hall wrote: > >> On 2/4/11, Bill Felton wrote: >>> Um, yes, emphatically yes. You missed the context, which was Smalltalk, >>> and >>> it is terms of Smalltalk that my reply is couched. >>> Yes, Python returns None. >>> Smalltalk returns self by default. >>> Given the dropped context, you are correct. >>> Given the context meant, I am. >> I was following this until now... what is this smalltalk and drop? >>> >>> regards, >>> Bill >>> >>> On Feb 4, 2011, at 9:28 AM, Emile van Sebille wrote: >>> >>>> On 2/4/2011 5:35 AM Bill Felton said... >>>> >>>>> Um, not quite correct -- methods *without a specified return value* >>>>> always return self, that is, the object which executed the method. >>>> >>>> Um, no. They return None. >>>> >>>>>>> class Test: >>>> ... def __init__(self):pass >>>> ... def test(self):pass >>>> ... >>>>>>> a=Test().test() >>>>>>> a >>>>>>> print a >>>> None >>>>>>> >>>> >>>> Emile >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehgcap at gmail.com; http://www.facebook.com/mehgcap > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From karim.liateni at free.fr Fri Feb 4 20:07:24 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 04 Feb 2011 20:07:24 +0100 Subject: [Tutor] RE module is working ? In-Reply-To: <4D4B5816.6050708@pearwood.info> References: <4D49AEC3.7020900@free.fr> <4D4AF83A.9030706@free.fr> <4D4B5816.6050708@pearwood.info> Message-ID: <4D4C4E6C.8010000@free.fr> On 02/04/2011 02:36 AM, Steven D'Aprano wrote: > Karim wrote: > >>>> *Indeed what's the matter with RE module!?* >>> You should really fix the problem with your email program first; >> Thunderbird issue with bold type (appears as stars) but I don't know >> how to fix it yet. > > A man when to a doctor and said, "Doctor, every time I do this, it > hurts. What should I do?" > > The doctor replied, "Then stop doing that!" > > :) Yes this these words made me laugh. I will keep it in my funny box. > > > Don't add bold or any other formatting to things which should be > program code. Even if it looks okay in *your* program, you don't know > how it will look in other people's programs. If you need to draw > attention to something in a line of code, add a comment, or talk about > it in the surrounding text. > > > [...] >> That is not the thing I want. I want to escape any " which are not >> already escaped. >> The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have >> made regex on unix since 15 years). Mainly sed, awk and perl sometimes grep and egrep. I know this is the jungle. > Which regex? Perl regexes? sed or awk regexes? Extended regexes? GNU > posix compliant regexes? grep or egrep regexes? They're all different. > > In any case, I am sorry, I don't think your regex does what you say. > When I try it, it doesn't work for me. > > [steve at sylar ~]$ echo 'Some \"text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g' > Some \\"text\" I give you my word on this. Exact output I redid it: #MY OS VERSION karim at Requiem4Dream:~$ uname -a Linux Requiem4Dream 2.6.32-28-generic #55-Ubuntu SMP Mon Jan 10 23:42:43 UTC 2011 x86_64 GNU/Linux #MY SED VERSION karim at Requiem4Dream:~$ sed --version GNU sed version 4.2.1 Copyright (C) 2009 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, to the extent permitted by law. GNU sed home page: . General help using GNU software: . E-mail bug reports to: . Be sure to include the word ``sed'' somewhere in the ``Subject:'' field. #MY SED OUTPUT COMMAND: karim at Requiem4Dream:~$ echo 'Some ""' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \"\" # THIS IS WHAT I WANT 2 CONSECUTIVES IF THE FIRST ONE IS ALREADY ESCAPED I DON'T WANT TO ESCAPED IT TWICE. karim at Requiem4Dream:~$ echo 'Some \""' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \"\" # BY THE WAY THIS ONE WORKS: karim at Requiem4Dream:~$ echo 'Some "text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \"text\" # BUT SURE NOT THIS ONE NOT COVERED BY MY REGEX (I KNOW IT AND WANT ORIGINALY TO COVER IT): karim at Requiem4Dream:~$ echo 'Some \"text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g' Some \\"text\" By the way in all sed version I work with the '?' (0 or one match) should be escaped that's the reason I have '\?' same thing with save '\(' and '\)' to store value. In perl, grep you don't need to escape. # SAMPLE FROM http://www.gnu.org/software/sed/manual/sed.html |\+| same As |*|, but matches one or more. It is a GNU extension. |\?| same As |*|, but only matches zero or one. It is a GNU extension > I wouldn't expect it to work. See below. > > By the way, you don't need to escape the brackets or the question mark: > > [steve at sylar ~]$ echo 'Some \"text"' | sed -re 's/([^\\])?"/\1\\"/g' > Some \\"text\" > > >> For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"' > > No it is not. > Yes I know, see my latest post in detail I already found the solution. I put it again the solution below: #Found the solution: '?' needs to be inside parenthesis (saved pattern) because outside we don't know if the saved match argument #will exist or not namely '\1'. >>> re.subn(r'([^\\]?)"', r'\1\\"', expression) (' \\"\\" ', 2) > The pattern you are matching does not do what you think it does. "Zero > or one of not-backslash, followed by a quote" will match a single > quote *regardless* of what is before it. This is true even in sed, as > you can see above, your sed regex matches both quotes. > > \" will match, because the regular expression will match zero > characters, followed by a quote. So the regex is correct. > > >>> match = r'[^\\]?"' # zero or one not-backslash followed by quote > >>> re.search(match, r'aaa\"aaa').group() > '"' > > Now watch what happens when you call re.sub: > > > >>> match = r'([^\\])?"' # group 1 equals a single non-backslash > >>> replace = r'\1\\"' # group 1 followed by \ followed by " > >>> re.sub(match, replace, 'aaaa') # no matches > 'aaaa' > >>> re.sub(match, replace, 'aa"aa') # one match > 'aa\\"aa' > >>> re.sub(match, replace, '"aaaa') # one match, but there's no group 1 > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.1/re.py", line 166, in sub > return _compile(pattern, flags).sub(repl, string, count) > File "/usr/local/lib/python3.1/re.py", line 303, in filter > return sre_parse.expand_template(template, match) > File "/usr/local/lib/python3.1/sre_parse.py", line 807, in > expand_template > raise error("unmatched group") > sre_constants.error: unmatched group > > Because group 1 was never matched, Python's re.sub raised an error. It > is not a very informative error, but it is valid behaviour. > > If I try the same thing in sed, I get something different: > > [steve at sylar ~]$ echo '"Some text' | sed -re 's/([^\\])?"/\1\\"/g' > \"Some text > > It looks like this version of sed defines backreferences on the > right-hand side to be the empty string, in the case that they don't > match at all. But this is not standard behaviour. The sed FAQs say > that this behaviour will depend on the version of sed you are using: > > "Seds differ in how they treat invalid backreferences where no > corresponding group occurs." > > http://sed.sourceforge.net/sedfaq3.html > > So you can't rely on this feature. If it works for you, great, but it > may not work for other people. > > > When you delete the ? from the Python regex, group 1 is always valid, > and you don't get an exception. Or if you ensure the input always > matches group 1, no exception: > > >>> match = r'([^\\])?"' > >>> replace = r'\1\\"' > >>> re.sub(match, replace, 'a"a"a"a') # group 1 always matches > 'a\\"a\\"a\\"a' > > (It still won't do what you want, but that's a *different* problem.) > > > > Jamie Zawinski wrote: > > Some people, when confronted with a problem, think "I know, > I'll use regular expressions." Now they have two problems. > > How many hours have you spent trying to solve this problem using > regexes? This is a *tiny* problem that requires an easy solution, not > wrestling with a programming language that looks like line-noise. > > This should do what you ask for: > > def escape(text): > """Escape any double-quote characters if and only if they > aren't already escaped.""" > output = [] > escaped = False > for c in text: > if c == '"' and not escaped: > output.append('\\') > elif c == '\\': > output.append('\\') > escaped = True > continue > output.append(c) > escaped = False > return ''.join(output) > Thank you for this one! This gives me some inspiration for other more complicated parsing. :-) > > Armed with this helper function, which took me two minutes to write, I > can do this: > > >>> text = 'Some text with backslash-quotes \\" and plain quotes " > together.' > >>> print escape(text) > Some text with backslash-quotes \" and plain quotes \" together. > > > Most problems that people turn to regexes are best solved without > regexes. Even Larry Wall, inventor of Perl, is dissatisfied with regex > culture and syntax: > > http://dev.perl.org/perl6/doc/design/apo/A05.html Ok but if I have to suppress all use of my one-liner sed regex most used utilities this is like refusing to use my car to go to work and make 20km by feet. For overuse I can understand that though I already did 30 lines of pure sed script using all it features which would have taken much more lines with awk or perl language. Anyway I am inclined to python now so if a re module exists with my small regex there is no big deal to become familiar with this module. Thanks for your efforts you've done. Regards Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Fri Feb 4 20:34:26 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 04 Feb 2011 20:34:26 +0100 Subject: [Tutor] RE module is working ? In-Reply-To: References: <4D49AEC3.7020900@free.fr> <4D4AF83A.9030706@free.fr> Message-ID: <4D4C54C2.9080903@free.fr> On 02/04/2011 11:26 AM, Peter Otten wrote: > Karim wrote: > >> That is not the thing I want. I want to escape any " which are not >> already escaped. >> The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have >> made regex on unix since 15 years). > Can the backslash be escaped, too? If so I don't think your regex does what > you think it does. > > r'\\\"' # escaped \ followed by escaped " > > should not be altered, but: > > $ echo '\\\"' | sed 's/\([^\\]\)\?"/\1\\"/g' > \\\\" # two escaped \ folloed by a " that is not escaped > > By the way you are right: I changed an I added sed command for the ' "" ': karim at Requiem4Dream:~$ echo 'prima " "' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \" \" karim at Requiem4Dream:~$ echo 'prima ""' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"\" karim at Requiem4Dream:~$ echo 'prima "Ich Karim"' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"Ich Karim\" karim at Requiem4Dream:~$ echo 'prima "Ich Karim"' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"Ich Karim\" Sorry, for the incomplete command. You pointed it out, many thanks Peter! Regards Karim > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From karim.liateni at free.fr Fri Feb 4 20:37:41 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 04 Feb 2011 20:37:41 +0100 Subject: [Tutor] RE module is working ? In-Reply-To: <4D4C4E6C.8010000@free.fr> References: <4D49AEC3.7020900@free.fr> <4D4AF83A.9030706@free.fr> <4D4B5816.6050708@pearwood.info> <4D4C4E6C.8010000@free.fr> Message-ID: <4D4C5585.8060200@free.fr> By the way with your helper function algorithm Steven and Peter comments you made me think of this change: karim at Requiem4Dream:~$ echo 'prima " "' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \" \" karim at Requiem4Dream:~$ echo 'prima ""' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"\" karim at Requiem4Dream:~$ echo 'prima "Ich Karim"' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"Ich Karim\" karim at Requiem4Dream:~$ echo 'prima "Ich Karim"' | sed -e 's/""/\\"\\"/g;s/\([^\]\)"/\1\\"/g' prima \"Ich Karim\" Regards Karim On 02/04/2011 08:07 PM, Karim wrote: > On 02/04/2011 02:36 AM, Steven D'Aprano wrote: >> Karim wrote: >> >>>>> *Indeed what's the matter with RE module!?* >>>> You should really fix the problem with your email program first; >>> Thunderbird issue with bold type (appears as stars) but I don't know >>> how to fix it yet. >> >> A man when to a doctor and said, "Doctor, every time I do this, it >> hurts. What should I do?" >> >> The doctor replied, "Then stop doing that!" >> >> :) > > Yes this these words made me laugh. I will keep it in my funny box. > >> >> >> Don't add bold or any other formatting to things which should be >> program code. Even if it looks okay in *your* program, you don't know >> how it will look in other people's programs. If you need to draw >> attention to something in a line of code, add a comment, or talk >> about it in the surrounding text. >> >> >> [...] >>> That is not the thing I want. I want to escape any " which are not >>> already escaped. >>> The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I >>> have made regex on unix since 15 years). > > Mainly sed, awk and perl sometimes grep and egrep. I know this is the > jungle. > >> Which regex? Perl regexes? sed or awk regexes? Extended regexes? GNU >> posix compliant regexes? grep or egrep regexes? They're all different. >> >> In any case, I am sorry, I don't think your regex does what you say. >> When I try it, it doesn't work for me. >> >> [steve at sylar ~]$ echo 'Some \"text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g' >> Some \\"text\" > > I give you my word on this. Exact output I redid it: > > #MY OS VERSION > karim at Requiem4Dream:~$ uname -a > Linux Requiem4Dream 2.6.32-28-generic #55-Ubuntu SMP Mon Jan 10 > 23:42:43 UTC 2011 x86_64 GNU/Linux > #MY SED VERSION > karim at Requiem4Dream:~$ sed --version > GNU sed version 4.2.1 > Copyright (C) 2009 Free Software Foundation, Inc. > This is free software; see the source for copying conditions. There is NO > warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR > PURPOSE, > to the extent permitted by law. > > GNU sed home page: . > General help using GNU software: . > E-mail bug reports to: . > Be sure to include the word ``sed'' somewhere in the ``Subject:'' field. > #MY SED OUTPUT COMMAND: > karim at Requiem4Dream:~$ echo 'Some ""' | sed -e 's/\([^\\]\)\?"/\1\\"/g' > Some \"\" > # THIS IS WHAT I WANT 2 CONSECUTIVES IF THE FIRST ONE IS ALREADY > ESCAPED I DON'T WANT TO ESCAPED IT TWICE. > karim at Requiem4Dream:~$ echo 'Some \""' | sed -e 's/\([^\\]\)\?"/\1\\"/g' > Some \"\" > # BY THE WAY THIS ONE WORKS: > karim at Requiem4Dream:~$ echo 'Some "text"' | sed -e > 's/\([^\\]\)\?"/\1\\"/g' > Some \"text\" > # BUT SURE NOT THIS ONE NOT COVERED BY MY REGEX (I KNOW IT AND WANT > ORIGINALY TO COVER IT): > karim at Requiem4Dream:~$ echo 'Some \"text"' | sed -e > 's/\([^\\]\)\?"/\1\\"/g' > Some \\"text\" > > By the way in all sed version I work with the '?' (0 or one match) > should be escaped that's the reason I have '\?' same thing with save > '\(' and '\)' to store value. In perl, grep you don't need to escape. > > # SAMPLE FROM http://www.gnu.org/software/sed/manual/sed.html > > |\+| > same As |*|, but matches one or more. It is a GNU extension. > |\?| > same As |*|, but only matches zero or one. It is a GNU extension > >> I wouldn't expect it to work. See below. >> >> By the way, you don't need to escape the brackets or the question mark: >> >> [steve at sylar ~]$ echo 'Some \"text"' | sed -re 's/([^\\])?"/\1\\"/g' >> Some \\"text\" >> >> >>> For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"' >> >> No it is not. >> > > Yes I know, see my latest post in detail I already found the solution. > I put it again the solution below: > > #Found the solution: '?' needs to be inside parenthesis (saved > pattern) because outside we don't know if the saved match argument > #will exist or not namely '\1'. > > >>> re.subn(r'([^\\]?)"', r'\1\\"', expression) > > (' \\"\\" ', 2) > > >> The pattern you are matching does not do what you think it does. >> "Zero or one of not-backslash, followed by a quote" will match a >> single quote *regardless* of what is before it. This is true even in >> sed, as you can see above, your sed regex matches both quotes. >> >> \" will match, because the regular expression will match zero >> characters, followed by a quote. So the regex is correct. >> >> >>> match = r'[^\\]?"' # zero or one not-backslash followed by quote >> >>> re.search(match, r'aaa\"aaa').group() >> '"' >> >> Now watch what happens when you call re.sub: >> >> >> >>> match = r'([^\\])?"' # group 1 equals a single non-backslash >> >>> replace = r'\1\\"' # group 1 followed by \ followed by " >> >>> re.sub(match, replace, 'aaaa') # no matches >> 'aaaa' >> >>> re.sub(match, replace, 'aa"aa') # one match >> 'aa\\"aa' >> >>> re.sub(match, replace, '"aaaa') # one match, but there's no group 1 >> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/local/lib/python3.1/re.py", line 166, in sub >> return _compile(pattern, flags).sub(repl, string, count) >> File "/usr/local/lib/python3.1/re.py", line 303, in filter >> return sre_parse.expand_template(template, match) >> File "/usr/local/lib/python3.1/sre_parse.py", line 807, in >> expand_template >> raise error("unmatched group") >> sre_constants.error: unmatched group >> >> Because group 1 was never matched, Python's re.sub raised an error. >> It is not a very informative error, but it is valid behaviour. >> >> If I try the same thing in sed, I get something different: >> >> [steve at sylar ~]$ echo '"Some text' | sed -re 's/([^\\])?"/\1\\"/g' >> \"Some text >> >> It looks like this version of sed defines backreferences on the >> right-hand side to be the empty string, in the case that they don't >> match at all. But this is not standard behaviour. The sed FAQs say >> that this behaviour will depend on the version of sed you are using: >> >> "Seds differ in how they treat invalid backreferences where no >> corresponding group occurs." >> >> http://sed.sourceforge.net/sedfaq3.html >> >> So you can't rely on this feature. If it works for you, great, but it >> may not work for other people. >> >> >> When you delete the ? from the Python regex, group 1 is always valid, >> and you don't get an exception. Or if you ensure the input always >> matches group 1, no exception: >> >> >>> match = r'([^\\])?"' >> >>> replace = r'\1\\"' >> >>> re.sub(match, replace, 'a"a"a"a') # group 1 always matches >> 'a\\"a\\"a\\"a' >> >> (It still won't do what you want, but that's a *different* problem.) >> >> >> >> Jamie Zawinski wrote: >> >> Some people, when confronted with a problem, think "I know, >> I'll use regular expressions." Now they have two problems. >> >> How many hours have you spent trying to solve this problem using >> regexes? This is a *tiny* problem that requires an easy solution, not >> wrestling with a programming language that looks like line-noise. >> >> This should do what you ask for: >> >> def escape(text): >> """Escape any double-quote characters if and only if they >> aren't already escaped.""" >> output = [] >> escaped = False >> for c in text: >> if c == '"' and not escaped: >> output.append('\\') >> elif c == '\\': >> output.append('\\') >> escaped = True >> continue >> output.append(c) >> escaped = False >> return ''.join(output) >> > > Thank you for this one! This gives me some inspiration for other more > complicated parsing. :-) > > >> >> Armed with this helper function, which took me two minutes to write, >> I can do this: >> >> >>> text = 'Some text with backslash-quotes \\" and plain quotes " >> together.' >> >>> print escape(text) >> Some text with backslash-quotes \" and plain quotes \" together. >> >> >> Most problems that people turn to regexes are best solved without >> regexes. Even Larry Wall, inventor of Perl, is dissatisfied with >> regex culture and syntax: >> >> http://dev.perl.org/perl6/doc/design/apo/A05.html > > Ok but if I have to suppress all use of my one-liner sed regex most > used utilities this is like refusing to use my car to go to work > and make 20km by feet. > For overuse I can understand that though I already did 30 lines of > pure sed script using all it features > which would have taken much more lines with awk or perl language. > > Anyway I am inclined to python now so if a re module exists with my > small regex there is no big deal to become familiar with this module. > > Thanks for your efforts you've done. > > Regards > Karim > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Sat Feb 5 20:46:09 2011 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 5 Feb 2011 14:46:09 -0500 Subject: [Tutor] making object iterable Message-ID: Hi all, I have a class which has a list as an attribute, meaning you must say something like: for result in obj.results: ... I want to make life a bit easier and let users just say: for result in obj: ... Here is what I have tried to make my class into an iterable one, yet I get an error saying that the class does not support indexing: def __iter__(self): #makes this class indexable instead of having to use its "results" list return self.iterate() def iterate(self): i=0 while i Message-ID: Alex Hall wrote: > Hi all, > I have a class which has a list as an attribute, meaning you must say > something like: > for result in obj.results: ... > I want to make life a bit easier and let users just say: > for result in obj: ... > Here is what I have tried to make my class into an iterable one, yet I > get an error saying that the class does not support indexing: Please remember to always cut-and-paste code and traceback. > def __iter__(self): > #makes this class indexable instead of having to use its "results" list > return self.iterate() > > def iterate(self): > i=0 > while i yield self.results[i] > i+=1 > > I am not sure why this does not work, unless I am misunderstanding > something about iterators and iterables? I thought an iterable, which > is what I am shooting for, was an iterator on steroids, allowing > indexing, multiple passes over the list, and all that. Do I want to > make this an iterator instead of an iterable? It *does* work: >>> class A(object): ... def __init__(self, results): ... self.results = results ... def __iter__(self): ... return self.iterate() ... def iterate(self): ... i = 0 ... while i < len(self.results): ... yield self.results[i] ... i += 1 ... >>> a = A("abc") >>> for item in a: ... print item ... a b c Perhaps self.results is not what you think it is. Check by adding the apprpriate print statement. By the way, there are simpler alternatives to delegate iteration to an attribute: >>> class B(object): ... def __init__(self, results): ... self.results = results ... def __iter__(self): ... return iter(self.results) ... >>> b = B("abc") >>> for item in b: ... print item ... a b c From eire1130 at gmail.com Sat Feb 5 21:13:20 2011 From: eire1130 at gmail.com (James Reynolds) Date: Sat, 5 Feb 2011 15:13:20 -0500 Subject: [Tutor] making object iterable In-Reply-To: References: Message-ID: You should probably read this section in the python tutorial: http://docs.python.org/tutorial/classes.html#iterators If you have any questions after that, I would suggest posting back here but that should cover it. On Sat, Feb 5, 2011 at 2:46 PM, Alex Hall wrote: > Hi all, > I have a class which has a list as an attribute, meaning you must say > something like: > for result in obj.results: ... > I want to make life a bit easier and let users just say: > for result in obj: ... > Here is what I have tried to make my class into an iterable one, yet I > get an error saying that the class does not support indexing: > > def __iter__(self): > #makes this class indexable instead of having to use its "results" list > return self.iterate() > > def iterate(self): > i=0 > while i yield self.results[i] > i+=1 > > I am not sure why this does not work, unless I am misunderstanding > something about iterators and iterables? I thought an iterable, which > is what I am shooting for, was an iterator on steroids, allowing > indexing, multiple passes over the list, and all that. Do I want to > make this an iterator instead of an iterable? > > > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com; http://www.facebook.com/mehgcap > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Sat Feb 5 21:50:22 2011 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 5 Feb 2011 15:50:22 -0500 Subject: [Tutor] making object iterable In-Reply-To: References: Message-ID: On 2/5/11, Peter Otten <__peter__ at web.de> wrote: > Alex Hall wrote: > >> Hi all, >> I have a class which has a list as an attribute, meaning you must say >> something like: >> for result in obj.results: ... >> I want to make life a bit easier and let users just say: >> for result in obj: ... >> Here is what I have tried to make my class into an iterable one, yet I >> get an error saying that the class does not support indexing: > > Please remember to always cut-and-paste code and traceback. > >> def __iter__(self): >> #makes this class indexable instead of having to use its "results" list >> return self.iterate() >> >> def iterate(self): >> i=0 >> while i> yield self.results[i] >> i+=1 >> >> I am not sure why this does not work, unless I am misunderstanding >> something about iterators and iterables? I thought an iterable, which >> is what I am shooting for, was an iterator on steroids, allowing >> indexing, multiple passes over the list, and all that. Do I want to >> make this an iterator instead of an iterable? > > It *does* work: > >>>> class A(object): > ... def __init__(self, results): > ... self.results = results > ... def __iter__(self): > ... return self.iterate() > ... def iterate(self): > ... i = 0 > ... while i < len(self.results): > ... yield self.results[i] > ... i += 1 > ... >>>> a = A("abc") >>>> for item in a: > ... print item > ... > a > b > c Yes, I get the same thing. However, when you try to index, as in a[0], you have problems. Here are two lines from my program: for i in res: print i This works as expected, printing every object in res.results, just as I wanted. for i in range(len(res)): print str(i+1)+": "+str(res[i]) This gives me an error, on this line, that "TypeError: 'SearchResults' object does not support indexing". So it seems that I can iterate over the list, but not get at a given element. What builtin method do I need to overload to do this? > > Perhaps self.results is not what you think it is. Check by adding the > apprpriate print statement. > > By the way, there are simpler alternatives to delegate iteration to an > attribute: > >>>> class B(object): > ... def __init__(self, results): > ... self.results = results > ... def __iter__(self): > ... return iter(self.results) > ... >>>> b = B("abc") >>>> for item in b: > ... print item > ... > a > b > c True, and I have made this change. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From foobar8 at gmail.com Sat Feb 5 22:39:37 2011 From: foobar8 at gmail.com (=?ISO-8859-1?Q?Siim_M=E4rtmaa?=) Date: Sat, 5 Feb 2011 23:39:37 +0200 Subject: [Tutor] making object iterable In-Reply-To: References: Message-ID: 2011/2/5 Alex Hall : > Yes, I get the same thing. However, when you try to index, as in a[0], > you have problems. Here are two lines from my program: > for i in res: print i > This works as expected, printing every object in res.results, just as I wanted. > > for i in range(len(res)): print str(i+1)+": "+str(res[i]) > This gives me an error, on this line, that "TypeError: 'SearchResults' > object does not support indexing". So it seems that I can iterate over > the list, but not get at a given element. What builtin method do I > need to overload to do this? It is the __getitem__ method Strange that when I ran code that I wrote to look like yours, I got a different error: AttributeError: itertest instance has no attribute '__getitem__' My code: #### class itertest(): testlist = [1,2,32,4,5,6,7,8] def __iter__(self): return iter(self.testlist) def __len__(self): return len(self.testlist) def __getitem__(self, i): return self.testlist[i] tester = itertest() for i in range(len(tester)): print str(i+1)+": "+str(tester[i]) #### I think in this case it would be more readable to use enumerate instead of range(len(sequence)) for index, item in enumerate(tester): print str(index+1)+": "+str(item) or in some cases string substitution for index, item in enumerate(tester): print "%d: %s"%(index+1,item) From mehgcap at gmail.com Sat Feb 5 23:08:54 2011 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 5 Feb 2011 17:08:54 -0500 Subject: [Tutor] making object iterable In-Reply-To: References: Message-ID: On 2/5/11, Siim M?rtmaa wrote: > 2011/2/5 Alex Hall : >> Yes, I get the same thing. However, when you try to index, as in a[0], >> you have problems. Here are two lines from my program: >> for i in res: print i >> This works as expected, printing every object in res.results, just as I >> wanted. >> >> for i in range(len(res)): print str(i+1)+": "+str(res[i]) >> This gives me an error, on this line, that "TypeError: 'SearchResults' >> object does not support indexing". So it seems that I can iterate over >> the list, but not get at a given element. What builtin method do I >> need to overload to do this? > > It is the __getitem__ method Thanks, that did it. > > Strange that when I ran code that I wrote to look like yours, I got a > different error: > > AttributeError: itertest instance has no attribute '__getitem__' > > My code: > #### > class itertest(): > > testlist = [1,2,32,4,5,6,7,8] > > def __iter__(self): > return iter(self.testlist) > > def __len__(self): > return len(self.testlist) > > def __getitem__(self, i): > return self.testlist[i] > > > tester = itertest() > > for i in range(len(tester)): print str(i+1)+": "+str(tester[i]) > > #### Not sure. Is it because you did not declare it as an object class: class myClass(object): ... > > I think in this case it would be more readable to use enumerate > instead of range(len(sequence)) > > for index, item in enumerate(tester): print str(index+1)+": "+str(item) Very true, I always forget about that handy function. > > or in some cases string substitution > > for index, item in enumerate(tester): print "%d: %s"%(index+1,item) Also true, and something I really should do more. I have heard it is faster than concatenating anyway. > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From ben.ganzfried at gmail.com Sat Feb 5 22:13:09 2011 From: ben.ganzfried at gmail.com (Ben Ganzfried) Date: Sat, 5 Feb 2011 16:13:09 -0500 Subject: [Tutor] Roulette Unit Test Questions Message-ID: Hey, I'm having a lot of confusion getting the unit test working for one of my classes for the Roulette bot I'm working on and would greatly appreciate any advice or help. Here is the description of what I am trying to do: http://homepage.mac.com/s_lott/books/oodesign/build-python/html/roulette/bin.html . Basically, I have my Bin class working and I am trying to get my BinTest class to do the following: Perform a unit test of the Binclass. The unit test should create several instances of Outcome, two instances of Binand establish that Bins can be constructed from the Outcome s. While I would greatly appreciate any pointers in fixing my mistakes, I would also greatly appreciate any pointers telling me what exactly it is that I do not yet understand. Thanks a bunch, my code is below. Here is my Bin class: from Outcome import * class Bin: def __init__(self, *outcomes): self.outcomes = outcomes def add(self, outcome): self.outcomes += outcome return self.outcomes def __str__(self): return (', '.join( map(str,self.outcomes))) Here is the code for my BinTest class: import Outcome import Bin class BinTest: def __init__(self): pass def create_Outcome(outcome): o1 = Outcome(outcome) #creates two instances of Bin def create_Bin(): b1 = Bin(("Red", 5), ("Black", 17),("Red", 5)) b2 = Bin(("00-0-1-2-3"), ("00")) #establishes that Bin can be constructed from Outcome def construct_Bin_from_Outcome(): b3 = Bin(o2) b4 = Bin(o4) b5 = Bin(o1) def main(): bin_test1 = BinTest() bin_test1.create_Outcome() #create_Outcome("Red", 5) #create_Outcome("Black", 17) #create_Outcome("Red", 5) #create_Outcome("00-0-1-2-3") #create_Outcome("00") print("o2 is ", o2) print("o3 is ", o3) print("o4 is ", o4) print("o5 is ", o5) print("b1 is ", b1) print("b2 is ", b2) print("b3 is ", b3) print("b4 is ", b4) print("b5 is ", b5) if __name__ == "__main__": main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Feb 6 02:06:31 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 06 Feb 2011 12:06:31 +1100 Subject: [Tutor] Roulette Unit Test Questions In-Reply-To: References: Message-ID: <4D4DF417.4040500@pearwood.info> Ben Ganzfried wrote: > Hey, > > I'm having a lot of confusion getting the unit test working for one of my > classes for the Roulette bot I'm working on and would greatly appreciate any > advice or help. [...] > Here is my Bin class: > > from Outcome import * > class Bin: > def __init__(self, *outcomes): > self.outcomes = outcomes > def add(self, outcome): > self.outcomes += outcome > return self.outcomes > def __str__(self): > return (', '.join( map(str,self.outcomes))) > > > > Here is the code for my BinTest class: > > import Outcome > import Bin > > class BinTest: > def __init__(self): > pass The __init__ method does nothing. That makes it pointless and a waste of time. Either get rid of it, or make it do something useful. > def create_Outcome(outcome): > o1 = Outcome(outcome) Three problems with this... firstly, if this is a method, you don't seem to have declared a `self` parameter. Secondly, this method creates an Outcome, stores it in a local variable, and then immediately throws it away when the method returns. To be useful, you need to either *return* the Outcome, or *save* it for later use: # Pick one. self.ol = Outcome(outcome) return Outcome(outcome) But the second problem is more fundamental. This method seems pretty pointless to me. Why have a method that just calls a single function and does nothing else? You wouldn't do this, would you? def create_int(x): return int(x) value = create_int("42") It is simpler, faster and more efficient to just call int("42") directly instead of adding an extra layer of indirection. Why add that extra layer in your class? If you have a good reason, that's fine, but what is that reason? > #creates two instances of Bin > def create_Bin(): Misleading name. You call it "create_Bin" but it creates Bins plural. Missing `self` parameter. > b1 = Bin(("Red", 5), ("Black", 17),("Red", 5)) > b2 = Bin(("00-0-1-2-3"), ("00")) Again, the fundamental problem here is that you create the two bins, store them in local variables, and then return from the method, which immediately deletes them. Is this supposed to be a test, or a helper function for a test? > #establishes that Bin can be constructed from Outcome > def construct_Bin_from_Outcome(): > b3 = Bin(o2) > b4 = Bin(o4) > b5 = Bin(o1) With the comment "establishes that..." it seems to me that this is an actual test. I presume that the previous methods were helpers, but they don't seem to be used anywhere. Missing `self` parameter again. Where do o2, o4 and o1 come from? What are they? How do they differ? Why is o3 missing? Why does o2 give you b3, but o4 gives you b4? Is there some pattern or meaning to the mysterious jumping numbers? o1 -> b5 o2 -> b3 o3 -> ?? o4 -> b4 o5 doesn't seem to exist? The point of unit tests is that *they*, not you, should test the result. If your unit tests are printing results, as your support code here does: > def main(): > bin_test1 = BinTest() > bin_test1.create_Outcome() [...] > print("o2 is ", o2) > print("o3 is ", o3) [...] forcing *you* to read the results looking for errors, then your tests are too hard to use and you won't use them. Here is how I would write the unit tests: * Start with a naming convention for tests. A good convention is to call test methods "testSpam", with "Spam" replaced with some useful and descriptive name. * Each test should test *one* thing. * Although since "thing" can be arbitrarily simple, or complex, that gives you a lot of flexibility. * Each test should be clear about what it is testing. Ideally, a stranger should be able to guess what the test does just from the name and at most a single short comment. * Each test should either *pass* or *fail*. You shouldn't have to inspect the results to decide which it is -- the test should decide. * Because tests are code, they can be buggy too. Keep your tests as simple as possible. * Tests can also suffer *errors*, i.e. they raise an exception. That indicates a buggy test. Full-powered test frameworks like docttest and unittest have ways to keep going when a test crashes, but for this simple version, if a test crashes, the whole thing will stop. With those principles in mind, here is what I have: class BinTest: # Unit tests for the Bin class. def test_BinCreation(self): # Test that Bins can be created without failing. We don't # check that they are valid, only that they can be created. # # Test creation from multiple tuples. Bin(("Red", 5), ("Black", 17),("Red", 5)) # Test creation from multiple strings. Bin("00-0-1-2-3", "00") # Test creation from an Outcome. Bin(Outcome("something goes here, I don't know what")) # If we get here, we have passed all the tests. return True def test_BinValidity(self): # Test that Bins aren't just created, but are correct. b = Bin("00") # whatever... if b.something != "something": # Test has failed. return False if b.something_else != "something else": return False return True def test_BinString(self): # Test that Bins can be converted to strings correctly. b = Bin("00") # whatever... s = str(b) return s == "Bin('00')" # Now run the tests. test = BinTest() if test.test_BinCreate(): print "Bin creation passed." else: print "Bin creation failed." if test.test_BinValidity(): print "Created Bins are valid -- pass." else: print "Created Bins are invalid -- fail." if test.test_BinString(): print "String conversion -- pass." else: print "String conversion -- fail." You can see one disadvantage of this roll-your-own unit test suite... you have to remember to return True or False, otherwise the tests won't operate properly. This is why people have built automated test frameworks like unittest, which is moderately complex to learn, but handles 98% of the boring boilerplate for you. An even bigger disadvantage is that *using* the tests is a PITA -- there's nearly as much code needed to run them as there is in the tests themselves. I would call this a fatal flaw for this roll-your-own unit test system (but for something I knocked up in ten minutes, it's not bad). Again, frameworks like unittest have "test discovery", that is, you write the tests, and the framework can automatically discover them and run them. -- Steven From bgailer at gmail.com Sun Feb 6 02:12:14 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 05 Feb 2011 20:12:14 -0500 Subject: [Tutor] making object iterable In-Reply-To: References: Message-ID: <4D4DF56E.6010509@gmail.com> On 2/5/2011 2:46 PM, Alex Hall wrote: > Hi all, > I have a class which has a list as an attribute, meaning you must say > something like: > for result in obj.results: ... > I want to make life a bit easier and let users just say: > for result in obj: ... > Here is what I have tried to make my class into an iterable one, yet I > get an error saying that the class does not support indexing: > > def __iter__(self): > #makes this class indexable instead of having to use its "results" list > return self.iterate() > > def iterate(self): > i=0 > while i yield self.results[i] > i+=1 > Have you considered subclassing list? That would solve many problems. -- Bob Gailer 919-636-4239 Chapel Hill NC From mehgcap at gmail.com Sun Feb 6 02:59:32 2011 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 5 Feb 2011 20:59:32 -0500 Subject: [Tutor] making object iterable In-Reply-To: <4D4DF56E.6010509@gmail.com> References: <4D4DF56E.6010509@gmail.com> Message-ID: On 2/5/11, bob gailer wrote: > On 2/5/2011 2:46 PM, Alex Hall wrote: >> Hi all, >> I have a class which has a list as an attribute, meaning you must say >> something like: >> for result in obj.results: ... >> I want to make life a bit easier and let users just say: >> for result in obj: ... >> Here is what I have tried to make my class into an iterable one, yet I >> get an error saying that the class does not support indexing: >> >> def __iter__(self): >> #makes this class indexable instead of having to use its "results" list >> return self.iterate() >> >> def iterate(self): >> i=0 >> while i> yield self.results[i] >> i+=1 >> > Have you considered subclassing list? That would solve many problems. Well, it seems to be working now. Subclassing list would have probably worked, and I never thought of that. I have other attributes as well, though, not just the list of results. For example, there is a "url" string, a "pages" int, andso on. I am not sure if I could have mixed a list subclass with these other attributes... > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From kb1pkl at aim.com Sun Feb 6 05:14:38 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 05 Feb 2011 23:14:38 -0500 Subject: [Tutor] P2PU Python Challenges Message-ID: <4D4E202E.3000902@aim.com> In my journeys across the face of the Internet, I found this: http://p2pu.org/general/python-challenges Not sure what it's really going to be, but any new programmers/people looking for something to do might be interested. I'm not quite sure how a class can be organised around a web riddle, but it's there so someone must have figured it out. Just thought I'd share. From shrvtsnvs at gmail.com Sun Feb 6 09:58:54 2011 From: shrvtsnvs at gmail.com (Shrivats) Date: Sun, 6 Feb 2011 14:28:54 +0530 Subject: [Tutor] P2PU Python Challenges In-Reply-To: <4D4E202E.3000902@aim.com> References: <4D4E202E.3000902@aim.com> Message-ID: <20110206085854.GA2997@zorander> On Sat, Feb 05, 2011 at 11:14:38PM -0500, Corey Richardson wrote: > In my journeys across the face of the Internet, I found this: > http://p2pu.org/general/python-challenges > Browsing that site a little more, I also saw this - "Learn Python the hard way". I'm not sure how useful that would be, most of the exercises are geared towards fixing bugs as they come up. Maybe some newbie might find it useful to see how to go about fixing bugs. :) Regards, Shrivats From rdmoores at gmail.com Sun Feb 6 11:07:10 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 6 Feb 2011 02:07:10 -0800 Subject: [Tutor] mpmath now supports Python 3! Message-ID: Dick Moores From ramjaju.mail at gmail.com Mon Feb 7 08:43:16 2011 From: ramjaju.mail at gmail.com (Sriram Jaju) Date: Mon, 7 Feb 2011 13:13:16 +0530 Subject: [Tutor] Help with OCR Message-ID: Hi all, I'm new to python. I'm doing a project on OCR (Optical Character Recognition), I've heard a lot about Python so i want to know whether i can use python for OCR. If yes what are the tool require for that?. My another doubt is that, can i use python for programming microcontrollers ?. -- Xcited 2 be Alive....Sriram -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramjaju.mail at gmail.com Mon Feb 7 08:47:49 2011 From: ramjaju.mail at gmail.com (Sriram Jaju) Date: Mon, 7 Feb 2011 13:17:49 +0530 Subject: [Tutor] Need help on OCR. Message-ID: Hi all, I'm new to python. I'm doing a project on OCR (Optical Character Recognition), I've heard a lot about Python so i want to know whether i can use python for OCR. If yes what are the tool require for that?. My another doubt is that, can i use python for programming microcontrollers ? -- Xcited 2 be Alive....Sriram -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Mon Feb 7 08:51:57 2011 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Mon, 7 Feb 2011 13:21:57 +0530 Subject: [Tutor] Help with OCR In-Reply-To: References: Message-ID: On Mon, Feb 7, 2011 at 1:13 PM, Sriram Jaju wrote: > Hi all, > I'm new to python. I'm doing a project on OCR (Optical Character > Recognition), I've heard a lot about Python so i want to know whether i can > use python for OCR. > If yes what are the tool require for that?. > pytesseract. Needs some training though, based upon tesseract engine. > My another doubt is that, can i use python for programming microcontrollers > ?. > You bet. > > > -- > Xcited 2 be Alive....Sriram > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 7 09:55:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Feb 2011 08:55:18 -0000 Subject: [Tutor] Help with OCR References: Message-ID: "Sriram Jaju" wrote > I'm new to python. I'm doing a project on OCR (Optical Character > Recognition), I've heard a lot about Python so i want to know > whether i can > use python for OCR. That depends a lot on the environment. What OS will you be using? What are you doing exactly? Are you actually reading the characters optically or are you taking a feed from an OCR device? Are you processing a scanned image? > If yes what are the tool require for that?. It depends on the above indformation. > My another doubt is that, can i use python for programming > microcontrollers Not normally, but if you can find a program that can program the microcontroller you might be able to drive it from Python. Or if the micro has an interface that can be driven from, for example, a serial port you may be able to do something. We can't give specific answers without a lot more specific information. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Feb 7 09:56:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Feb 2011 08:56:40 -0000 Subject: [Tutor] Help with OCR References: Message-ID: "Shashwat Anand" wrote >> My another doubt is that, can i use python for programming >> microcontrollers > > You bet. Really? How would he go about that? I've not seen (or even heard of) Python used in that role before. Alan G From ramjaju.mail at gmail.com Mon Feb 7 10:58:49 2011 From: ramjaju.mail at gmail.com (Sriram Jaju) Date: Mon, 7 Feb 2011 15:28:49 +0530 Subject: [Tutor] Help with OCR In-Reply-To: References: Message-ID: I'm using windows7. I'm doing a robotic project in which a robot has to take instruction from images which are taken by camera. image consists of characters like 'START', 'STOP' etc. On Mon, Feb 7, 2011 at 2:25 PM, Alan Gauld wrote: > "Sriram Jaju" wrote > > I'm new to python. I'm doing a project on OCR (Optical Character >> Recognition), I've heard a lot about Python so i want to know whether i >> can >> use python for OCR. >> > > That depends a lot on the environment. What OS will you be using? > What are you doing exactly? Are you actually reading the characters > optically or are you taking a feed from an OCR device? Are you > processing a scanned image? > > > If yes what are the tool require for that?. >> > > It depends on the above indformation. > > > My another doubt is that, can i use python for programming >> microcontrollers >> > > Not normally, but if you can find a program that can program > the microcontroller you might be able to drive it from Python. > Or if the micro has an interface that can be driven from, for example, > a serial port you may be able to do something. > > We can't give specific answers without a lot more specific information. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Xcited 2 be Alive....Sriram -------------- next part -------------- An HTML attachment was scrubbed... URL: From aflint310 at yahoo.com Mon Feb 7 16:33:22 2011 From: aflint310 at yahoo.com (Ashley F) Date: Mon, 7 Feb 2011 07:33:22 -0800 (PST) Subject: [Tutor] nested loops Message-ID: <973783.90807.qm@web161215.mail.bf1.yahoo.com> I am trying to write a function...(it's kind of like a long way to do BLAST but only comparing 2 sequences) ? I have 3 loops nested...Within those loops, I obtain a "best fit score" so to speak. ? I can get the program to run...but the loops run all the way to the end.? I can't figure out how to print the best score found...and the alignment that went with it. (therefore, my results will only be correct if my last alignment is the highest scoring one--which it usually isn't) ? To try to clear this up... The part of my pseudocode that I'm having trouble putting into actual code in python is: "if that alignment has the best score seen so far ???? save the score and that alignment" -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Feb 7 16:55:18 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 7 Feb 2011 09:55:18 -0600 (CST) Subject: [Tutor] nested loops In-Reply-To: <973783.90807.qm@web161215.mail.bf1.yahoo.com> References: <973783.90807.qm@web161215.mail.bf1.yahoo.com> Message-ID: On Mon, 7 Feb 2011, Ashley F wrote: > ? > To try to clear this up... > The part of my pseudocode that I'm having trouble putting into actual code in python is: > "if that alignment has the best score seen so far > ???? save the score and that alignment" Tip: It's helpful to send code, like perhaps the triple loop, that illustrates your problem. highscore = 0 alignment = somealignment for x in something: for y in somethingelse: for z in evenmoresomething: if x+y+z > highscore: highscore = x+y+z alignment = newalignment Is that something to the effect of what you're looking for? HTH, Wayne From bermanrl at cfl.rr.com Mon Feb 7 16:55:33 2011 From: bermanrl at cfl.rr.com (Robert Berman) Date: Mon, 07 Feb 2011 10:55:33 -0500 Subject: [Tutor] nested loops In-Reply-To: <973783.90807.qm@web161215.mail.bf1.yahoo.com> References: <973783.90807.qm@web161215.mail.bf1.yahoo.com> Message-ID: <4D5015F5.6050309@cfl.rr.com> On 02/07/2011 10:33 AM, Ashley F wrote: > I am trying to write a function...(it's kind of like a long way to do > BLAST but only comparing 2 sequences) > I have 3 loops nested...Within those loops, I obtain a "best fit > score" so to speak. > I can get the program to run...but the loops run all the way to the > end. I can't figure out how to print the best score found...and the > alignment that went with it. (therefore, my results will only be > correct if my last alignment is the highest scoring one--which it > usually isn't) > To try to clear this up... > The part of my pseudocode that I'm having trouble putting into actual > code in python is: > "if that alignment has the best score seen so far > save the score and that alignment" > > It would be much easier for people to help you if you would include the actual code you have written. We have no way to tell you are running to the end or not; we certainly have nothing showing 'a best fit' algorithm. If we can see the actual code we can at least show you where you might want to look for current and/or potential problems. Also, what OS are you using? What version of Python are you using? Robert Berman -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 7 17:40:51 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 7 Feb 2011 16:40:51 -0000 Subject: [Tutor] nested loops References: <973783.90807.qm@web161215.mail.bf1.yahoo.com> Message-ID: "Wayne Werner" wrote You probably want to add a sentinel to break out of the outer loops too: found = False > highscore = 0 > alignment = somealignment > for x in something and not found: > for y in somethingelse and not found: > for z in evenmoresomething: > if x+y+z > highscore: > highscore = x+y+z > alignment = newalignment found = True break HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From aflint310 at yahoo.com Mon Feb 7 17:45:46 2011 From: aflint310 at yahoo.com (Ashley F) Date: Mon, 7 Feb 2011 08:45:46 -0800 (PST) Subject: [Tutor] function help Message-ID: <21116.46156.qm@web161201.mail.bf1.yahoo.com> ok...here's the function I've written so far. ? def padWithGaps(seq): ??? for letter in seq: ?????? letter="-" ?????? line=len(seq) ?????? dashline=line*letter ??? return dashline ? def replace(someString,position,letter): ??? first=someString[0:position] ??? second=letter ??? third=someString[position+1:len(someString)] ??? newString=first+second+third ??? return newString ? ##findScore("MPFVS","MS-V-") would return a score of 2 def findScore(first,second): ??? count=0 ??? for position in range(0,len(first)): ???????? if first[position]==second[position]: ???????????? count=count+1 ???????????? position=position+1 ??? return count ? #shorter is a 3 amino acid sequence ##longer is any length sequence greater than 3 ###i=first amino acid; j=second amino acid; k=third amino acid def findAlignment(shorter,longer): ???? for i in range(0,len(longer)-2): ???????? for j in range(1,len(longer)-1): ????????????? for k in range(2,len(longer)): ???????????????????dashline=padWithGaps(longer) ?????????????????? nextLine=replace(dashline,i,shorter[0]) ?????????????????? nextNext=replace(nextLine,j,shorter[1]) ?????????????????? alignment=replace(nextNext,k,shorter[2]) ?????????????????? score=findScore(longer,alignment) ?????????? ####don't know what to do here ??????print longer ??????print alignment ??????print "Score = " + str(score) ? I don't know what to do at the end of my loop but what I'm trying to do in pseudocode is: ?"if that alignment has the best score seen so far ????????? save the score and the alignment print the best score and the best alignment" -------------- next part -------------- An HTML attachment was scrubbed... URL: From Michael at shamirlens.co.uk Mon Feb 7 17:49:59 2011 From: Michael at shamirlens.co.uk (Michael M Mason) Date: Mon, 7 Feb 2011 16:49:59 +0000 Subject: [Tutor] nested loops In-Reply-To: References: <973783.90807.qm@web161215.mail.bf1.yahoo.com> Message-ID: <5378B081D0A21C45A6135E92E182BD7F0A9677EC@Mail1-Shamir.shamir.org.il> Alan Gauld wrote:- > "Wayne Werner" wrote > found = False > > highscore = 0 > > alignment = somealignment > > for x in something and not found: > > for y in somethingelse and not found: > > for z in evenmoresomething: > > if x+y+z > highscore: > > highscore = x+y+z > > alignment = newalignment > found = True > break > > HTH, That's going to exit first time through, isn't it? -- Michael This mail was sent via Mail-SeCure System. ************************************************************************************ This footnote confirms that this email message has been scanned by PineApp Mail-SeCure for the presence of malicious code, vandals & computer viruses. ************************************************************************************ From delegbede at dudupay.com Mon Feb 7 19:22:27 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Mon, 7 Feb 2011 19:22:27 +0100 Subject: [Tutor] PyS60 request Message-ID: Hello Everybody, I am working on a little project centered on PyS60, developing applications for symbian phones. Before I start asking questions pertaining to that, I would like to first clarify if it is appropriate to post such questions here. If it is a yes, then, my subsequent mails would be conveying my questions and if it is a no, kindly accept my unreserved apologies. There are no intentions to abuse the principles of this group. Thanks. -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Mon Feb 7 20:00:26 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 7 Feb 2011 14:00:26 -0500 Subject: [Tutor] function help In-Reply-To: <21116.46156.qm@web161201.mail.bf1.yahoo.com> References: <21116.46156.qm@web161201.mail.bf1.yahoo.com> Message-ID: I'm not sure of the answer to your question, because i'm not sure I understand it. Perhaps you could rephrase it? But, there is some other stuff I noticed though: def padWithGaps(seq): for letter in seq: letter="-" line=len(seq) dashline=line*letter return dashline This function is fairly inefficient. Let's say you pass the function a sequence three items long something like a_list = ['a','b','c']. Your telling Python to create a dashed line three dashes long three separate times. So, you do it for the 'a' part of the sequence, the 'b' and the 'c'. You can condense this to something like: def padWithGaps(seq): lent = len(seq) return lent*'-' And you really don't need to have a separate function for that, as you can just do it on the fly Another thing, whenever your taking a slice of a list and the first argument is 0, you can just omit that. For example, from my list a_list example above a_list[0:2] is equivalent to a_list[:2] As for the rest of them, what you could do is pass each function data that you would expect to be passed under normal operation (assuming this is possible of course) and instead of using return use print instead and see if the results are what you expect. What I mean is, let's say I pass the results from the padWithGaps (the results of which I call dashline to be consistent) to the next function: def replace(someString,position,letter): first=someString[0:position] second=letter third=someString[position+1:len(someString)] newString=first+second+third return newString So, I can do something like z = replace(dashline,0,'a') and then print z. What the results should be is "a--". def findScore(first,second): count=0 for position in range(0,len(first)): if first[position]==second[position]: count=count+1 position=position+1 return count With this function here, there is a few things you can do to optimize and clean up clutter as well. I only point this out because it pays huge dividends in the long run (or it has for me at least). The first thing though is that you don't need to have the line position=position+1. Python will go to the next item in the list "position" whether you tell it to or not. So below is the same thing but without the position +=1 line: def findScore(first,second): count=0 for position in range(0,len(first)): if first[position]==second[position]: count=count+1 return count The other thing I would suggest is to use enumerate. Enumerate is your friend. And the last thing I would suggest is whenever you want to do something like a = a+1, you can just do a +=1. > def findScore2(first,second): count=0 for i, position in enumerate(first): if position==second[i]: count+=1 return count enumerate returns both the next item in the list and the position of that item in the list (in this case, I called that variable i). So you will find that if you run findScore2 you will have the same results as findScore. Or at least you should ;) On Mon, Feb 7, 2011 at 11:45 AM, Ashley F wrote: > ok...here's the function I've written so far. > > def padWithGaps(seq): > for letter in seq: > letter="-" > line=len(seq) > dashline=line*letter > return dashline > > def replace(someString,position,letter): > first=someString[0:position] > second=letter > third=someString[position+1:len(someString)] > newString=first+second+third > return newString > > ##findScore("MPFVS","MS-V-") would return a score of 2 > def findScore(first,second): > count=0 > for position in range(0,len(first)): > if first[position]==second[position]: > count=count+1 > position=position+1 > return count > > #shorter is a 3 amino acid sequence > ##longer is any length sequence greater than 3 > ###i=first amino acid; j=second amino acid; k=third amino acid > def findAlignment(shorter,longer): > for i in range(0,len(longer)-2): > for j in range(1,len(longer)-1): > for k in range(2,len(longer)): > dashline=padWithGaps(longer) > nextLine=replace(dashline,i,shorter[0]) > nextNext=replace(nextLine,j,shorter[1]) > alignment=replace(nextNext,k,shorter[2]) > score=findScore(longer,alignment) > ####don't know what to do here > print longer > print alignment > print "Score = " + str(score) > > I don't know what to do at the end of my loop but what I'm trying to do in > pseudocode is: > "if that alignment has the best score seen so far > save the score and the alignment > print the best score and the best alignment" > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From and1showgod at yahoo.com Mon Feb 7 20:45:55 2011 From: and1showgod at yahoo.com (Eun Koo) Date: Mon, 7 Feb 2011 11:45:55 -0800 (PST) Subject: [Tutor] JES Jython Message-ID: <131233.77321.qm@web34207.mail.mud.yahoo.com> Hi I have a problem in JES getting a solution to a function. Is there a way you guys can help? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Feb 7 21:58:50 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 07 Feb 2011 15:58:50 -0500 Subject: [Tutor] JES Jython In-Reply-To: <131233.77321.qm@web34207.mail.mud.yahoo.com> References: <131233.77321.qm@web34207.mail.mud.yahoo.com> Message-ID: <4D505D0A.6060602@gmail.com> On 2/7/2011 2:45 PM, Eun Koo wrote: > Hi I have a problem in JES getting a solution to a function. Is there > a way you guys can help? > Maybe. You might say more about the problem. What is JES and how does it relate to Python? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Feb 7 21:57:16 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 07 Feb 2011 21:57:16 +0100 Subject: [Tutor] JES Jython In-Reply-To: <131233.77321.qm@web34207.mail.mud.yahoo.com> References: <131233.77321.qm@web34207.mail.mud.yahoo.com> Message-ID: Eun Koo, 07.02.2011 20:45: > Hi I have a problem in JES getting a solution to a function. Is there a way you guys can help? If you can provide enough information for us to understand what your problem is, we may be able to help you. It's a matter of politeness to help us help you. The more work we have to put into figuring out what you want (or even what your words are supposed to mean), the less likely it is that someone will do that and help you out. Stefan From steve at pearwood.info Mon Feb 7 22:27:01 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 08 Feb 2011 08:27:01 +1100 Subject: [Tutor] nested loops In-Reply-To: References: <973783.90807.qm@web161215.mail.bf1.yahoo.com> Message-ID: <4D5063A5.60602@pearwood.info> Alan Gauld wrote: > "Wayne Werner" wrote > You probably want to add a sentinel to break out of the outer > loops too: I don't think you want to break out of *any* of the loops. Otherwise you will skip testing combinations. In your example, the first time you set highscore and alignment, you break out of all three loops and only test the first triple x,y,z. > found = False >> highscore = 0 >> alignment = somealignment >> for x in something and not found: >> for y in somethingelse and not found: >> for z in evenmoresomething: >> if x+y+z > highscore: >> highscore = x+y+z >> alignment = newalignment > found = True > break That's the equivalent of a return in the innermost loop. If you're looking for the *first* matching highscore, that's fine, but not if you want the biggest. -- Steven From steve at pearwood.info Mon Feb 7 22:37:00 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 08 Feb 2011 08:37:00 +1100 Subject: [Tutor] PyS60 request In-Reply-To: References: Message-ID: <4D5065FC.7080201@pearwood.info> Dipo Elegbede wrote: > Hello Everybody, > > I am working on a little project centered on PyS60, developing applications > for symbian phones. > > Before I start asking questions pertaining to that, I would like to first > clarify if it is appropriate to post such questions here. This is a mailing list about learning Python the programming language. If your question is about Python itself, then it doesn't matter if you are using PyS60, CPython, IronPython, PyPy, or any other implementation of Python. If your question is specifically about PyS60, then you are welcome to ask, but chances are high that there will not be anyone here who knows anything about PyS60. You might be better off trying the main Python mailing list, python-list at python.org, or if you prefer Usenet, comp.lang.python. Or you can look here for a mailing list specifically about Python on the Symbian: http://www.python.org/community/lists/ -- Steven From steve at pearwood.info Mon Feb 7 23:09:03 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 08 Feb 2011 09:09:03 +1100 Subject: [Tutor] JES Jython In-Reply-To: <131233.77321.qm@web34207.mail.mud.yahoo.com> References: <131233.77321.qm@web34207.mail.mud.yahoo.com> Message-ID: <4D506D7F.9000008@pearwood.info> Eun Koo wrote: > Hi I have a problem in JES getting a solution to a function. Is there a way you guys can help? Probably not. This is a mailing list about learning the language Python, not specific to JES (whatever that is!) under Jython. If JES has a support forum dedicated to it, you should try there. Otherwise, try a Jython mailing list. You might try the main Python mailing list, python-list at python.org, also available on Usenet as comp.lang.python. -- Steven From steve at pearwood.info Mon Feb 7 23:36:02 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 08 Feb 2011 09:36:02 +1100 Subject: [Tutor] function help In-Reply-To: <21116.46156.qm@web161201.mail.bf1.yahoo.com> References: <21116.46156.qm@web161201.mail.bf1.yahoo.com> Message-ID: <4D5073D2.5070908@pearwood.info> Ashley F wrote: > ok...here's the function I've written so far. > > def padWithGaps(seq): > for letter in seq: > letter="-" > line=len(seq) > dashline=line*letter > return dashline I don't think that's a useful function. It seems to do a HUGE amount of work that just keeps getting thrown away. Let's say seq = "GACT", this function will do the following: letter = "G" letter = "-" line = 4 # len of seq dashline = "----" letter = "A" letter = "-" line = 4 dashline = "----" letter = "C" letter = "-" line = 4 dashline = "----" letter = "T" letter = "-" line = 4 dashline = "----" It does everything four times. Now imagine that seq is a million characters long instead of four! This will do the job *much* faster: def padWithGaps(seq): return "-" * len(seq) *Much* faster, much easier to read. [...] > I don't know what to do at the end of my loop but what I'm trying to do in pseudocode is: > "if that alignment has the best score seen so far > save the score and the alignment > print the best score and the best alignment" You need to store the current best score and the current best alignment. Then each time around the innermost loop, you need to calculate the score and alignment (as you already do), and compare them to the best seen so far. If they are worse or equal, you don't need to do anything, just go on to the next loop as normal. But if they are better, then you need to update the best score and alignment, and print them. if score > best_score: best_score = score best_alignment = alignment print 'best seen so far is', score, alignment Does that help? Try writing the code, and if you still can't get it working, ask again. -- Steven From alan.gauld at btinternet.com Tue Feb 8 01:59:29 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Feb 2011 00:59:29 -0000 Subject: [Tutor] nested loops References: <973783.90807.qm@web161215.mail.bf1.yahoo.com> <4D5063A5.60602@pearwood.info> Message-ID: "Steven D'Aprano" wrote > I don't think you want to break out of *any* of the loops. Otherwise > you will skip testing combinations. In that case I misread the OP. I thought he specifically wanted to avoid testing all the options and exit when he reached his target. > In your example, the first time you set highscore and alignment, you > break out of all three loops Yep, thats what I thought was being asked for. It seems I mistook the intent. reading too quickly I suspect. Alan G From duretn at bellsouth.net Tue Feb 8 04:15:06 2011 From: duretn at bellsouth.net (Nevins Duret) Date: Mon, 7 Feb 2011 22:15:06 -0500 Subject: [Tutor] Converting From Unicode to ASCII!! Message-ID: <003001cbc73e$6328d030$297a7090$@bellsouth.net> Hello all, Don't know if I'll be bashed on this forum for doing this, but I will assure you I have the best intentions and simply want to apply a real world problem and how to go about solving it using python3.1. Here is my predicament. A good friend of mine locked herself out of her computer and forgot her password. I pretty much scoured the internet as a resource only to hit a brick wall. I tried using ophcrack version 2.3.1 in order to obtain the password and felt completely at home being that it was Linux, but then towards the end it failed and the output of this file which seems to contain the Users and passwords but in Unicode format: Administrator:500::31d6cfe0d16ae931b73c59d7e0c089c 0::: Guest:501::31d6cfe0d16ae931b73c59d7e0c089c0::: SUPPORT_388945a0:1002::881037e0b6909b04b6900f7c806 dca6e::: HelpAssistant:1004:b209ce7e3ff7aea1131906e9f5df481 9:d83f663c50bcd5815ccb94f9e38a9a4b::: Beverly:1005:00006395b1acd69aaad3b435b51404ee:992a c78ffb08204c592c6e47b916f85d::: And it didn't complete as a result of this error message: Tables found: /mnt/hdc/tables/xp_free_small Found one partition that contains hashes: /mnt/hda1/WINDOWS/system32/config Starting Ophcrack QIconvCodec::convertFromUnicode: using ASCII for conversion, iconv_open failed QIconvCodec::convertToUnicode: using ASCII for conversion, iconv_open failed /home/tux/launch.sh: line 100: 1044 Killed ABLES_INLINE -w $FOUND/ -n $numcpu -o /tmp/ophcrack.txt $opts Press a key to exit:: Now , I remember reading somewhere that Python is very good for converting Unicode data into ASCII and admittedly know nothing about this: Is there a work around in Python where I can simply import the file like and convert it to readable string using A for loop. Any help on this would be greatly appreciated. So far, I'm reading up on this topic at this url: http://docs.python.org/howto/unicode.html Best Regards, Nevins Duret -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexander.fairley at gmail.com Tue Feb 8 05:44:57 2011 From: alexander.fairley at gmail.com (Alexander Fairley) Date: Mon, 7 Feb 2011 23:44:57 -0500 Subject: [Tutor] vim as a python editor In-Reply-To: <4D27AE5D.3040806@pearwood.info> References: <4D27AE5D.3040806@pearwood.info> Message-ID: Some high profile ruby hackers have put together a pretty snazzy set of vim/gvim configs together on github at https://github.com/carlhuda/janus On the topic of configuring Capslock to be an escape key, it's because that's where the "meta" key used to be on old school unix keyboards, and so it makes you double plus unix if you reconfigure things that way(also has the plus of rendering emacs a lot more usable). On Fri, Jan 7, 2011 at 7:22 PM, Steven D'Aprano wrote: > Alan Gauld wrote: > >> "Paul Griffiths" wrote >> >>> I've learned that: >>> ... >>> - re-configuring the Caps Lock to be an extra Esc saves time >>> >> >> Huh? How do you use that? Its a new one on me. Why would two escape keys >> be useful? >> > > What if you want to escape the escape, so that (say) esc-C is the same as > just C? > > > Not-very-helpfully y'rs, > > -- > Steven > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Tue Feb 8 06:54:23 2011 From: smokefloat at gmail.com (David Hutto) Date: Tue, 8 Feb 2011 00:54:23 -0500 Subject: [Tutor] Converting From Unicode to ASCII!! In-Reply-To: <003001cbc73e$6328d030$297a7090$@bellsouth.net> References: <003001cbc73e$6328d030$297a7090$@bellsouth.net> Message-ID: On Mon, Feb 7, 2011 at 10:15 PM, Nevins Duret wrote: > Hello all, > > > > ??????????????? Don?t know if I?ll be bashed on this forum for doing this, > but I will assure you I have the best intentions and > > simply want to apply a real world problem and how to go about solving it > using python3.1.? Here is my? predicament. > > A good friend of mine locked herself out of her computer and forgot her > password.? I pretty much scoured the internet as > > a resource only to hit a brick wall.? I tried using ophcrack version 2.3.1 > in order to obtain the password and felt completely at home > > being that it was Linux,? but then towards the end it failed and the output > of this file which seems to contain the Users and passwords The linux forums might be better. Or you could use: http://www.google.com/search?client=ubuntu&channel=fs&q=linux+lost+password+brute+force&ie=utf-8&oe=utf-8 > > but in Unicode format: > > > > Administrator:500::31d6cfe0d16ae931b73c59d7e0c089c 0::: > Guest:501::31d6cfe0d16ae931b73c59d7e0c089c0::: > SUPPORT_388945a0:1002::881037e0b6909b04b6900f7c806 dca6e::: > HelpAssistant:1004:b209ce7e3ff7aea1131906e9f5df481 > 9:d83f663c50bcd5815ccb94f9e38a9a4b::: > Beverly:1005:00006395b1acd69aaad3b435b51404ee:992a > c78ffb08204c592c6e47b916f85d::: > > > > And it didn?t complete as a result of this error message: > > > > Tables found: > /mnt/hdc/tables/xp_free_small > > Found one partition that contains hashes: > /mnt/hda1/WINDOWS/system32/config > > Starting Ophcrack > QIconvCodec::convertFromUnicode: using ASCII for conversion, iconv_open > failed > QIconvCodec::convertToUnicode: using ASCII for conversion, iconv_open failed > /home/tux/launch.sh: line 100: 1044 Killed > ABLES_INLINE -w $FOUND/ -n $numcpu -o /tmp/ophcrack.txt $opts > Press a key to exit:: > > > > Now , I remember reading somewhere that Python is very good for converting > Unicode > > data into ASCII and admittedly know nothing about this: > > > > Is there a work around in Python where I can simply import the file like and > convert it to readable string using > > A for loop. > > > > Any help on this would be greatly appreciated.? So far, I?m reading up on > this topic at this url: > > http://docs.python.org/howto/unicode.html > > > > Best Regards, > > > > Nevins Duret > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- The lawyer in me says argue...even if you're wrong. The scientist in me... says shut up, listen, and then argue. But the lawyer won on appeal, so now I have to argue due to a court order. Furthermore, if you could be a scientific celebrity, would you want einstein sitting around with you on saturday morning, while you're sitting in your undies, watching Underdog?...Or better yet, would Einstein want you to violate his Underdog time? Can you imagine Einstein sitting around in his underware? Thinking about the relativity between his pubic nardsac, and his Fruit of the Looms, while knocking a few Dorito's crumbs off his inner brilliant white thighs, and hailing E = mc**2, and licking the orangy, delicious, Doritoey crust that layered his genetically rippled fingertips? But then again, J. Edgar Hoover would want his pantyhose intertwined within the equation. However, I digress, momentarily. But Einstein gave freely, for humanity, not for gain, other than personal freedom. An equation that benefited all, and yet gain is a personal product. Also, if you can answer it, is gravity anymore than interplanetary static cling? From smokefloat at gmail.com Tue Feb 8 07:00:02 2011 From: smokefloat at gmail.com (David Hutto) Date: Tue, 8 Feb 2011 01:00:02 -0500 Subject: [Tutor] Converting From Unicode to ASCII!! In-Reply-To: References: <003001cbc73e$6328d030$297a7090$@bellsouth.net> Message-ID: Also, If you can install a second version, then you should be able to mount the other version you're locked out of, then recover your files, and reinstall. From smokefloat at gmail.com Tue Feb 8 07:20:16 2011 From: smokefloat at gmail.com (David Hutto) Date: Tue, 8 Feb 2011 01:20:16 -0500 Subject: [Tutor] Converting From Unicode to ASCII!! In-Reply-To: References: <003001cbc73e$6328d030$297a7090$@bellsouth.net> Message-ID: And I forgot, that you don't have to install another version, but just boot from the live disk, and mount the partition. But from looking, you should be able to recover with linux utilities. Look here: http://aplawrence.com/Linux/lostlinuxpassword.htmlhttp://aplawrence.com/Linux/lostlinuxpassword.html From element.effect at gmail.com Tue Feb 8 06:18:29 2011 From: element.effect at gmail.com (Eric Stevens) Date: Mon, 7 Feb 2011 23:18:29 -0600 Subject: [Tutor] zipfile error message Message-ID: Hi: I am relatively new to Python and have been recently trying to experiment with its zipfile capabilities. However, everytime I try to open a zip ( using method zipfile.ZipFile(open('zipfile.zip','r')) ) I continue to get an error message that states:error: unpack requires a string argument of length 46. Would anyone be able to help me figure out what is wrong? I am currently running Python 2.7 on Windows (not sure if that matters). Thank you. Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Tue Feb 8 10:20:16 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Tue, 8 Feb 2011 09:20:16 +0000 Subject: [Tutor] Splitting a string Message-ID: hi all, i have a function which returns a string. for eg: X='101110'. i want to search for 0 and highlight the location. i am thinking of defining X as a list. but how can i split 101110 as there are no spaces in between? i'm thinking if i can put it into a list: X=['1','0','1','1','1','0'], then i can use index to point out the locations of the 0. pls advise. i'm using Python2.5 and WinXP. thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From ajarncolin at gmail.com Tue Feb 8 10:36:09 2011 From: ajarncolin at gmail.com (col speed) Date: Tue, 8 Feb 2011 16:36:09 +0700 Subject: [Tutor] Splitting a string In-Reply-To: References: Message-ID: On 8 February 2011 16:20, tee chwee liong wrote: > hi all, > > >i have a function which returns a string. for eg: X='101110'. i want to > search for 0 and highlight the location. > i> am thinking of defining X as a list. but how can i split 101110 as there > are no spaces in between? i'm thinking if i can put it into a list: > >X=['1','0','1','1','1','0'], then i can use index to point out the > locations of the 0. pls advise. > i>'m using Python2.5 and WinXP. > > >thanks > >tcl > > You can use x.find("0"), but this will only give you the first position. How about our friend 'enumerate'?: for index, i in enumerate(x): if i == "0": print index Cheers -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Feb 8 10:40:13 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 08 Feb 2011 11:40:13 +0200 Subject: [Tutor] Splitting a string In-Reply-To: References: Message-ID: <4D510F7D.7010003@compuscan.co.za> On 08/02/2011 11:20, tee chwee liong wrote: > hi all, > > i have a function which returns a string. for eg: X='101110'. i want > to search for 0 and highlight the location. > i am thinking of defining X as a list. but how can i split 101110 as > there are no spaces in between? i'm thinking if i can put it into a > list: X=['1','0','1','1','1','0'], then i can use index to point out > the locations of the 0. pls advise. > i'm using Python2.5 and WinXP. > > thanks > tcl > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > In Python strings are lists of characters so you can use indexes already. You can look at the .find() function to return you index numbers for the location of your search criteria, it only returns the first within your parameters, but you can create your own function utilising it to return all occurrences. -- Kind Regards, Christian Witts From steve at pearwood.info Tue Feb 8 12:09:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 08 Feb 2011 22:09:33 +1100 Subject: [Tutor] zipfile error message In-Reply-To: References: Message-ID: <4D51246D.7010705@pearwood.info> Eric Stevens wrote: > Hi: > > I am relatively new to Python and have been recently trying to experiment > with its zipfile capabilities. However, everytime I try to open a zip ( > using method zipfile.ZipFile(open('zipfile.zip','r')) ) I continue to get an > error message that states:error: unpack requires a string argument of length > 46. Would anyone be able to help me figure out what is wrong? I am currently > running Python 2.7 on Windows (not sure if that matters). Thank you. When posting error messages, please copy and paste the *entire* error message. Do not retype it, paraphrase it, or summarize it. But in this case, I can guess the error. You're opening the zip file in text mode: open('zipfile.zip','r') which will cause corruption of binary files. Zip files are binary and must be either opened in binary mode: open('zipfile.zip','rb') or better still, just pass the file name to ZipFile and let it open it: zipfile.ZipFile('zipfile.zip','r') -- Steven From steve at pearwood.info Tue Feb 8 12:13:01 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 08 Feb 2011 22:13:01 +1100 Subject: [Tutor] Splitting a string In-Reply-To: References: Message-ID: <4D51253D.9020208@pearwood.info> tee chwee liong wrote: > hi all, > > i have a function which returns a string. for eg: X='101110'. i want > to search for 0 and highlight the location. i am thinking of defining > X as a list. but how can i split 101110 as there are no spaces in > between? i'm thinking if i can put it into a list: > X=['1','0','1','1','1','0'], then i can use index to point out the > locations of the 0. pls advise. i'm using Python2.5 and WinXP. Strings are indexable, and have a find method: >>> s = "abcd" >>> s.find('c') 2 >>> s[2] 'c' To get a list, just ask for one: >>> list("abcd") ['a', 'b', 'c', 'd'] -- Steven From smokefloat at gmail.com Tue Feb 8 12:29:03 2011 From: smokefloat at gmail.com (David Hutto) Date: Tue, 8 Feb 2011 06:29:03 -0500 Subject: [Tutor] Splitting a string In-Reply-To: <4D51253D.9020208@pearwood.info> References: <4D51253D.9020208@pearwood.info> Message-ID: > To get a list, just ask for one: > >>>> list("abcd") > ['a', 'b', 'c', 'd'] > or., and this isn't to argue with anyone;), you could: >>> x = 'abcd' >>> y = [] >>> for letter in x: ... y.append(letter) ... >>> print y ['a', 'b', 'c', 'd'] which explains that the list is derived from the string. x is 'abcd', and list is the list seperated at the characters, and can be split further with string 'tags'. > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From paulmg2010 at gmail.com Tue Feb 8 12:31:49 2011 From: paulmg2010 at gmail.com (Paul Griffiths) Date: Tue, 8 Feb 2011 11:31:49 +0000 Subject: [Tutor] vim as a python editor In-Reply-To: References: <4D27AE5D.3040806@pearwood.info> Message-ID: On 8 February 2011 04:44, Alexander Fairley wrote: > Some high profile ruby hackers have put together a pretty snazzy set of > vim/gvim configs together on github at > > https://github.com/carlhuda/janus > > Thank you, but I think this only works on OSX? I use Ubuntu and if I understand your link correctly, gvim has the equivalent functionality. > On the topic of configuring Capslock to be an escape key, it's because > that's where the "meta" key used to be on old school unix keyboards, and so > it makes you double plus unix if you reconfigure things that way(also has > the plus of rendering emacs a lot more usable). > Sorry, I don't know what 'meta' key and 'double plus' means. What I've now done, using Preferences > Keyboard, is to swap the functionality of the Esc and Caps Lock keys. This helps me because I'm a fairly competent touch typist. Every time I need to press Esc on a default keyboard, I have to lift my left hand from the asdf home keys to get at it. This 'breaks the flow' and gets quite annoying after a while. > > On Fri, Jan 7, 2011 at 7:22 PM, Steven D'Aprano wrote: > >> Alan Gauld wrote: >> >>> "Paul Griffiths" wrote >>> >>>> I've learned that: >>>> ... >>>> >>>> - re-configuring the Caps Lock to be an extra Esc saves time >>>> >>> >>> Huh? How do you use that? Its a new one on me. Why would two escape keys >>> be useful? >>> >> >> What if you want to escape the escape, so that (say) esc-C is the same as >> just C? >> >> >> Not-very-helpfully y'rs, >> >> -- >> Steven >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Feb 8 12:48:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 08 Feb 2011 22:48:34 +1100 Subject: [Tutor] Converting From Unicode to ASCII!! In-Reply-To: <003001cbc73e$6328d030$297a7090$@bellsouth.net> References: <003001cbc73e$6328d030$297a7090$@bellsouth.net> Message-ID: <4D512D92.70500@pearwood.info> Nevins Duret wrote: > A good friend of mine locked herself out of her computer and forgot her > password. I pretty much scoured the internet as > a resource only to hit a brick wall. I tried using ophcrack version 2.3.1 > in order to obtain the password and felt completely at home > being that it was Linux, but then towards the end it failed and the output > of this file which seems to contain the Users and passwords > but in Unicode format: > > > > Administrator:500::31d6cfe0d16ae931b73c59d7e0c089c 0::: > Guest:501::31d6cfe0d16ae931b73c59d7e0c089c0::: > SUPPORT_388945a0:1002::881037e0b6909b04b6900f7c806 dca6e::: > HelpAssistant:1004:b209ce7e3ff7aea1131906e9f5df481 > 9:d83f663c50bcd5815ccb94f9e38a9a4b::: > Beverly:1005:00006395b1acd69aaad3b435b51404ee:992a > c78ffb08204c592c6e47b916f85d::: I see no Unicode there. It looks like plain ASCII. Are you sure you understand how to use ophcrack? Perhaps you should be asking on a ophcrack mailing list (if they have one). > And it didn't complete as a result of this error message: > > Tables found: > /mnt/hdc/tables/xp_free_small > > Found one partition that contains hashes: > /mnt/hda1/WINDOWS/system32/config > > Starting Ophcrack > QIconvCodec::convertFromUnicode: using ASCII for conversion, iconv_open > failed > QIconvCodec::convertToUnicode: using ASCII for conversion, iconv_open failed > /home/tux/launch.sh: line 100: 1044 Killed > ABLES_INLINE -w $FOUND/ -n $numcpu -o /tmp/ophcrack.txt $opts > Press a key to exit:: Looks to me like a bug in ophcrack, although I could be wrong. > Now , I remember reading somewhere that Python is very good for converting > Unicode > data into ASCII and admittedly know nothing about this: Before asking any more questions about converting Unicode to ASCII, I think you need to read this article: http://www.joelonsoftware.com/articles/Unicode.html You can't just "convert" Unicode to ASCII -- what would you expect to get if you convert (say) "????????"? For starters, you need to know what encoding(s) are being used. > Is there a work around in Python where I can simply import the file like and > convert it to readable string using > A for loop. Import *which* file? What does ophcrack consider "readable"? How do you know that you're not making the problem worse? No, don't go down this track. You'll probably end up making your friend's computer completely unusable without a complete re-build. My advice is to start with Microsoft's instructions: http://support.microsoft.com/kb/321305 and if they aren't helpful, then try using a Linux live cd to reset the password. You can find instructions on the internet, such as: http://www.ehow.com/how_6532691_change-xp-password-linux.html http://www.psychocats.net/ubuntucat/resetwindowspassword/ -- Steven From tcl76 at hotmail.com Tue Feb 8 14:04:17 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Tue, 8 Feb 2011 13:04:17 +0000 Subject: [Tutor] Splitting a string In-Reply-To: References: , <4D51253D.9020208@pearwood.info>, Message-ID: hi all, thanks for the advice. i modified my code to be: c=('01101') i=-1 try: while 1: i=c.index('0',i+1) print "Lane fail",i except ValueError: print "All Lanes PASS" pass when i run, the result is: >>> Lane fail 0 Lane fail 3 All Lanes PASS Question: How do i prevent the code from executing the except ValueError part. it seems to be checking bit by bit and when is see 1 it will execute the except part. i just want the results to be: >>> Lane fail 0 Lane fail 3 thanks tcl76 -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Tue Feb 8 14:09:35 2011 From: smokefloat at gmail.com (David Hutto) Date: Tue, 8 Feb 2011 08:09:35 -0500 Subject: [Tutor] Splitting a string In-Reply-To: References: <4D51253D.9020208@pearwood.info> Message-ID: Don't use the try and except, use a if else. I'm not as good as an explainer as the pros, but I can make enough sense if you respond back with a useful set of examples you've tried. From cwitts at compuscan.co.za Tue Feb 8 14:36:11 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 08 Feb 2011 15:36:11 +0200 Subject: [Tutor] Splitting a string In-Reply-To: References: , <4D51253D.9020208@pearwood.info>, Message-ID: <4D5146CB.1000803@compuscan.co.za> On 08/02/2011 15:04, tee chwee liong wrote: > hi all, > > thanks for the advice. i modified my code to be: > > c=('01101') > i=-1 > try: > while 1: > i=c.index('0',i+1) > print "Lane fail",i > except ValueError: > print "All Lanes PASS" > pass > > when i run, the result is: > > >>> > Lane fail 0 > Lane fail 3 > All Lanes PASS > > Question: How do i prevent the code from executing the except > ValueError part. it seems to be checking bit by bit and when is see 1 > it will execute the except part. > i just want the results to be: > >>> > Lane fail 0 > Lane fail 3 > > > thanks > tcl76 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > `while i < len(c)` instead of `while 1` -- Kind Regards, Christian Witts From smokefloat at gmail.com Tue Feb 8 14:38:50 2011 From: smokefloat at gmail.com (David Hutto) Date: Tue, 8 Feb 2011 08:38:50 -0500 Subject: [Tutor] Splitting a string In-Reply-To: <4D5146CB.1000803@compuscan.co.za> References: <4D51253D.9020208@pearwood.info> <4D5146CB.1000803@compuscan.co.za> Message-ID: On Tue, Feb 8, 2011 at 8:36 AM, Christian Witts wrote: > On 08/02/2011 15:04, tee chwee liong wrote: >> >> hi all, >> >> thanks for the advice. i modified my code to be: >> >> c=('01101') >> i=-1 >> try: >> ? ?while 1: >> ? ? ? ?i=c.index('0',i+1) >> ? ? ? ?print "Lane fail",i >> except ValueError: >> ? ?print "All Lanes PASS" >> ? ?pass >> >> when i run, the result is: >> >> >>> >> Lane fail 0 >> Lane fail 3 >> All Lanes PASS >> >> Question: How do i prevent the code from executing the except ValueError >> part. it seems to be checking bit by bit and when is see 1 it will execute >> the except part. >> i just want the results to be: >> >>> >> Lane fail 0 >> Lane fail 3 >> >> >> thanks >> tcl76 >> >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > `while i < len(c)` instead of `while 1` You remind me of me...like it was yesterday. Explanations with no thought. Unimpressive isn't it? > > -- > Kind Regards, > Christian Witts > > > -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From cwitts at compuscan.co.za Tue Feb 8 14:47:34 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 08 Feb 2011 15:47:34 +0200 Subject: [Tutor] Splitting a string In-Reply-To: References: <4D51253D.9020208@pearwood.info> <4D5146CB.1000803@compuscan.co.za> Message-ID: <4D514976.1020105@compuscan.co.za> On 08/02/2011 15:38, David Hutto wrote: > On Tue, Feb 8, 2011 at 8:36 AM, Christian Witts wrote: > >> On 08/02/2011 15:04, tee chwee liong wrote: >> >>> hi all, >>> >>> thanks for the advice. i modified my code to be: >>> >>> c=('01101') >>> i=-1 >>> try: >>> while 1: >>> i=c.index('0',i+1) >>> print "Lane fail",i >>> except ValueError: >>> print "All Lanes PASS" >>> pass >>> >>> when i run, the result is: >>> >>> >>>>>> >>> Lane fail 0 >>> Lane fail 3 >>> All Lanes PASS >>> >>> Question: How do i prevent the code from executing the except ValueError >>> part. it seems to be checking bit by bit and when is see 1 it will execute >>> the except part. >>> i just want the results to be: >>> >>>>>> >>> Lane fail 0 >>> Lane fail 3 >>> >>> >>> thanks >>> tcl76 >>> >>> >> `while i< len(c)` instead of `while 1` >> > You remind me of me...like it was yesterday. Explanations with no > thought. Unimpressive isn't it? > While the index is smaller than the length of the string do your processing. It reads like that. But thank you for your commentary. -- Kind Regards, Christian Witts From __peter__ at web.de Tue Feb 8 15:15:36 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Feb 2011 15:15:36 +0100 Subject: [Tutor] Splitting a string References: <4D51253D.9020208@pearwood.info> <4D5146CB.1000803@compuscan.co.za> Message-ID: Christian Witts wrote: > On 08/02/2011 15:04, tee chwee liong wrote: >> hi all, >> >> thanks for the advice. i modified my code to be: >> >> c=('01101') >> i=-1 >> try: >> while 1: >> i=c.index('0',i+1) >> print "Lane fail",i >> except ValueError: >> print "All Lanes PASS" >> pass >> >> when i run, the result is: >> >> >>> >> Lane fail 0 >> Lane fail 3 >> All Lanes PASS >> >> Question: How do i prevent the code from executing the except >> ValueError part. it seems to be checking bit by bit and when is see 1 >> it will execute the except part. >> i just want the results to be: >> >>> >> Lane fail 0 >> Lane fail 3 > `while i < len(c)` instead of `while 1` You have an off-by-one bug. But even if you fix that you'll still enter the except suite if the string c doesn't end with a "0". You need to keep track of the failed lanes, e. g.: for c in "011010", "111", "000", "", "1", "0", "001": print c.center(20, "-") i = -1 all_passed = True try: while True: i = c.index('0', i+1) print "Lane fail", i all_passed = False except ValueError: pass if all_passed: print "All Lanes PASS" From hugo.yoshi at gmail.com Tue Feb 8 15:28:56 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 8 Feb 2011 15:28:56 +0100 Subject: [Tutor] Splitting a string In-Reply-To: <4D514976.1020105@compuscan.co.za> References: <4D51253D.9020208@pearwood.info> <4D5146CB.1000803@compuscan.co.za> <4D514976.1020105@compuscan.co.za> Message-ID: On Tue, Feb 8, 2011 at 2:47 PM, Christian Witts >>> `while i< ?len(c)` instead of `while 1` >>> >> >> You remind me of me...like it was yesterday. Explanations with no >> thought. Unimpressive isn't it? >> > > While the index is smaller than the length of the string do your processing. > ?It reads like that. ?But thank you for your commentary. > The goal of this list is not to criticize, David, but to help. Why not provide some explanations yourself? EIther way, even with this correction a ValueError is still raised at least *once* if the string doesn't end with a 0, so it won't actually help a bit. A quick fix is to set some variable if you find a 0, then check on that variable after the loop (See Peter's example). Now, find is nice if you care about finding one instance, but if you need to find *all* instances you'll have to check the entire string anyway, and find becomes a rather cumbersome tool. Interestingly, enumerate was suggested all the way at the beginning of the thread, and I think it's the best answer: zeroes = ["lane fail {0}".format(i) for i, val in enumerate(c) if val == '0'] print '\n'.join(zeroes) if zeroes else "All Lanes pass" Ok, That looks a little advanced, but strip away all that syntactic sugar and you arrive at basically this: zeroes = [] for index, value in enumerate(c): if value == '0': zeroes.append(index) if zeroes: for x in zeroes: print "lane fail", x else: print "all lanes pass" Since we have to scan the whole string anyway, this is equally efficient as using find (theoretically!!! if you care about performance, *measure*). Hugo From polisetv at deshaw.com Tue Feb 8 10:13:58 2011 From: polisetv at deshaw.com (Polisetti, Vinay) Date: Tue, 8 Feb 2011 14:43:58 +0530 Subject: [Tutor] CrackTheInterview Message-ID: Visit http://www.cracktheinterview.org/ for more interview preparation tips and interview experiences of various people -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Feb 8 17:16:20 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 8 Feb 2011 10:16:20 -0600 (CST) Subject: [Tutor] zipfile error message In-Reply-To: References: Message-ID: On Mon, 7 Feb 2011, Eric Stevens wrote: > Hi: > I am relatively new to Python and have been recently trying to experiment > with its zipfile capabilities. However, everytime I try to open a zip ( > using method zipfile.ZipFile(open('zipfile.zip','r')) ) I continue to get an > error message that states:error: unpack requires a string argument of length > 46. Would anyone be able to help me figure out what is wrong? I am currently > running Python 2.7 on Windows (not sure if that matters). Thank you. zip files are not ascii text, so in order to send it to the zipfile you need to open it with the 'rb' flag to indicate you want to read in binary mode. HTH, Wayne From alan.gauld at btinternet.com Tue Feb 8 19:12:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Feb 2011 18:12:27 -0000 Subject: [Tutor] Apologies, mea culpa Message-ID: Sorry folks, I meant to hit discard on this one but clicked Accept by mistake. Alan G. List moderator From alan.gauld at btinternet.com Tue Feb 8 19:23:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 8 Feb 2011 18:23:11 -0000 Subject: [Tutor] Splitting a string References: Message-ID: "tee chwee liong" wrote > i have a function which returns a string. for eg: X='101110'. > i want to search for 0 and highlight the location. I'm not sure what you mean by highlight the location. Is it a GUI? Are you colour coding the characters? > i am thinking of defining X as a list. You shouldn't need to, you can treat the string as a sequence directly indexes = [i for i, c in enumerate(X) if char == '0'] Will give you the list of indexes you need. How you use that to highlight the zeros will depend on your UI I guess. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From tcl76 at hotmail.com Wed Feb 9 01:21:40 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Wed, 9 Feb 2011 00:21:40 +0000 Subject: [Tutor] Splitting a string In-Reply-To: References: , Message-ID: > I'm not sure what you mean by highlight the location. > Is it a GUI? Are you colour coding the characters? > hi, no it is not GUI. i just want to know where is the location of the 0 in the returned string. For eg: 10111, i want to say 0 is at lane 3 (calculating location from right to left). thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Wed Feb 9 01:32:05 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Wed, 9 Feb 2011 00:32:05 +0000 Subject: [Tutor] Splitting a string In-Reply-To: <4D5146CB.1000803@compuscan.co.za> References: , <4D51253D.9020208@pearwood.info>, , <4D5146CB.1000803@compuscan.co.za> Message-ID: > `while i < len(c)` instead of `while 1` > hi, i modified codes to be i>> Lane fail 0 Lane fail 3 All Lanes PASS >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 9 02:14:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 Feb 2011 01:14:22 -0000 Subject: [Tutor] Splitting a string References: , <4D51253D.9020208@pearwood.info>, , <4D5146CB.1000803@compuscan.co.za> Message-ID: "tee chwee liong" wrote ########### c=('01101') i=-1 try: while i References: , , <4D51253D.9020208@pearwood.info>, , , , <4D5146CB.1000803@compuscan.co.za>, , Message-ID: hi all, the code works: #### s='00101' found = False for i,c in enumerate(s): if c == '0': print 'Lane fail',i found = True if not found: print 'All lanes PASS ##### Result: >>> Lane fail 0 Lane fail 1 Lane fail 3 >>> the enumerate is checking from left to right. is it possible check from right to left? for eg:s='00101' Will give below result: Lane fail 1 Lane fail 3 Lane fail 4 thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 9 09:55:04 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 9 Feb 2011 08:55:04 +0000 (GMT) Subject: [Tutor] Splitting a string In-Reply-To: References: , , <4D51253D.9020208@pearwood.info>, , , , <4D5146CB.1000803@compuscan.co.za>, , Message-ID: <332160.83220.qm@web86705.mail.ird.yahoo.com> #### >s='00101' >found = False >for i,c in enumerate(s): > if c == '0': > print 'Lane fail',i > found = True > if not found: print 'All lanes PASS >##### > >the enumerate is checking from left to right. is it possible check from right to >left? > >for eg:s='00101' >The easiest way is just to reverse the string: for i,c in enumerate(reversed(s)): HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Wed Feb 9 11:08:20 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Wed, 9 Feb 2011 11:08:20 +0100 Subject: [Tutor] SMS to URL Message-ID: Hi peeps, I am trying to write a code such that i can send an sms to a specific url from my phone and get a reply back from the url. I want the reply to be the content of the url I send to; what modules would you advice. I am testing with the url: http://www.dipoelegbede.com/msg.txt. I have succeeded in writing a code that fetches the content of the page using urllib and urllib2 but i still want a way to have my sms speak to the url. I will appreciate any help in this direction. Advices or links to documentations would be fine. Thank You. -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Feb 9 11:30:42 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 09 Feb 2011 21:30:42 +1100 Subject: [Tutor] Splitting a string In-Reply-To: References: , , <4D51253D.9020208@pearwood.info>, , , , <4D5146CB.1000803@compuscan.co.za>, , Message-ID: <4D526CD2.3050300@pearwood.info> tee chwee liong wrote: > hi all, > > the code works: > #### > s='00101' > found = False > for i,c in enumerate(s): > if c == '0': > print 'Lane fail',i > found = True > if not found: print 'All lanes PASS No, it doesn't work. You haven't sufficiently tested it. It tells lies: >>> s='11100101' >>> found = False >>> for i,c in enumerate(s): ... if c == '0': ... print 'Lane fail',i ... found = True ... if not found: print 'All lanes PASS' ... All lanes PASS All lanes PASS All lanes PASS Lane fail 3 Lane fail 4 Lane fail 6 All lanes did NOT pass. > the enumerate is checking from left to right. is it possible check from right to left? > for eg:s='00101' > > Will give below result: > Lane fail 1 > Lane fail 3 > Lane fail 4 for i,c in enumerate(reversed(s)) is the easiest way. -- Steven From kyronoth at gmail.com Wed Feb 9 12:09:28 2011 From: kyronoth at gmail.com (de Haan) Date: Wed, 9 Feb 2011 12:09:28 +0100 Subject: [Tutor] System Monitoring Message-ID: Hi, Im fairly new to programming in python, and have a question. Im looking to build a program that monitor's certain things on my Linux system. for instance disk space. What is the best way to monitor a Linux server without using to much resources? Should I execute shell commands and grab the output of them? Or should i use SNMP. Or is there a better way? Thanks in advance! de Haan -------------- next part -------------- An HTML attachment was scrubbed... URL: From nitinpawar432 at gmail.com Wed Feb 9 12:17:27 2011 From: nitinpawar432 at gmail.com (Nitin Pawar) Date: Wed, 9 Feb 2011 16:47:27 +0530 Subject: [Tutor] System Monitoring In-Reply-To: References: Message-ID: We use nagios for all of our monitoring which provides central information for all machines its ok to use shell scripts to do system level monitoring (minimal level) but if you have complex monitoring on java programs and all then use jmax etc Thanks, Nitin On Wed, Feb 9, 2011 at 4:39 PM, de Haan wrote: > Hi, > > Im fairly new to programming in python, and have a question. > > Im looking to build a program that monitor's certain things on my Linux > system. for instance disk space. What is the best way to monitor a Linux > server without using to much resources? > > Should I execute shell commands and grab the output of them? Or should i > use SNMP. Or is there a better way? > > Thanks in advance! > de Haan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Nitin Pawar -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Feb 9 12:18:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 09 Feb 2011 22:18:28 +1100 Subject: [Tutor] System Monitoring In-Reply-To: References: Message-ID: <4D527804.5060505@pearwood.info> de Haan wrote: > Hi, > > Im fairly new to programming in python, and have a question. > > Im looking to build a program that monitor's certain things on my Linux > system. for instance disk space. What is the best way to monitor a Linux > server without using to much resources? Why reinvent the wheel? What's wrong with using an existing system such as Nagios or Cactii? > Should I execute shell commands and grab the output of them? Or should i use > SNMP. Or is there a better way? Depends on what and how often you're checking. -- Steven From kyronoth at gmail.com Wed Feb 9 12:25:08 2011 From: kyronoth at gmail.com (de Haan) Date: Wed, 9 Feb 2011 12:25:08 +0100 Subject: [Tutor] System Monitoring In-Reply-To: <4D527804.5060505@pearwood.info> References: <4D527804.5060505@pearwood.info> Message-ID: On Wed, Feb 9, 2011 at 12:18 PM, Steven D'Aprano wrote: > de Haan wrote: > >> Hi, >> >> Im fairly new to programming in python, and have a question. >> >> Im looking to build a program that monitor's certain things on my Linux >> system. for instance disk space. What is the best way to monitor a Linux >> server without using to much resources? >> > > Why reinvent the wheel? What's wrong with using an existing system such as > Nagios or Cactii? This is true, and yes, Nagios is good for this job. But im wondering what the best way is... > > > > Should I execute shell commands and grab the output of them? Or should i >> use >> SNMP. Or is there a better way? >> > > Depends on what and how often you're checking. > Most likely live monitoring. > > > -- > Steven > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Feb 9 12:35:18 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 09 Feb 2011 22:35:18 +1100 Subject: [Tutor] System Monitoring In-Reply-To: References: <4D527804.5060505@pearwood.info> Message-ID: <4D527BF6.3010007@pearwood.info> de Haan wrote: > On Wed, Feb 9, 2011 at 12:18 PM, Steven D'Aprano wrote: > >> de Haan wrote: >> >>> Hi, >>> >>> Im fairly new to programming in python, and have a question. >>> >>> Im looking to build a program that monitor's certain things on my Linux >>> system. for instance disk space. What is the best way to monitor a Linux >>> server without using to much resources? >>> >> Why reinvent the wheel? What's wrong with using an existing system such as >> Nagios or Cactii? > > > This is true, and yes, Nagios is good for this job. But im wondering what > the best way is... Define "best". Cheapest? Fastest? Most reliable? Least impact? Most powerful? You can pick any one, maybe two if you're lucky. But in general, the best tool is the one that already exists, not the one that you will spend six months writing to be a fifth as useful. -- Steven From tcl76 at hotmail.com Wed Feb 9 12:44:08 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Wed, 9 Feb 2011 11:44:08 +0000 Subject: [Tutor] Splitting a string In-Reply-To: <4D526CD2.3050300@pearwood.info> References: , ,,<4D51253D.9020208@pearwood.info>, , , , , , <4D5146CB.1000803@compuscan.co.za>, , , , , , <4D526CD2.3050300@pearwood.info> Message-ID: > No, it doesn't work. You haven't sufficiently tested it. It tells lies: > > > >>> s='11100101' > >>> found = False > >>> for i,c in enumerate(s): > ... if c == '0': > ... print 'Lane fail',i > ... found = True > ... if not found: print 'All lanes PASS' > ... > All lanes PASS > All lanes PASS > All lanes PASS > Lane fail 3 > Lane fail 4 > Lane fail 6 > > All lanes did NOT pass. > thanks for catching the bug. the code should be: #### s='11100101' found = False for i,c in enumerate(reversed(s)): if c == '0': print 'Lane fail',i found = True if not found: print 'All lanes PASS' ### the if not found needs to be indented. result: >>> Lane fail 1 Lane fail 3 Lane fail 4 >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyronoth at gmail.com Wed Feb 9 13:18:48 2011 From: kyronoth at gmail.com (de Haan) Date: Wed, 9 Feb 2011 13:18:48 +0100 Subject: [Tutor] System Monitoring In-Reply-To: <4D527BF6.3010007@pearwood.info> References: <4D527804.5060505@pearwood.info> <4D527BF6.3010007@pearwood.info> Message-ID: On Wed, Feb 9, 2011 at 12:35 PM, Steven D'Aprano wrote: > de Haan wrote: > >> On Wed, Feb 9, 2011 at 12:18 PM, Steven D'Aprano > >wrote: >> >> de Haan wrote: >>> >>> Hi, >>>> >>>> Im fairly new to programming in python, and have a question. >>>> >>>> Im looking to build a program that monitor's certain things on my Linux >>>> system. for instance disk space. What is the best way to monitor a Linux >>>> server without using to much resources? >>>> >>>> Why reinvent the wheel? What's wrong with using an existing system such >>> as >>> Nagios or Cactii? >>> >> >> >> This is true, and yes, Nagios is good for this job. But im wondering what >> the best way is... >> > > Define "best". > > Cheapest? Fastest? Most reliable? Least impact? Most powerful? You can pick > any one, maybe two if you're lucky. > > The best way to talk with the system hardware. (or is that to general?) > > But in general, the best tool is the one that already exists, not the one > that you will spend six months writing to be a fifth as useful. > > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 9 13:35:51 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 9 Feb 2011 12:35:51 -0000 Subject: [Tutor] Splitting a string References: , , , <4D51253D.9020208@pearwood.info>, , , , , , <4D5146CB.1000803@compuscan.co.za>, , , , , , <4D526CD2.3050300@pearwood.info> Message-ID: "tee chwee liong" wrote t> hanks for catching the bug. the code should be: > s='11100101' > found = False > for i,c in enumerate(reversed(s)): > if c == '0': > print 'Lane fail',i > found = True > if not found: print 'All lanes PASS' > > the if not found needs to be indented. No, exactly the opposite - the last line needs to be ex-dented. ie taken out of the loop. Take a look at my original post. Alan G. From scarolan at gmail.com Wed Feb 9 16:18:56 2011 From: scarolan at gmail.com (Sean Carolan) Date: Wed, 9 Feb 2011 09:18:56 -0600 Subject: [Tutor] System Monitoring In-Reply-To: References: Message-ID: > Hi, > Im fairly new to programming in python, and have a question. > Im looking to build a program that monitor's certain things on my Linux > system. for instance disk space. What is the best way to monitor a Linux > server without using to much resources? > Should I execute shell commands and grab the output of them? Or should i use > SNMP. Or is there a better way? > Thanks in advance! > de Haan de Haan: I'm guessing from the text of your message that this is a single, stand-alone system. Nagios and cacti are complete overkill for system monitoring on a single machine. Here are some other options that you can try: * GUI monitoring - gkrellm is great for this. You can run it and see performance graphs and monitors right in a little app on your desktop. * Command line monitoring - it's pretty easy to cobble together a python script that monitors things like load average, memory, disk space, etc. Hint: you can get a *lot* of useful info from the /proc directory, for example, /proc/meminfo, /proc/loadavg, etc. Here's a quickie that I built for a client, it watches the 15 minute load average. #!/usr/bin/env python ''' File: load_average_watcher.py Author: Sean Carolan Description: Watches 15 minute load average and alerts sysadmin if it gets over a certain level. ''' import smtplib from email.MIMEText import MIMEText threshhold = 3.0 sender = 'root at server.com' recipient = 'sysadmin at example.com' def sendMail(): msg = MIMEText("Alert - system load is over "+str(threshhold)) msg['Subject'] = 'System Load Alert' msg['From'] = sender msg['To'] = recipient s = smtplib.SMTP() s.connect() s.sendmail(sender, [recipient], msg.as_string()) s.close() for line in open('/proc/loadavg'): #If the load average is above threshhold, send alert loadav = float(line.split()[2]) if loadav < threshhold: print '15 minute load average is '+str(loadav)+': OK!' else: print '15 minute load average is '+str(loadav)+': HIGH!' sendMail() From kyronoth at gmail.com Wed Feb 9 16:32:08 2011 From: kyronoth at gmail.com (de Haan) Date: Wed, 9 Feb 2011 16:32:08 +0100 Subject: [Tutor] System Monitoring In-Reply-To: References: Message-ID: On Wed, Feb 9, 2011 at 4:18 PM, Sean Carolan wrote: > > Hi, > > Im fairly new to programming in python, and have a question. > > Im looking to build a program that monitor's certain things on my Linux > > system. for instance disk space. What is the best way to monitor a Linux > > server without using to much resources? > > Should I execute shell commands and grab the output of them? Or should i > use > > SNMP. Or is there a better way? > > Thanks in advance! > > de Haan > > de Haan: > > I'm guessing from the text of your message that this is a single, > stand-alone system. Nagios and cacti are complete overkill for system > monitoring on a single machine. Here are some other options that you > can try: > > * GUI monitoring - gkrellm is great for this. You can run it and see > performance graphs and monitors right in a little app on your desktop. > > * Command line monitoring - it's pretty easy to cobble together a > python script that monitors things like load average, memory, disk > space, etc. Hint: you can get a *lot* of useful info from the /proc > directory, for example, /proc/meminfo, /proc/loadavg, etc. > > Here's a quickie that I built for a client, it watches the 15 minute > load average. > > #!/usr/bin/env python > ''' > File: load_average_watcher.py > Author: Sean Carolan > Description: Watches 15 minute load average and alerts sysadmin if it > gets over a certain level. > ''' > > import smtplib > from email.MIMEText import MIMEText > > threshhold = 3.0 > sender = 'root at server.com' > recipient = 'sysadmin at example.com' > > def sendMail(): > msg = MIMEText("Alert - system load is over "+str(threshhold)) > msg['Subject'] = 'System Load Alert' > msg['From'] = sender > msg['To'] = recipient > s = smtplib.SMTP() > s.connect() > s.sendmail(sender, [recipient], msg.as_string()) > s.close() > > for line in open('/proc/loadavg'): > #If the load average is above threshhold, send alert > loadav = float(line.split()[2]) > if loadav < threshhold: > print '15 minute load average is '+str(loadav)+': OK!' > else: > print '15 minute load average is '+str(loadav)+': HIGH!' > sendMail() > This was indeed what i was thinking. So using /proc is a viable/recommended way of programming a system monitoring tool? And do you run this via a cron job? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Feb 9 20:42:16 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 10 Feb 2011 06:42:16 +1100 Subject: [Tutor] System Monitoring In-Reply-To: References: Message-ID: <4D52EE18.3040906@pearwood.info> Sean Carolan wrote: >> Hi, >> Im fairly new to programming in python, and have a question. >> Im looking to build a program that monitor's certain things on my Linux >> system. for instance disk space. What is the best way to monitor a Linux >> server without using to much resources? >> Should I execute shell commands and grab the output of them? Or should i use >> SNMP. Or is there a better way? >> Thanks in advance! >> de Haan > > de Haan: > > I'm guessing from the text of your message that this is a single, > stand-alone system. Nagios and cacti are complete overkill for system > monitoring on a single machine. Here are some other options that you > can try: More options are good, but de Haan describes it as a Linux *server*, not desktop. In any case, some people might disagree that nagios is overkill -- it depends on what you want to monitor. > * GUI monitoring - gkrellm is great for this. You can run it and see > performance graphs and monitors right in a little app on your desktop. I've used that. I can't say it excited me too much. > Here's a quickie that I built for a client, it watches the 15 minute > load average. [...] Your script appears to mix tabs and spaces for indentation. Either that or Thunderbird is playing silly buggers. Specifically: > for line in open('/proc/loadavg'): > #If the load average is above threshhold, send alert > loadav = float(line.split()[2]) > if loadav < threshhold: > print '15 minute load average is '+str(loadav)+': OK!' > else: > print '15 minute load average is '+str(loadav)+': HIGH!' > sendMail() Note the inconsistent indent at the end. -- Steven From matlocs at odscompanies.com Wed Feb 9 23:56:26 2011 From: matlocs at odscompanies.com (Shawn Matlock) Date: Wed, 9 Feb 2011 14:56:26 -0800 Subject: [Tutor] list of strings Message-ID: <1160CE2227C1694BA39144335BC3502540BCDC73A2@MAIL.pdx.odshp.com> Hello All, I'm doing something wrong. This prints a list of data source names: # List all data sources dataSourceList = AdminConfig.list('DataSource') # .split(ls) if verbose == 'True': print 'DEBUG Data Source List: ' print dataSourceList DEBUG Data Source List: "Facets Data Source(cells/Staging2Cell|resources.xml#DataSource_1267574027582)" "Facets Extended DataSource(cells/Staging2Cell|resources.xml#DataSource_1267574091663)" "Facets Reporting Database(cells/Staging2Cell|resources.xml#DataSource_1267574150361)" CorpReports(cells/Staging2Cell|resources.xml#DataSource_1270069048670) DefaultEJBTimerDataSource(cells/Staging2Cell/applications/cisNotesEar.ear/deployments/cisNotesEar|resources.xml#DataSour ce_1216665969544) DefaultEJBTimerDataSource(cells/Staging2Cell/nodes/pyxisNode01/servers/Agent01|resources.xml#DataSource_1000001) DefaultEJBTimerDataSource(cells/Staging2Cell/nodes/pyxisNode01/servers/DBIC01|resources.xml#DataSource_1000001) I expected this to print each data source name in the list. Instead, it is printing each character: # Modify the data sources so that the aged timeout is set correctly. for dataSource in dataSourceList: print 'DataSource: %s' % dataSource time.sleep(5) DataSource: " DataSource: F DataSource: a DataSource: c DataSource: e Thank you, ---------------------------------- Shawn Matlock Lead Application Admin ODS (503) 228-6554 http://www.odscompanies.com This message is intended for the sole use of the individual and entity to whom it is addressed, and may contain information that is privileged, confidential and exempt from disclosure under applicable law. If you are not the intended addressee, nor authorized to receive for the intended addressee, you are hereby notified that you may not use, copy, disclose or distribute to anyone the message or any information contained in the message. If you have received this message in error, please immediately advise the sender by reply email and delete the message. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Thu Feb 10 00:21:46 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 10 Feb 2011 00:21:46 +0100 Subject: [Tutor] list of strings In-Reply-To: <1160CE2227C1694BA39144335BC3502540BCDC73A2@MAIL.pdx.odshp.com> References: <1160CE2227C1694BA39144335BC3502540BCDC73A2@MAIL.pdx.odshp.com> Message-ID: On Wed, Feb 9, 2011 at 11:56 PM, Shawn Matlock wrote: > Hello All, > > I?m doing something wrong. > This prints a list of data source names: > > ??? # List all data sources > ??? dataSourceList = AdminConfig.list('DataSource') # .split(ls) > ??? if verbose == 'True': > ??????? print 'DEBUG Data Source List: ' > ??????? print dataSourceList > [snip] > > I expected this to print each data source name in the list. Instead, it is > printing each character: > > ??? # Modify the data sources so that the aged timeout is set correctly. > ??? for dataSource in dataSourceList: > ??????? print 'DataSource: %s' % dataSource > ??????? time.sleep(5) > > DataSource: " > DataSource: F > DataSource: a > DataSource: c > DataSource: e > > First off, please use plain text formatting when sending emails to this list. I like fancy colors as much as the next guy, but html emails screw up my replies like there's no tomorrow, making me spend extra work to format everything correctly. The problem is that dataSourceList is not, as the name implies, a list, but a string. Iterating over strings happens on a character basis. If you re-add the .split() that was commented out, you should get a list. The split method splits the string at the specified character. To split the string on newlines you can do split('\n') on linux or split('\r\n') on windows. Hugo From dwbarne at gmail.com Thu Feb 10 01:17:44 2011 From: dwbarne at gmail.com (Daniel Barnette) Date: Wed, 9 Feb 2011 17:17:44 -0700 Subject: [Tutor] PMW combobox won't display properly using X Message-ID: I've written a Python gui using Python Mega Widgets (PMW) that works beautifully when run natively on Windows or Linux. However, when I run the app on a Linux box and try to display it back to my Windows box using an X server (like freeXer or XMing), the combobox widget's drop-down menu is squashed all to the left, leaving just a small vertical bar which otherwise should be a wide drop-down menu. Can't scroll it or select anything in it -- it's not wide enough to see anything in it. I've tried this on several machines, all producing the same result. Does anyone know why this should happen and what might be the solution? -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Feb 10 01:28:45 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 09 Feb 2011 16:28:45 -0800 Subject: [Tutor] PMW combobox won't display properly using X In-Reply-To: References: Message-ID: On 2/9/2011 4:17 PM Daniel Barnette said... > Python Mega Widgets Generally speaking, issues with third party packages are best resolved on the package's specific support forum. In this case, try at http://lists.sourceforge.net/lists/listinfo/pmw-general HTH, Emile From alan.gauld at btinternet.com Thu Feb 10 01:54:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Feb 2011 00:54:45 -0000 Subject: [Tutor] PMW combobox won't display properly using X References: Message-ID: "Daniel Barnette" wrote > However, when I run the app on a Linux box and try to display it > back to my > Windows box using an X server (like freeXer or XMing), the combobox > widget's > drop-down menu is squashed all to the left, Thats a pretty specific query about Tkinter and PMW and X servers. I suspect the Tkinter or PMW mailing lists might offer bettwer support. This list is really for issues with Python and basic programming topics. Basic Tkinter usually gets an answer but something so off mainstream is better dealt with by specialists. Alan G. From wallenpb at gmail.com Thu Feb 10 05:17:48 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 9 Feb 2011 22:17:48 -0600 Subject: [Tutor] python packaging systems Message-ID: I have found there are a few systems available to package Python programs as standalone programs for distribution. Do the folks here have any recommendation or comment on any of these? Thanks, --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Thu Feb 10 11:42:22 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Thu, 10 Feb 2011 05:42:22 -0500 Subject: [Tutor] python packaging systems In-Reply-To: References: Message-ID: <4D53C10E.3030202@aim.com> On 02/09/2011 11:17 PM, Bill Allen wrote: > I have found there are a few systems available to package Python programs as > standalone programs for distribution. Do the folks here have any > recommendation or comment on any of these? > > Thanks, > --Bill > I found cx_Freeze to be the most useful, because it supported Python 3. The mailing list is also very helpful. ~Corey From enalicho at gmail.com Thu Feb 10 11:50:36 2011 From: enalicho at gmail.com (Noah Hall) Date: Thu, 10 Feb 2011 10:50:36 +0000 Subject: [Tutor] python packaging systems In-Reply-To: References: Message-ID: On Thu, Feb 10, 2011 at 4:17 AM, Bill Allen wrote: > > I have found there are a few systems available to package Python programs as > standalone programs for distribution.?? Do the folks here have any > recommendation or comment on any of these? My favourites are http://www.py2exe.org/ and http://www.pyinstaller.org/ From alan.gauld at btinternet.com Thu Feb 10 17:14:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 Feb 2011 16:14:33 -0000 Subject: [Tutor] python packaging systems References: Message-ID: "Bill Allen" wrote >I have found there are a few systems available to package Python >programs as > standalone programs for distribution. Do the folks here have any > recommendation or comment on any of these? Personally I don't like them and prefer to install a version of Python and then install my modules separately. If you want to hide your code(a little bit) you can ship only the pyc files rather than the py. Otherwise py2exe etc helps a little bit in concealing your design. But I'm not convinced it is worth the effort, or the potential cluttering of your users hard drive with multiple Python interpreters. But I confess I'm not in the business of selling commercial Python apps and if I was I might feel differently! :-) Alan G From swiftone at swiftone.org Thu Feb 10 18:26:37 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Thu, 10 Feb 2011 12:26:37 -0500 Subject: [Tutor] python packaging systems In-Reply-To: References: Message-ID: On Thu, Feb 10, 2011 at 11:14 AM, Alan Gauld wrote: > Personally I don't like them and prefer to install a version of Python > and then install my modules separately. > > If you want to hide your code(a little bit) you can ship only the pyc ... Don't forget that the motivation need not be obfuscation. I myself like to package standalone programs for non-techie friends and family to use. For them, "Run this" is a good first instruction versus "Install Python..." (regardless of how much their lives might be improved by the latter :) ) -- Brett Ritter / SwiftOne swiftone at swiftone.org From karim.liateni at free.fr Thu Feb 10 19:12:48 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 10 Feb 2011 19:12:48 +0100 Subject: [Tutor] Accessing query results html frame Message-ID: <4D542AA0.5080801@free.fr> Hello All, I get from Steven an very useful link (void space) for http authentication. I added some codes to be able to POST FORM a query as I do it by clicking a query button to get a list of bug Id on a server. The problem is I get a html page which refers 2 frames. And I am interesting in one particular frame namely for example, http://{server}:{port}/wt/tmp/results:karim.liateni.31_3917.html'.format(server=server, port=port). But this pages is created every times in a tmp directory each time with a different name. 1) How can I get the name of this page because with python the page resulting of my query is not mentionned (hidden like)? Interactively there are 3 frames but only this one is of interest for me. But no name of this page is visible in the main html page. Is there a method to get all the nested frames locations? 2) I can see this page interactively when I click on a submit query button. Do I need to add 'ACTION': "Query" data = { 'NextForm': "", 'LastForm': "SavedQuery", 'prompted': "yes", 'class': "Development", 'personalQuery': "DKPV", 'REMOTE_USER': username, 'QS': " -p DKPVALIDATION_PLUGIN \(Class 'isequal' "Development" \)", 'use_field_defs':"false", 'QueryName': "DKPV", 'QueryType': "personal", 'ACTION': "Query" } query = urllib.urlencode(data) request = urllib2.Request(theurl, query) passman = urllib2.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, theurl, username, password) authhandler = urllib2.HTTPBasicAuthHandler(passman) opener = urllib2.build_opener(authhandler) urllib2.install_opener(opener) pagehandle = urllib2.urlopen(request) print(pagehandle.read()) From alan.gauld at btinternet.com Thu Feb 10 19:21:51 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 10 Feb 2011 18:21:51 +0000 (GMT) Subject: [Tutor] python packaging systems In-Reply-To: References: Message-ID: <137651.6275.qm@web86708.mail.ird.yahoo.com> Yes, but a good installer will install Python (if needed) and then your app in one seamless operation from the users point of view. Then create the launch shortcut in the appropriate start menu. So the user only needs to click the launch icon to start the app, the fact that it's a Python scri[pt v a VB program versus a C++ native binary should be irrelevant to them. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Original Message ---- > From: Brett Ritter > To: Alan Gauld > Cc: tutor at python.org > Sent: Thursday, 10 February, 2011 17:26:37 > Subject: Re: [Tutor] python packaging systems > > On Thu, Feb 10, 2011 at 11:14 AM, Alan Gauld >wrote: > > Personally I don't like them and prefer to install a version of Python > > and then install my modules separately. > > > > If you want to hide your code(a little bit) you can ship only the pyc > ... > > Don't forget that the motivation need not be obfuscation. I myself > like to package standalone programs for non-techie friends and family > to use. For them, "Run this" is a good first instruction versus > "Install Python..." (regardless of how much their lives might be > improved by the latter :) ) > > -- > Brett Ritter / SwiftOne > swiftone at swiftone.org > From ranceh at gmail.com Thu Feb 10 20:52:47 2011 From: ranceh at gmail.com (Rance Hall) Date: Thu, 10 Feb 2011 13:52:47 -0600 Subject: [Tutor] SMS to URL In-Reply-To: References: Message-ID: On Wed, Feb 9, 2011 at 4:08 AM, Dipo Elegbede wrote: > Hi peeps, > I am trying to write a code such that i can send an sms to a specific url > from my phone and get a reply back from the url. > I want the reply to be the content of the url I send to; what modules would > you advice. > I am testing with the url: http://www.dipoelegbede.com/msg.txt. > I have succeeded in writing a code that fetches the content of the page > using urllib and urllib2 but i still want a way to have my sms speak to the > url. > I will appreciate any help in this direction. Advices or links to > documentations would be fine. > Thank You. > I'm not convinced that what you say you want to do is really what you want to do, so I may be off base here, but as far as I know, you can not send an SMS message to anything other than a phone number. Many cell providers offer email-sms-gateway services so that you can send an email to the email address that matches your phone, and the phone company turns the email into an SMS and sends it to your phone for you. If your carrier has an emaiil-to-sms gateway then its reasonably trivial to use urllib and capture a web page and send it to you. Its the remote control aspect that you have requested that has me stumped. A friend of mine runs a phone message service and he has a device hooked to his network that has an antenna on it that sends sms message directly on the carrier network. If you had one of these things (which I doubt you do) I'm sure you could reverse it and send an sms message directly to your network. But the work that would be required to set this up (not to mention the expense) seems like more trouble than it is worth. Sorry I wasn't more help. Rance From smed at missinglynx.net Thu Feb 10 22:52:12 2011 From: smed at missinglynx.net (John Martinetti) Date: Thu, 10 Feb 2011 16:52:12 -0500 Subject: [Tutor] process and modify a list of strings, in place Message-ID: Hello - I'm a novice programmer, not even amateur level and I need some help with developing an algorithm to process a list of strings. I hope this list is tolerant of n00bs, if not, please let me know and I'll take this elsewhere. Some background. I cut up a text based report from a reporting application into fields by slicing the lines up using fixed column widths to delimit the fields. This was necessary to ensure that a couple of the fields that had free-form "comments" with variable spacing. If there were well-defined field delimiters I could have used awk or some other text processing tool. Python worked very well for cutting up the lines from the report into fields and let me store each "record" into a list of strings. So - I have a list of openPOs which is a list of strings. I do this like this: ############################################################################################################# #! /usr/bin/python import sys, re txtreport=open("open_pos.txt",'r') openPOs=[] while 1: record = txtreport.readline() # - reads in a line of data from the report file vendornum = record[:6] # - breaks out each column of the report into fields vendorname = record[7:40] ordernum = record[41:47] ordersuffix = record[48:59] orderdate = record[60:70] buyer = record[71:77] partnum = record[78:100] qty = record[101:108] comment = record[109:135] # - create a record from all the fields linedata = (vendornum, vendorname, ordernum, ordersuffix, orderdate, buyer, partnum, qty, comment) # - append the record to the list of records representing the CQ report openPOs.append(linedata) # if not the end of the file, do it again if not record: break ######################################################################################################################## All of the records (each one is type list) has a field (of type string) that represents the "buyer ID" (the report is about purchase orders). Due to the crappy ERP application we have, there are Purchase Orders in the system with no "buyer ID" (six spaces). Obviously, this is a problem. I need to be able to scan each record in, detect whether field index #5 is blank and has no buyer ID, and if so, change that field to be "NOBUYER" instead of blank (six spaces actually) so that some further processing down the road can pick up on that and handle it appropriately. I can reliably detect the field as being blank using the following code: for line in openPOs: ### openPOs is of type 'list' if line[5] == " ": print "The buyerID field is blank!!!!" I can run this code after the initial routine that chops up the text based report and stores it into the list "openPOs" and reliably detect each "record"(list) has a blank "buyerID" field (which is field #5 as you can tell by my slice). The part I'm having a problem with is once I've detected that a record has a blank buyerID field, I can't seem to figure out how to change it, in place. I've tried finding the index of the openPOs using this: openPOs.index(line) and then trying to change the item like this: openPOs[openPOs.index(line),5] = "NOBUYER" but I'm getting a strange error: "TypeError: 'tuple' object does not support item assignment" I've thrown in a bunch of debugging code to "type" each variable I'm using...the "line" variable in the code above is the only tuple, but I can't for the life of me figure out what I'm doing wrong. And now I've been staring at it too long and I'm getting myself confused. Perhaps I'm going about changing this field in this list of strings all the wrong way....I'm somewhat familiar with indexing a multi-dimensional array in other languages to search for certain values and replace them with something else, but I'm kinda stumped on this one. Any thoughts would be appreciated. I can share more code but I need to sanitize it so nothing confidential gets out, please let know what would be helpful. Thanks - smed -------------- next part -------------- An HTML attachment was scrubbed... URL: From jdeltoro1973 at gmail.com Thu Feb 10 01:18:44 2011 From: jdeltoro1973 at gmail.com (jdeltoro1973 at gmail.com) Date: Thu, 10 Feb 2011 00:18:44 +0000 Subject: [Tutor] PMW combobox won't display properly using X Message-ID: <4d54650f.813ee30a.3918.033c@mx.google.com> I've written a Python gui using Python Mega Widgets (PMW) that works beautifully when run natively on Windows or Linux. However, when I run the app on a Linux box and try to display it back to my Windows box using an X server (like freeXer or XMing), the combobox widget's drop-down menu is squashed all to the left, leaving just a small vertical bar which otherwise should be a wide drop-down menu. Can't scroll it or select anything in it -- it's not wide enough to see anything in it. I've tried this on several machines, all producing the same result. Does anyone know why this should happen and what might be the solution? -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Feb 10 23:52:44 2011 From: davea at ieee.org (Dave Angel) Date: Thu, 10 Feb 2011 17:52:44 -0500 Subject: [Tutor] process and modify a list of strings, in place In-Reply-To: References: Message-ID: <4D546C3C.8090908@ieee.org> On 01/-10/-28163 02:59 PM, John Martinetti wrote: > Hello - > Welcome, > > > # - create a record from all the fields > linedata = (vendornum, vendorname, ordernum, ordersuffix, orderdate, > buyer, partnum, qty, comment) > # - append the record to the list of records representing the CQ report > openPOs.append(linedata) > (snip) > > The part I'm having a problem with is once I've detected that a record has a > blank buyerID field, I can't seem to figure out how to change it, in place. > I've tried finding the index of the openPOs using this: > openPOs.index(line) > and then trying to change the item like this: > openPOs[openPOs.index(line),5] = "NOBUYER" > but I'm getting a strange error: "TypeError: 'tuple' object does not > support item assignment" > > You assign a tuple to linedata with the (vendornum, vendorname, ...) syntax. Change those to square brackets and it'll be a list, which is modifiable. There are other ways to simplify your code, but the most relevant might be to modify line[5] directly: if line[5] == " " : print "The field is blank!!!" line[5] = "NOBUYER" So first change it so that individual "line"s are lists instead of tuples. Then change the list item directly, without resorting to searching with index(). Another thing I note: You're counting on the file ending with a blank line. If you're sure that'll always be the case, fine. But if you really just want to read the whole file, replace the while True loop with something like: for record in txtreport: and if you need to ignore blank lines, use if record="" : continue -- -- davea at ieee.org From steve at pearwood.info Fri Feb 11 01:31:05 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 11 Feb 2011 11:31:05 +1100 Subject: [Tutor] process and modify a list of strings, in place In-Reply-To: References: Message-ID: <4D548349.1020306@pearwood.info> John Martinetti wrote: > Hello - > > I'm a novice programmer, not even amateur level and I need some help with > developing an algorithm to process a list of strings. > I hope this list is tolerant of n00bs, if not, please let me know and I'll > take this elsewhere. Hi John! This list is specifically for n00bs, so don't be shy. > #! /usr/bin/python > import sys, re > txtreport=open("open_pos.txt",'r') > > openPOs=[] > > while 1: > > record = txtreport.readline() # - reads in a line of data from the report > file > > vendornum = record[:6] # - breaks out each column of the report > into fields [snip slicing and dicing of the line] > # - create a record from all the fields > linedata = (vendornum, vendorname, ordernum, ordersuffix, orderdate, > buyer, partnum, qty, comment) > # - append the record to the list of records representing the CQ report > openPOs.append(linedata) > > # if not the end of the file, do it again > if not record: > break The first thing that comes to mind is that you can simplify the line processing by using a for loop instead of an infinite while loop: for line in txtreport: # walks the txtreport file, yielding each line in turn # and stopping at the end of the file vendornum = line[:6] # etc. record = (vendornum, vendorname, ordernum, ordersuffix, orderdate, buyer, partnum, qty, comment) openPOs.append(record) Notice I've swapped the names around -- what you called "record" I'm calling "line", and what you called "linedata" I'm calling a record. > The part I'm having a problem with is once I've detected that a record has a > blank buyerID field, I can't seem to figure out how to change it, in place. > I've tried finding the index of the openPOs using this: > openPOs.index(line) > and then trying to change the item like this: > openPOs[openPOs.index(line),5] = "NOBUYER" > but I'm getting a strange error: "TypeError: 'tuple' object does not > support item assignment" Correct. Out of the box, Python supports two main built-in sequence types, the tuple and the list. A tuple is designed for fixed-size records, and is designed to be immutable -- once created, you can't modify it. Instead of writing to a tuple in place, you would create a new tuple and replace it: for i in range(len(openPOs)): # i = 0, 1, 2, ... N record = openPOs[i] if record[5] == ' ': record = record[:5] + ('NOBUYER',) + record[6:] openPOs[i] = record The only part that's a bit tricky is that you need a one-item tuple for the NOBUYER element. To do that, you need to know a trick for creating a one-element tuple: take note of the comma inside the brackets. The alternative is to use a list instead of a tuple. Lists are designed for variable length data structures, and so lists can shrink and grow as needed, and elements can be changed in place. To use a list, change the line in the earlier for-loop to use square brackets instead of round: record = [vendornum, vendorname, ordernum, ordersuffix, orderdate, buyer, partnum, qty, comment] and then replace NOBUYER fields in place: for i in range(len(openPOs)): record = openPOs[i] if record[5] == ' ': record[5] = 'NOBUYER' One final improvement... whether you use a list or a tuple, the code that checks for blank buyers can be simplified. Both versions start off with the same two lines of boilerplate code: for i in range(len(openPOs)): record = openPOs[i] # ... We can simplify this to a single line that gets the record number i and the record itself together: for i,record in enumerate(openPOs): # ... Hope this helps. -- Steven From wallenpb at gmail.com Fri Feb 11 06:02:22 2011 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 10 Feb 2011 23:02:22 -0600 Subject: [Tutor] python packaging systems In-Reply-To: <137651.6275.qm@web86708.mail.ird.yahoo.com> References: <137651.6275.qm@web86708.mail.ird.yahoo.com> Message-ID: My main aim in packaging is simplicity of distribution to many workstations at work. Hiding the source is not an issue. I have successfully used cx_freeze. I did find that in some cases I have had to manually copy some files from my Python system, usually a 3rd party import, into the distribution folder cx_freeze creates. The error messages produced from the code when run with missing files are mostly sufficient to work out what files are missing. Good information everyone. Thanks very much. --Bill On Thu, Feb 10, 2011 at 12:21, ALAN GAULD wrote: > Yes, but a good installer will install Python (if needed) > and then your app in one seamless operation from the > users point of view. Then create the launch shortcut > in the appropriate start menu. > > So the user only needs to click the launch icon to > start the app, the fact that it's a Python scri[pt v a VB > program versus a C++ native binary should be irrelevant > > to them. > > > Alan Gauld > Author of the Learn To Program website > http://www.alan-g.me.uk/ > > > > > ----- Original Message ---- > > From: Brett Ritter > > To: Alan Gauld > > Cc: tutor at python.org > > Sent: Thursday, 10 February, 2011 17:26:37 > > Subject: Re: [Tutor] python packaging systems > > > > On Thu, Feb 10, 2011 at 11:14 AM, Alan Gauld > >wrote: > > > Personally I don't like them and prefer to install a version of Python > > > and then install my modules separately. > > > > > > If you want to hide your code(a little bit) you can ship only the pyc > > ... > > > > Don't forget that the motivation need not be obfuscation. I myself > > like to package standalone programs for non-techie friends and family > > to use. For them, "Run this" is a good first instruction versus > > "Install Python..." (regardless of how much their lives might be > > improved by the latter :) ) > > > > -- > > Brett Ritter / SwiftOne > > swiftone at swiftone.org > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Fri Feb 11 08:51:46 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 11 Feb 2011 08:51:46 +0100 Subject: [Tutor] Accessing query results html frame In-Reply-To: <4D542AA0.5080801@free.fr> References: <4D542AA0.5080801@free.fr> Message-ID: <4D54EA92.4030800@free.fr> Hello, In fact as found in the net: "The concept of browser frames is completely outside the scope of HTTP. However, browser frames are defined in HTML, and so is the target property on form elements: <form action="/somescript?x=y" method="POST" target="_top"> This will make the form submit to the _top frame, which means "use the full browser window" " That means that my post form:
has a target property to make the submit to the 'rightframe'. Any ideas how I can modified the code (I think the request data or whatever) below to access without knowing the temporary html file name generically. Regards Karim On 02/10/2011 07:12 PM, Karim wrote: > > Hello All, > > I get from Steven an very useful link (void space) for http > authentication. I added some codes to be > able to POST FORM a query as I do it by clicking a query button to get > a list of bug Id on a server. > The problem is I get a html page which refers 2 frames. And I am > interesting in one particular frame > namely for example, > http://{server}:{port}/wt/tmp/results:karim.liateni.31_3917.html'.format(server=server, > port=port). > But this pages is created every times in a tmp directory each time > with a different name. > > 1) How can I get the name of this page because with python the page > resulting of my query is not mentionned (hidden like)? > Interactively there are 3 frames but only this one is of interest for > me. But no name of this page is visible in the main html page. > Is there a method to get all the nested frames locations? > > 2) I can see this page interactively when I click on a submit query > button. Do I need to add 'ACTION': "Query" in the query dictionnary to simulate a click for submission > (type="submit" button) ? > > 3) Interactively I see that cgi arg NextForm is empty so I let it like > that in my query and LastForm was set to "SavedQuery". I put the > same value in my python code. Is this ok? > > import urllib > import urllib2 > > server='dummy.com' > port='8081' > > username = 'karim.liateni' > password = 'dummy_pass' > > theurl = 'http://{server}:{port}/ddts/ddts_main'.format(server=server, > port=port) > #theurl = > 'http://{server}:{port}:8081/wt/tmp/results:karim.liateni.31_3917.html'.format(server=server, > port=port) > > #MEMO: > # ENCTYPE="application/x-www-form-urlencoded" TARGET="rightframe"> > > data = { > 'NextForm': "", > 'LastForm': "SavedQuery", > 'prompted': "yes", > 'class': "Development", > 'personalQuery': "DKPV", > 'REMOTE_USER': username, > 'QS': " -p DKPVALIDATION_PLUGIN \(Class 'isequal' > "Development" \)", > 'use_field_defs':"false", > 'QueryName': "DKPV", > 'QueryType': "personal", > 'ACTION': "Query" > } > > query = urllib.urlencode(data) > request = urllib2.Request(theurl, query) > > passman = urllib2.HTTPPasswordMgrWithDefaultRealm() > passman.add_password(None, theurl, username, password) > authhandler = urllib2.HTTPBasicAuthHandler(passman) > > opener = urllib2.build_opener(authhandler) > urllib2.install_opener(opener) > > pagehandle = urllib2.urlopen(request) > print(pagehandle.read()) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From smed at missinglynx.net Fri Feb 11 18:25:38 2011 From: smed at missinglynx.net (John Martinetti) Date: Fri, 11 Feb 2011 12:25:38 -0500 Subject: [Tutor] process and modify a list of strings, in place In-Reply-To: <4D546C3C.8090908@ieee.org> References: <4D546C3C.8090908@ieee.org> Message-ID: Dave - Thanks so much for your feedback. You pointed out the biggest error that I made, I was unable to see the mistake myself, but yes...I stored the "record" in the list "openPOs" as a tuple. Doh! That's not what I meant to do. I most certainly meant to make that a list, because one of the design specs from the beginning on this project would be that I am going to need to modify all of the contents of the list "openPOs" Thank you very much for pointing that out to me, I'm going to correct that first thing. Also - I appreciate your suggestions for modifying the buyerID field in place, that is the most desired result for me. I got all tangled up around the axle trying to modify it indirectly...that's what happens when you stare at the terminal too long, I'm sure you've been there. Again - Thanks a bunch, I'm going to modify my code and I'll get back to the list if I have any other issues that I need help with. Lastly - this list is great...I think I'm going to learn a lot here. Thanks. On Thu, Feb 10, 2011 at 5:52 PM, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, John Martinetti wrote: > >> Hello - >> >> Welcome, > > >> >> >> # - create a record from all the fields >> linedata = (vendornum, vendorname, ordernum, ordersuffix, orderdate, >> buyer, partnum, qty, comment) >> # - append the record to the list of records representing the CQ report >> openPOs.append(linedata) >> >> (snip) > > >> The part I'm having a problem with is once I've detected that a record has >> a >> blank buyerID field, I can't seem to figure out how to change it, in >> place. >> I've tried finding the index of the openPOs using this: >> openPOs.index(line) >> and then trying to change the item like this: >> openPOs[openPOs.index(line),5] = "NOBUYER" >> but I'm getting a strange error: "TypeError: 'tuple' object does not >> support item assignment" >> >> >> > You assign a tuple to linedata with the (vendornum, vendorname, ...) > syntax. Change those to square brackets and it'll be a list, which is > modifiable. > > There are other ways to simplify your code, but the most relevant might be > to modify line[5] directly: > if line[5] == " " : > print "The field is blank!!!" > line[5] = "NOBUYER" > > So first change it so that individual "line"s are lists instead of tuples. > Then change the list item directly, without resorting to searching with > index(). > > Another thing I note: You're counting on the file ending with a blank > line. If you're sure that'll always be the case, fine. But if you really > just want to read the whole file, replace the while True loop with something > like: > > for record in txtreport: > > and if you need to ignore blank lines, use > if record="" : continue > > -- > -- > davea at ieee.org > -------------- next part -------------- An HTML attachment was scrubbed... URL: From smed at missinglynx.net Fri Feb 11 18:31:16 2011 From: smed at missinglynx.net (John Martinetti) Date: Fri, 11 Feb 2011 12:31:16 -0500 Subject: [Tutor] process and modify a list of strings, in place In-Reply-To: <4D548349.1020306@pearwood.info> References: <4D548349.1020306@pearwood.info> Message-ID: Steve - Dave pointed out earlier in the thread the primary mistake I made...which was that when I assembled the record to be store in the list "openPOs", I did so and made it a tuple, instead of a list. That was a mistake, I meant to make that a list and after reviewing my code, over and over again, I missed the fact that I made it a tuple. I like the idea of using a for-loop, I'm going to incorporate that...thanks for the suggestions. In addition to that, I like your suggestion for detecting the blank buyerID field, I plan on incorporating that as well. It's great to have a list like this to get another set of eyes reviewing the code, very very helpful. Thanks again Steve for your response, I really appreciate it. I'll report back once I get the changes implemented. On Thu, Feb 10, 2011 at 7:31 PM, Steven D'Aprano wrote: > John Martinetti wrote: > >> Hello - >> >> I'm a novice programmer, not even amateur level and I need some help with >> developing an algorithm to process a list of strings. >> I hope this list is tolerant of n00bs, if not, please let me know and I'll >> take this elsewhere. >> > > Hi John! This list is specifically for n00bs, so don't be shy. > > > > #! /usr/bin/python >> import sys, re >> txtreport=open("open_pos.txt",'r') >> >> openPOs=[] >> >> while 1: >> >> record = txtreport.readline() # - reads in a line of data from the >> report >> file >> >> vendornum = record[:6] # - breaks out each column of the report >> into fields >> > > [snip slicing and dicing of the line] > > > # - create a record from all the fields >> linedata = (vendornum, vendorname, ordernum, ordersuffix, orderdate, >> buyer, partnum, qty, comment) >> # - append the record to the list of records representing the CQ report >> openPOs.append(linedata) >> >> # if not the end of the file, do it again >> if not record: >> break >> > > The first thing that comes to mind is that you can simplify the line > processing by using a for loop instead of an infinite while loop: > > for line in txtreport: > # walks the txtreport file, yielding each line in turn > # and stopping at the end of the file > vendornum = line[:6] > # etc. > record = (vendornum, vendorname, ordernum, ordersuffix, > > orderdate, buyer, partnum, qty, comment) > openPOs.append(record) > > Notice I've swapped the names around -- what you called "record" I'm > calling "line", and what you called "linedata" I'm calling a record. > > > > The part I'm having a problem with is once I've detected that a record has >> a >> blank buyerID field, I can't seem to figure out how to change it, in >> place. >> I've tried finding the index of the openPOs using this: >> openPOs.index(line) >> and then trying to change the item like this: >> openPOs[openPOs.index(line),5] = "NOBUYER" >> but I'm getting a strange error: "TypeError: 'tuple' object does not >> support item assignment" >> > > Correct. Out of the box, Python supports two main built-in sequence types, > the tuple and the list. A tuple is designed for fixed-size records, and is > designed to be immutable -- once created, you can't modify it. > > Instead of writing to a tuple in place, you would create a new tuple and > replace it: > > for i in range(len(openPOs)): # i = 0, 1, 2, ... N > record = openPOs[i] > if record[5] == ' ': > record = record[:5] + ('NOBUYER',) + record[6:] > openPOs[i] = record > > > The only part that's a bit tricky is that you need a one-item tuple for the > NOBUYER element. To do that, you need to know a trick for creating a > one-element tuple: take note of the comma inside the brackets. > > The alternative is to use a list instead of a tuple. Lists are designed for > variable length data structures, and so lists can shrink and grow as needed, > and elements can be changed in place. To use a list, change the line in the > earlier for-loop to use square brackets instead of round: > > record = [vendornum, vendorname, ordernum, ordersuffix, > orderdate, buyer, partnum, qty, comment] > > > and then replace NOBUYER fields in place: > > for i in range(len(openPOs)): > record = openPOs[i] > if record[5] == ' ': > record[5] = 'NOBUYER' > > > One final improvement... whether you use a list or a tuple, the code that > checks for blank buyers can be simplified. Both versions start off with the > same two lines of boilerplate code: > > for i in range(len(openPOs)): > record = openPOs[i] > # ... > > We can simplify this to a single line that gets the record number i and the > record itself together: > > for i,record in enumerate(openPOs): > # ... > > > > Hope this helps. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Sat Feb 12 05:49:53 2011 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 11 Feb 2011 20:49:53 -0800 Subject: [Tutor] process and modify a list of strings, in place References: Message-ID: "John Martinetti" wrote in message news:AANLkTi=8KvksqzpUJSQwFFJ8YaRjCWHuHaWTzkzFVNV6 at mail.gmail.com... > Hello - > > I'm a novice programmer, not even amateur level and I need some help with > developing an algorithm to process a list of strings. > I hope this list is tolerant of n00bs, if not, please let me know and I'll > take this elsewhere. > > > Some background. > > I cut up a text based report from a reporting application into fields by > slicing the lines up using fixed column widths to delimit the fields. > This > was necessary to ensure that a couple of the fields that had free-form > "comments" with variable spacing. If there were well-defined field > delimiters I could have used awk or some other text processing tool. > Python > worked very well for cutting up the lines from the report into fields and > let me store each "record" into a list of strings. So - I have a list of > openPOs which is a list of strings. > I do this like this: > > ############################################################################################################# > #! /usr/bin/python > import sys, re > txtreport=open("open_pos.txt",'r') > > openPOs=[] > > while 1: > > record = txtreport.readline() # - reads in a line of data from the > report > file > > vendornum = record[:6] # - breaks out each column of the report > into fields > vendorname = record[7:40] > ordernum = record[41:47] > ordersuffix = record[48:59] > orderdate = record[60:70] > buyer = record[71:77] > partnum = record[78:100] > qty = record[101:108] > comment = record[109:135] > > # - create a record from all the fields > linedata = (vendornum, vendorname, ordernum, ordersuffix, orderdate, > buyer, partnum, qty, comment) > # - append the record to the list of records representing the CQ report > openPOs.append(linedata) > > # if not the end of the file, do it again > if not record: > break I noticed when splitting up your record line there is a character skipped between each field. A delimiter perhaps? Then you may be interested in the csv module. Assuming the delimiter is '|', the following code will produce the same result in openPOs: import csv with open('open_pos.txt','rb') as f: reader = csv.reader(f,delimiter='|') openPOs = list(reader) print openPOs Note you may have to specify some more parameters to csv.reader depending on your file "dialect". See the csv.Dialect class for details. -Mark From kb1pkl at aim.com Sat Feb 12 07:07:32 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 12 Feb 2011 01:07:32 -0500 Subject: [Tutor] Python + Sound Message-ID: <4D5623A4.1050308@aim.com> Hello Tutors, I'm working on a small script that compresses a file, sends it through the telephone, and then receives and decompresses the file on the other end. The compression is the easy part. The transmission is the hard part. If anyone has worked with sound before, what do you recommend? I've tried out audiere (didn't really work out) and alsaaudio (not quite sure that it was working like I wanted to, probably an ID-10t error). I'm doing this for a number of reasons including boredom and something new that I've never seen before (too young to remember archaic things like 'dial-up'). I don't really want to use the wave module because it looks like too much work. I like the alsaaudio interface of p.write(data), but I didn't really know what data was supposed to be (probably should read up on PCM devices?) So, what should I use? I can use different things different ways too, I don't need one module for sending and one for recording. Thank you, ~Corey From smokefloat at gmail.com Sat Feb 12 07:10:47 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Feb 2011 01:10:47 -0500 Subject: [Tutor] Python + Sound In-Reply-To: <4D5623A4.1050308@aim.com> References: <4D5623A4.1050308@aim.com> Message-ID: for some reason, if you're on linux, I wanna say use python's subprocess, and man pppd. also look into proc and a thread in the archives I did a while back. From kb1pkl at aim.com Sat Feb 12 07:20:15 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 12 Feb 2011 01:20:15 -0500 Subject: [Tutor] Python + Sound In-Reply-To: References: <4D5623A4.1050308@aim.com> Message-ID: <4D56269F.1020206@aim.com> On 02/12/2011 01:10 AM, David Hutto wrote: > for some reason, if you're on linux, I wanna say use python's > subprocess, and man pppd. also look into proc and a thread in the > archives I did a while back. The point is to specifically transmit the data as sound, and then turn the sound back into the gzipped file. If I were doing this for anything other than my own entertainment and education, I'd do it some way that made sense :-) From smokefloat at gmail.com Sat Feb 12 07:23:18 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Feb 2011 01:23:18 -0500 Subject: [Tutor] Python + Sound In-Reply-To: <4D56269F.1020206@aim.com> References: <4D5623A4.1050308@aim.com> <4D56269F.1020206@aim.com> Message-ID: On Sat, Feb 12, 2011 at 1:20 AM, Corey Richardson wrote: > On 02/12/2011 01:10 AM, David Hutto wrote: >> for some reason, if you're on linux, I wanna say use python's >> subprocess, and man pppd. also look into proc and a thread in the >> archives I did a while back. > > The point is to specifically transmit the data as sound, and what is sound, electromagnetically transmitted, then turned into ones and zeroes. THis is where I started with my research, even though I remembered a good bit from earlier in my life. http://www.google.com/search?client=ubuntu&channel=fs&q=the+modern+telephone&ie=utf-8&oe=utf-8 and then turn > the sound back into the gzipped file. If I were doing this for anything > other than my own entertainment and education, I'd do it some way that > made sense :-) > -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From smokefloat at gmail.com Sat Feb 12 07:24:57 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Feb 2011 01:24:57 -0500 Subject: [Tutor] Python + Sound In-Reply-To: <4D56269F.1020206@aim.com> References: <4D5623A4.1050308@aim.com> <4D56269F.1020206@aim.com> Message-ID: > The point is to specifically transmit the data as sound, and then turn > the sound back into the gzipped file. If I were doing this for anything > other than my own entertainment and education, I'd do it some way that > made sense :-) > Do you mean just a wav file, and then send it to someone? From smokefloat at gmail.com Sat Feb 12 07:26:08 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Feb 2011 01:26:08 -0500 Subject: [Tutor] Python + Sound In-Reply-To: References: <4D5623A4.1050308@aim.com> <4D56269F.1020206@aim.com> Message-ID: On Sat, Feb 12, 2011 at 1:24 AM, David Hutto wrote: >> The point is to specifically transmit the data as sound, and then turn >> the sound back into the gzipped file. If I were doing this for anything >> other than my own entertainment and education, I'd do it some way that >> made sense :-) >> > > Do you mean just a wav file, and then send it to someone? You want to have a sound file, gzip it, and then gunzip it on the other end? From smokefloat at gmail.com Sat Feb 12 07:36:39 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Feb 2011 01:36:39 -0500 Subject: [Tutor] Python + Sound In-Reply-To: <4D562990.6040709@aim.com> References: <4D5623A4.1050308@aim.com> <4D56269F.1020206@aim.com> <4D562990.6040709@aim.com> Message-ID: On Sat, Feb 12, 2011 at 1:32 AM, Corey Richardson wrote: > On 02/12/2011 01:26 AM, David Hutto wrote: >> On Sat, Feb 12, 2011 at 1:24 AM, David Hutto wrote: >>>> The point is to specifically transmit the data as sound, and then turn >>>> the sound back into the gzipped file. If I were doing this for anything >>>> other than my own entertainment and education, I'd do it some way that >>>> made sense :-) >>>> >>> >>> Do you mean just a wav file, and then send it to someone? >> >> You want to have a sound file, gzip it, and then gunzip it on the other end? > > I have any file, gzip it, turn it to a sound file, and then gunzip it on > the other end. Using tones to specify bit patterns, I'll work that out > after I get to the point where I can output sound. > And what are you outputting sound to. I can use a library, or just subprocess and aplay from alsa on linux. This is just command line, until I understand ctypes more. You can also record this way, but pause would would require appending one to the other, which would require something else. But you could go commandline with subprocess or move and understand c and ctypes. -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From kb1pkl at aim.com Sat Feb 12 07:32:48 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 12 Feb 2011 01:32:48 -0500 Subject: [Tutor] Python + Sound In-Reply-To: References: <4D5623A4.1050308@aim.com> <4D56269F.1020206@aim.com> Message-ID: <4D562990.6040709@aim.com> On 02/12/2011 01:26 AM, David Hutto wrote: > On Sat, Feb 12, 2011 at 1:24 AM, David Hutto wrote: >>> The point is to specifically transmit the data as sound, and then turn >>> the sound back into the gzipped file. If I were doing this for anything >>> other than my own entertainment and education, I'd do it some way that >>> made sense :-) >>> >> >> Do you mean just a wav file, and then send it to someone? > > You want to have a sound file, gzip it, and then gunzip it on the other end? I have any file, gzip it, turn it to a sound file, and then gunzip it on the other end. Using tones to specify bit patterns, I'll work that out after I get to the point where I can output sound. From smokefloat at gmail.com Sat Feb 12 07:40:34 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Feb 2011 01:40:34 -0500 Subject: [Tutor] Python + Sound In-Reply-To: References: <4D5623A4.1050308@aim.com> <4D56269F.1020206@aim.com> <4D562990.6040709@aim.com> Message-ID: >> I have any file, gzip it, turn it to a sound file, you have a sound file, then gzip it. and then gunzip it on >> the other end. which requires an unzip utility on the other end, and then an app to play the sound files format. Using tones to specify bit patterns, I'll work that out >> after I get to the point where I can output sound. From smokefloat at gmail.com Sat Feb 12 07:50:14 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Feb 2011 01:50:14 -0500 Subject: [Tutor] Python + Sound In-Reply-To: References: <4D5623A4.1050308@aim.com> <4D56269F.1020206@aim.com> <4D562990.6040709@aim.com> Message-ID: This is how i zip the file: david at david-HP-Pavilion-dv9700-Notebook-PC:~$ sudo gzip /usr/lib/openoffice/basis-link/share/gallery/sounds/apert.wav > /home/david/examp.gz[sudo] password for david: david at david-HP-Pavilion-dv9700-Notebook-PC:~$ Then they: david at david-HP-Pavilion-dv9700-Notebook-PC:~$ gunzip /home/david/examp.gz then they: david at david-HP-Pavilion-dv9700-Notebook-PC:~$ play soundfilethatwasgunzipped.wav -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From smokefloat at gmail.com Sat Feb 12 08:21:18 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Feb 2011 02:21:18 -0500 Subject: [Tutor] Python + Sound In-Reply-To: References: <4D5623A4.1050308@aim.com> <4D56269F.1020206@aim.com> <4D562990.6040709@aim.com> Message-ID: and a simple makefile, as I've recently understood, or a file that executes command lines, can do that. From smokefloat at gmail.com Sat Feb 12 08:24:31 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Feb 2011 02:24:31 -0500 Subject: [Tutor] Python + Sound In-Reply-To: References: <4D5623A4.1050308@aim.com> <4D56269F.1020206@aim.com> <4D562990.6040709@aim.com> Message-ID: There doesn't even have to be a source file, or .o and.h and.c, it just executes the command lines in it. So just a makefile in a directory and typing make at the command line executes those commands. So you can do a whole reorientation of a system with just command line s in a makefile. From steve at pearwood.info Sat Feb 12 08:27:06 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Feb 2011 18:27:06 +1100 Subject: [Tutor] Python + Sound In-Reply-To: <4D5623A4.1050308@aim.com> References: <4D5623A4.1050308@aim.com> Message-ID: <4D56364A.2090406@pearwood.info> Corey Richardson wrote: > Hello Tutors, > > I'm working on a small script that compresses a file, sends it through > the telephone, and then receives and decompresses the file on the other > end. The compression is the easy part. The transmission is the hard > part. If anyone has worked with sound before, what do you recommend? Sorry, do I understand you correctly? You want to compress an arbitrary file, convert that compressed data into some sort of sound, play the sound through the telephone, record it at the other end, decompress it, and get the original file back again? This is certainly possible -- it's how modems work. But it's a lot of work, and it's reinventing the wheel in the biggest way. Good luck! Normally, people transmit files using the highest level protocol they can: application sends data via HTTP (etc) ... which is built on top of TCP ... which is built on top of IP ... which is built on top of the link layer ... which is built on top of the physical hardware layer If I've understood you correctly, you want to write your own equivalent of TCP/IP, using only some sort of library link layer to deal with the hardware. That is, you don't want to care about voltages, but you do want to send data to the speaker and receive data from microphones. Yes? I suggest you read up on how much work is needed to get reliable data transport: http://en.wikipedia.org/wiki/TCP/IP_model http://www.howstuffworks.com/modem.htm http://en.wikipedia.org/wiki/Modem and this may entertain, and help: http://www.joelonsoftware.com/articles/LeakyAbstractions.html Of course this can be done -- otherwise we wouldn't have the Internet! But my guess is that doing this in pure Python will be so slow it will be almost faster for you to copy the file onto a USB stick and hand-deliver it to the other end. But if you insist... * Your compressed file is a bunch of bytes. You need to come up with a scheme for encoding that to sound. This needs to be reversible and designed to work on low-fidelity systems (phone networks). The obvious way is to have one tone represent a one-bit, and another *very different* tone represent a two-bit. See also "frequency modulation" and "amplitude modulation". * Because of noise on the line, you need a scheme for error correction. Google for "Error correcting codes" for more information. * The sender and receiver need a way to notify each other that they are ready to start transmitting data. This is called a handshake. Otherwise, you risk losing data from the ends of the transmission. You described this as "a small script" -- it might be so far, but by the time you finish it will be huge. > I don't really want to use the wave module because it looks like too > much work. Pardon me while I chortle :) -- Steven From smokefloat at gmail.com Sat Feb 12 08:31:43 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Feb 2011 02:31:43 -0500 Subject: [Tutor] Python + Sound In-Reply-To: <4D56364A.2090406@pearwood.info> References: <4D5623A4.1050308@aim.com> <4D56364A.2090406@pearwood.info> Message-ID: > Pardon me while I chortle :) > > Like I said, start here: http://www.google.com/search?client=ubuntu&channel=fs&q=the+modern+telephone&ie=utf-8&oe=utf-8 Steven forgot a little in his elaboration,that he isn't an expert in this: -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From kb1pkl at aim.com Sat Feb 12 08:56:43 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 12 Feb 2011 02:56:43 -0500 Subject: [Tutor] Python + Sound In-Reply-To: <4D56364A.2090406@pearwood.info> References: <4D5623A4.1050308@aim.com> <4D56364A.2090406@pearwood.info> Message-ID: <4D563D3B.6040209@aim.com> On 02/12/2011 02:27 AM, Steven D'Aprano wrote: > Corey Richardson wrote: >> Hello Tutors, >> >> I'm working on a small script that compresses a file, sends it through >> the telephone, and then receives and decompresses the file on the other >> end. The compression is the easy part. The transmission is the hard >> part. If anyone has worked with sound before, what do you recommend? > > [snip of excellent help and advice] > > http://en.wikipedia.org/wiki/TCP/IP_model > http://www.howstuffworks.com/modem.htm > http://en.wikipedia.org/wiki/Modem > > and this may entertain, and help: > http://www.joelonsoftware.com/articles/LeakyAbstractions.html > Always been a fan of Joel's articles. > > Of course this can be done -- otherwise we wouldn't have the Internet! > But my guess is that doing this in pure Python will be so slow it will > be almost faster for you to copy the file onto a USB stick and > hand-deliver it to the other end. But if you insist... Well, I'm still on my way to learning other languages, Java (which I hate) and soon I begin my voyage onwards into C. I figure once I get something working in a tool I know how to use well, I'll be able to get it done in a tool that I /don't/ know as well. > > * Your compressed file is a bunch of bytes. You need to come up with > a scheme for encoding that to sound. This needs to be reversible > and designed to work on low-fidelity systems (phone networks). > The obvious way is to have one tone represent a one-bit, and another > *very different* tone represent a two-bit. See also "frequency > modulation" and "amplitude modulation". > > * Because of noise on the line, you need a scheme for error correction. > Google for "Error correcting codes" for more information. > > * The sender and receiver need a way to notify each other that they > are ready to start transmitting data. This is called a handshake. > Otherwise, you risk losing data from the ends of the transmission. > > You described this as "a small script" -- it might be so far, but by the > time you finish it will be huge. > >> I don't really want to use the wave module because it looks like too >> much work. > > Pardon me while I chortle :) Merely one aspect of a larger whole that I expected to be much more complex - I didn't want to spend all my time working on sound encoding. I think I have much more realistic view on it now. Thank you _so much_ for the help. I truly appreciate it, you've given me much more perspective, and I'll need to consider carefully my next steps. Probably quite a bit of time at the drawing board! From alan.gauld at btinternet.com Sat Feb 12 10:43:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Feb 2011 09:43:28 -0000 Subject: [Tutor] Python + Sound References: <4D5623A4.1050308@aim.com><4D56269F.1020206@aim.com> Message-ID: "David Hutto" wrote > and what is sound, electromagnetically transmitted, then turned into > ones and zeroes. Just to be picky sound is mechanical waves not electromagnetic. The ear is primarily a mechanical device. Audio is the more general term to describe signalling which represents sound. And audio can be transmitted as electromagnetic waves. The other big thing about audio is that it is analog not digital. So to represent a binary digital signal using audio you need to define one audio signal frequency for 1 and another for 0. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Feb 12 10:56:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Feb 2011 09:56:49 -0000 Subject: [Tutor] Python + Sound References: <4D5623A4.1050308@aim.com> <4D56364A.2090406@pearwood.info> Message-ID: "Steven D'Aprano" wrote > I suggest you read up on how much work is needed to get reliable > data transport: > > http://en.wikipedia.org/wiki/TCP/IP_model > http://www.howstuffworks.com/modem.htm > http://en.wikipedia.org/wiki/Modem He probably doesn't need all of that since its only for education but he will need session setup/tear down as a minimum. > But my guess is that doing this in pure Python will be so slow it > will Python won't be the limit. The fastest you can swend pure digital (without multiplexing) using audio is about 600 bits per second. Thats less than 80 bytes per second. Python can handle that easily. > be almost faster for you to copy the file onto a USB stick and > hand-deliver it to the other end. But if you insist... Ah, the days of sneakerNet I remember it well :-) > The obvious way is to have one tone represent a one-bit, and > another > *very different* tone represent a two-bit. See also "frequency > modulation" and "amplitude modulation". The other ways are to use more tones and encode groupss of digits. Thats how faster modems work. And you can mess with the phasing to send multiple groups simulateouslty. But for various technical reasons the upper limit is around 64kb/s. And dont forget the phone system can only transmit frequencies between 300 and 3400Hz reliably. (100-4000Hz less reliably - not all carriers support it) > * Because of noise on the line, you need a scheme for error > correction. > Google for "Error correcting codes" for more information. If you choose a realistic speed and stick with pure binary - say 100 bps error correction shouldn't be a big issue for short messages - say less than a kilobyte. > * The sender and receiver need a way to notify each other that they > are ready to start transmitting data. This is called a handshake. > Otherwise, you risk losing data from the ends of the transmission. Yes, session set up and tear down is unavoidable. The equivalent of saying "over", "roger" and "over and out" in radio comms... And the other big issue will be how to make the call in the first place. I assume you plan on doing that bit manually? Otherwise you are into a whole new can of worms!! > You described this as "a small script" -- it might be so far, but by > the time you finish it will be huge. It will be pretty big I suspect. >> I don't really want to use the wave module because it looks like >> too >> much work. > > Pardon me while I chortle :) Yep, me too. You need all the help you can get! The work without it will be much bigger! It really will be much easier if you use a modem, at least for the first attempt. HTH, Alan G. From smed at missinglynx.net Sat Feb 12 15:43:46 2011 From: smed at missinglynx.net (John Martinetti) Date: Sat, 12 Feb 2011 09:43:46 -0500 Subject: [Tutor] process and modify a list of strings, in place In-Reply-To: References: Message-ID: Hi Mark - The characters skipped were unintentional, I sliced up the report based on starting/ending column numbers that I somewhat guessed and massaged by merely comparing the output of the openPOs list to the actual report. There might even been some room to massage those boundaries further to be quite honest. The report writer we use is called Cyberquery and it works on CISAM database flat-files (as well as other databases). It's awful with this pseudo/SQL reporting language that just trips me up constantly when compared to any of the SQL languages. And the fact that we run our business on a non-relational database is archaic, I could drone on & on about that but it's just makes my blood-pressure rise. Anyway - the short story is that I dont have many choices in output formats from the report-writer. I can export to normal text files, Excel spreadsheets, DIF format and HTML. Those are the options. I can't believe there's no CSV format, that would make my life a lot easier, but there isn't. I wish there was. I've even thought that it might be worth my while to try exporting the HTML and parsing it out from there....could be more consistent, but it would require experimentation. Anywho - thanks for the suggestion about the CSV module, I can actually use that in the future too, just not for this project. Thanks a bunch for bringing that to my attention, I was not aware of that module and it may come in very useful for me. {quote} I noticed when splitting up your record line there is a character skipped between each field. A delimiter perhaps? Then you may be interested in the csv module. Assuming the delimiter is '|', the following code will produce the same result in openPOs: > > import csv > with open('open_pos.txt','rb') as f: > reader = csv.reader(f,delimiter='|') > openPOs = list(reader) > print openPOs > > Note you may have to specify some more parameters to csv.reader depending > on your file "dialect". See the csv.Dialect class for details. > > -Mark > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > {/quote} -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Sat Feb 12 16:14:21 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 12 Feb 2011 09:14:21 -0600 Subject: [Tutor] Python printing to LPT Message-ID: Is is possible to print directly to an LPT port printer from Python? --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Sat Feb 12 16:32:03 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 12 Feb 2011 10:32:03 -0500 Subject: [Tutor] Python + Sound In-Reply-To: References: <4D5623A4.1050308@aim.com> <4D56269F.1020206@aim.com> Message-ID: On Sat, Feb 12, 2011 at 4:43 AM, Alan Gauld wrote: > > "David Hutto" wrote > >> and what is sound, electromagnetically transmitted, then turned into >> ones and zeroes. > > Just to be picky sound is mechanical waves not electromagnetic. > The ear is primarily a mechanical device. I meant after your voice speaks(sound waves to em), and before it vibrates the speaker(em to sound). > > Audio is the more general term to describe signalling which > represents sound. And audio can be transmitted as electromagnetic > waves. The other big thing about audio is that it is analog not digital. > > So to represent a binary digital signal using audio you need to > define one audio signal frequency for 1 and another for 0. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From emile at fenx.com Sat Feb 12 17:27:39 2011 From: emile at fenx.com (Emile van Sebille) Date: Sat, 12 Feb 2011 08:27:39 -0800 Subject: [Tutor] process and modify a list of strings, in place In-Reply-To: References: Message-ID: On 2/12/2011 6:43 AM John Martinetti said... > dont have many choices in output formats from the report-writer. I can > export to normal text files, Excel spreadsheets, DIF format and HTML. > Those are the options. I can't believe there's no CSV format, You may want to try the excel format. Two possible outcomes may be that these are actually csv files under the covers that depend on excel's ability to recognize csv formats in files terminating with '.xls' -- another possibility is that the excel format is legitimate, and you can then parse the results more reliably with John Machin's xlrd package. See http://pypi.python.org/pypi/xlrd Emile From alan.gauld at btinternet.com Sat Feb 12 20:06:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Feb 2011 19:06:57 -0000 Subject: [Tutor] Python printing to LPT References: Message-ID: "Bill Allen" wrote > Is is possible to print directly to an LPT port printer from Python? Yes. and No. It depends on how you define "directly" and what you are trying to print and from which OS. Alan G From wallenpb at gmail.com Sat Feb 12 22:14:53 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 12 Feb 2011 15:14:53 -0600 Subject: [Tutor] Python printing to LPT In-Reply-To: References: Message-ID: Alan, Sorry for being vague. I am wanting to print from a Python app that I am writing for MS Windows XP. The desired end result is to print some plain text to a dot matrix printer that the printer can handle with its own internal fonts without need for any kind of other processing. What I envisioned was something like a write method to a file, except LPT being the file object. I was hoping to do this directly from the Python program to avoid calls to the Windows OS utilities, like a redirect to PRN, but am open to that if I must. If this was a *nix system of some sort, I would not sweat it and use the OS to handle this but I am dubious about the reliability of using the MS Windows "DOS" in a production environment. Also, to answer the "what in the world are you doing with a dot matrix printer?" question that some may be wondering. Normally, I would not even bother with an LPT dot matrix printer, but in this case the application requires that the dot matrix printer do the job of printing to an "etching tape". The dot matrix pins cut through the wax on the etching tape allowing it to be used as an acid electro-etching negative on metallic parts. I am guessing there may be a 3rd party module that allows for what I am doing, but have not yet identified it. As always, I am very open to any suggestions and appreciative of the help. --Bill On Sat, Feb 12, 2011 at 13:06, Alan Gauld wrote: > > "Bill Allen" wrote > > > Is is possible to print directly to an LPT port printer from Python? >> > > Yes. > > and No. > > It depends on how you define "directly" and what you are trying > to print and from which OS. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Feb 12 22:34:18 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 12 Feb 2011 21:34:18 +0000 (GMT) Subject: [Tutor] Python printing to LPT In-Reply-To: References: Message-ID: <118363.44435.qm@web86702.mail.ird.yahoo.com> > to print some plain text to a dot matrix printer that the printer can handle > with its own internal fonts without need for any kind of other processing. In that case you can either open LPT1 as a file and write to it or use redirection to PRN from the command line. > I am dubious about the reliability of using the MS Windows "DOS" in > a production environment. We used DOS in production environments for 10 years before Windows took over, its not a problem for this kind of thing! Caveat: I've only tried his from Windows 98 but I don't know of any reason it shouldn't work from an XP CMD prompt. If echo "hello world" > PRN: works then it should work from Python too. HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Sat Feb 12 23:58:06 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 12 Feb 2011 16:58:06 -0600 Subject: [Tutor] Python printing to LPT In-Reply-To: <118363.44435.qm@web86702.mail.ird.yahoo.com> References: <118363.44435.qm@web86702.mail.ird.yahoo.com> Message-ID: Allan, Ok, that encourages me to try it both ways and see which works out better. Thanks, --Bill On Sat, Feb 12, 2011 at 15:34, ALAN GAULD wrote: > > to print some plain text to a dot matrix printer that the printer can > handle > > with its own internal fonts without need for any kind of other > processing. > > In that case you can either open LPT1 as a file and write to it or use > redirection to PRN from the command line. > > > > I am dubious about the reliability of using the MS Windows "DOS" in > > a production environment. > > We used DOS in production environments for 10 years before Windows > took over, its not a problem for this kind of thing! > > Caveat: I've only tried his from Windows 98 but I don't know of any reason > it shouldn't work from an XP CMD prompt. If > > echo "hello world" > PRN: > > works then it should work from Python too. > > HTH, > > Alan G. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkidken at gmail.com Sun Feb 13 01:33:55 2011 From: beachkidken at gmail.com (Ken G.) Date: Sat, 12 Feb 2011 19:33:55 -0500 Subject: [Tutor] Python printing to LPT In-Reply-To: References: Message-ID: <4D5726F3.1090306@gmail.com> On 02/12/2011 10:14 AM, Bill Allen wrote: > > Is is possible to print directly to an LPT port printer from Python? > > > --Bill > I use the following format in my Ubuntu 10.04 usage. It set up a printing file. import os # declare values month = "02"; date = "11"; year = "2011" # open up file pr = os.popen("lpr", "w") #tab two times before printing string pr.write("\t\tDate of Drawing: "), # print the month on the same line and added a space pr.write(month), pr.write (" " ), # print the date on the same line and added a space pr.write(date), pr.write(" "), # print the year on the same line and added a space pr.write(year), pr.write(" "), # print up two line feeds pr.write("\n"), pr.write("\n") # close the print file pr.close() will produce the following: Date of Drawing: 02 11 2011 (start of new line here) Very time consuming and detailing but it work. Ken From wallenpb at gmail.com Sun Feb 13 03:53:34 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 12 Feb 2011 20:53:34 -0600 Subject: [Tutor] Python printing to LPT In-Reply-To: <4D5726F3.1090306@gmail.com> References: <4D5726F3.1090306@gmail.com> Message-ID: Ken, Thanks for the great info on doing this on a Linux platform. I am sure I will be trying this with Linux sometime and I'll refer back to this. --Bill On Sat, Feb 12, 2011 at 18:33, Ken G. wrote: > On 02/12/2011 10:14 AM, Bill Allen wrote: > >> >> Is is possible to print directly to an LPT port printer from Python? >> >> >> --Bill >> >> I use the following format in my Ubuntu 10.04 usage. It set up a > printing file. > > > import os > > # declare values > month = "02"; date = "11"; year = "2011" > > # open up file > pr = os.popen("lpr", "w") > > #tab two times before printing string > pr.write("\t\tDate of Drawing: "), > > # print the month on the same line and added a space > pr.write(month), pr.write (" " ), > > # print the date on the same line and added a space > pr.write(date), pr.write(" "), > > # print the year on the same line and added a space > pr.write(year), pr.write(" "), > > # print up two line feeds > pr.write("\n"), pr.write("\n") > > # close the print file > pr.close() > > will produce the following: > > Date of Drawing: 02 11 2011 > > (start of new line here) > > Very time consuming and detailing but it work. > > Ken > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sun Feb 13 04:01:17 2011 From: davea at ieee.org (Dave Angel) Date: Sat, 12 Feb 2011 22:01:17 -0500 Subject: [Tutor] Python + Sound In-Reply-To: References: <4D5623A4.1050308@aim.com> <4D56269F.1020206@aim.com> Message-ID: <4D57497D.4080105@ieee.org> On 01/-10/-28163 02:59 PM, David Hutto wrote: > On Sat, Feb 12, 2011 at 4:43 AM, Alan Gauld wrote: >> >> "David Hutto" wrote >> >>> and what is sound, electromagnetically transmitted, then turned into >>> ones and zeroes. >> >> Just to be picky sound is mechanical waves not electromagnetic. >> The ear is primarily a mechanical device. > > I meant after your voice speaks(sound waves to em), and before it > vibrates the speaker(em to sound). > >> You're skipping a few steps, but unless you're using a cordless radio microphone, there's no em between your voice and the speaker. Radio waves, as well as light, are electromagnetic. Sound is very different, and so is the electrical signal produced by a microphone. In any case, none of your responses corresponded to the OP's query. DaveA From wallenpb at gmail.com Sun Feb 13 04:08:55 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 12 Feb 2011 21:08:55 -0600 Subject: [Tutor] Python printing to LPT In-Reply-To: <118363.44435.qm@web86702.mail.ird.yahoo.com> References: <118363.44435.qm@web86702.mail.ird.yahoo.com> Message-ID: As a followup, I have done some more searching and found some terrific information on this subject of Python printing on the Windows platform. The following link shows variations using some modules from the pywin32 package. http://timgolden.me.uk/python/win32_how_do_i/print.html --Bill On Sat, Feb 12, 2011 at 15:34, ALAN GAULD wrote: > > to print some plain text to a dot matrix printer that the printer can > handle > > with its own internal fonts without need for any kind of other > processing. > > In that case you can either open LPT1 as a file and write to it or use > redirection to PRN from the command line. > > > > I am dubious about the reliability of using the MS Windows "DOS" in > > a production environment. > > We used DOS in production environments for 10 years before Windows > took over, its not a problem for this kind of thing! > > Caveat: I've only tried his from Windows 98 but I don't know of any reason > it shouldn't work from an XP CMD prompt. If > > echo "hello world" > PRN: > > works then it should work from Python too. > > HTH, > > Alan G. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkidken at gmail.com Sun Feb 13 05:26:01 2011 From: beachkidken at gmail.com (Ken G.) Date: Sat, 12 Feb 2011 23:26:01 -0500 Subject: [Tutor] Python printing to LPT In-Reply-To: References: <4D5726F3.1090306@gmail.com> Message-ID: <4D575D59.3030805@gmail.com> On 02/12/2011 09:53 PM, Bill Allen wrote: > Ken, > > Thanks for the great info on doing this on a Linux platform. I am > sure I will be trying this with Linux sometime and I'll refer back to > this. > > > --Bill > > > I discovered some more information on this at the following link: http://mail.python.org/pipermail/tutor/2010-January/073725.html Good luck. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From deshpande.jaidev at gmail.com Sun Feb 13 09:54:47 2011 From: deshpande.jaidev at gmail.com (Jaidev Deshpande) Date: Sun, 13 Feb 2011 14:24:47 +0530 Subject: [Tutor] Backpropagation Learning in Python Message-ID: Dear All Please suggest a link to tutorials for backpropagation and other neural network training algorithms through Python. Any other commentary is welcome, as I am new to both Python and Neural Networks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Sun Feb 13 15:37:03 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 13 Feb 2011 14:37:03 +0000 Subject: [Tutor] How to group data? Message-ID: hi, i'm using Python 2.5 and Win XP. i want to extract the last column of the attached text file and group 128 characters to each row. want the result to look like: Row1=XXXXX.............................1XXX (total of 128 char) Row2=11XX...............................X1XX (total of 128 char) ###code from __future__ import with_statement def main(): new_rows = {} values = [] with open('test2.txt') as f: for line in f: values.append(line.rstrip('\n')[-1]) x = [] # making a new list here, not only x += values # a new reference to the same object for count in xrange(0,len(values),128): temp_values1 = (x.pop(9))+(x.pop(8))+(x.pop(7))+(x.pop(6))+(x.pop(5))+(x.pop(4))+(x.pop(3))+(x.pop(2))+(x.pop(1))+(x.pop(0)) temp_values2 = (x.pop(19))+(x.pop(18))+(x.pop(17))+(x.pop(16))+(x.pop(15))+(x.pop(14))+(x.pop(13))+(x.pop(12))+(x.pop(11))+(x.pop(10)) temp_values3 = (x.pop(29))+(x.pop(28))+(x.pop(27))+(x.pop(26))+(x.pop(25))+(x.pop(24))+(x.pop(23))+(x.pop(22))+(x.pop(21))+(x.pop(20)) temp_values4 = (x.pop(39))+(x.pop(38))+(x.pop(37))+(x.pop(36))+(x.pop(35))+(x.pop(34))+(x.pop(33))+(x.pop(32))+(x.pop(31))+(x.pop(30)) temp_values5 = (x.pop(49))+(x.pop(48))+(x.pop(47))+(x.pop(46))+(x.pop(45))+(x.pop(44))+(x.pop(43))+(x.pop(42))+(x.pop(41))+(x.pop(40)) temp_values6 = (x.pop(59))+(x.pop(58))+(x.pop(57))+(x.pop(56))+(x.pop(55))+(x.pop(54))+(x.pop(53))+(x.pop(52))+(x.pop(51))+(x.pop(50)) temp_values7 = (x.pop(69))+(x.pop(68))+(x.pop(67))+(x.pop(66))+(x.pop(65))+(x.pop(64))+(x.pop(63))+(x.pop(62))+(x.pop(61))+(x.pop(60)) temp_values8 = (x.pop(79))+(x.pop(78))+(x.pop(77))+(x.pop(76))+(x.pop(75))+(x.pop(74))+(x.pop(73))+(x.pop(72))+(x.pop(71))+(x.pop(70)) temp_values9 = (x.pop(89))+(x.pop(88))+(x.pop(87))+(x.pop(86))+(x.pop(85))+(x.pop(84))+(x.pop(83))+(x.pop(82))+(x.pop(81))+(x.pop(80)) temp_values10 = (x.pop(99))+(x.pop(98))+(x.pop(97))+(x.pop(96))+(x.pop(95))+(x.pop(94))+(x.pop(93))+(x.pop(92))+(x.pop(91))+(x.pop(90)) temp_values11 = (x.pop(109))+(x.pop(108))+(x.pop(107))+(x.pop(106))+(x.pop(105))+(x.pop(104))+(x.pop(103))+(x.pop(102))+(x.pop(101))+(x.pop(100)) temp_values12 = (x.pop(119))+(x.pop(118))+(x.pop(117))+(x.pop(116))+(x.pop(115))+(x.pop(114))+(x.pop(113))+(x.pop(112))+(x.pop(111))+(x.pop(110)) temp_values13 = (x.pop(127))+(x.pop(126))+(x.pop(125))+(x.pop(124))+(x.pop(123))+(x.pop(122))+(x.pop(121))+(x.pop(120)) temp_values=temp_values1+temp_values2+temp_values3+temp_values4+temp_values5+temp_values6+temp_values7+temp_values8+temp_values9+temp_values10+temp_values11+temp_values12+temp_values13 new_rows['ROW'+str(count+1)] = temp_values print new_rows if __name__ == '__main__': main() ###### but getting error: >>> Traceback (most recent call last): File "C:/Python25/myscript/group/group5.py", line 43, in main() File "C:/Python25/myscript/group/group5.py", line 26, in main temp_values8 = (x.pop(79))+(x.pop(78))+(x.pop(77))+(x.pop(76))+(x.pop(75))+(x.pop(74))+(x.pop(73))+(x.pop(72))+(x.pop(71))+(x.pop(70)) IndexError: pop index out of range pls advise. tq -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test2.txt URL: From kb1pkl at aim.com Sun Feb 13 15:50:15 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 13 Feb 2011 09:50:15 -0500 Subject: [Tutor] Backpropagation Learning in Python In-Reply-To: References: Message-ID: <4D57EFA7.9090202@aim.com> On 02/13/2011 03:54 AM, Jaidev Deshpande wrote: > Dear All > > Please suggest a link to tutorials for backpropagation and other neural > network training algorithms through Python. > > Any other commentary is welcome, as I am new to both Python and Neural > Networks. > > http://lmgtfy.com/?q=neural+networking+in+python http://lmgtfy.com/?q=backpropagation+in+python -- Corey Richardson From steve at pearwood.info Sun Feb 13 17:00:36 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 14 Feb 2011 03:00:36 +1100 Subject: [Tutor] How to group data? In-Reply-To: References: Message-ID: <4D580024.602@pearwood.info> tee chwee liong wrote: > hi, > > i'm using Python 2.5 and Win XP. > i want to extract the last column of the attached text file and group 128 characters to each row. want the result to look like: Did you have to flood us with the ENTIRE text file? Please show some respect! Next time, just show us a sample of the data: 0 BC_4 SYSCLK_DN observe_only 1 1 BC_4 SYSCLK_DP observe_only 1 2 BC_4 QPI3_DRX_DN 19 input X 3 BC_4 QPI3_DRX_DP 19 input X 4 BC_4 QPI3_DRX_DN 18 input X 5 BC_4 QPI3_DRX_DP 18 input X [...] 515 BC_1 internal X 516 BC_1 internal X 517 BC_1 internal X 518 BC_4 PWRGOOD observe_only 0 519 BC_4 VIOPWRGOOD observe_only 0 > Row1=XXXXX.............................1XXX (total of 128 char) > Row2=11XX...............................X1XX (total of 128 char) [...] > x = [] # making a new list here, not only > x += values # a new reference to the same object > > for count in xrange(0,len(values),128): > temp_values1 = (x.pop(9))+(x.pop(8))+(x.pop(7))+(x.pop(6))+(x.pop(5))+(x.pop(4))+(x.pop(3))+(x.pop(2))+(x.pop(1))+(x.pop(0)) > temp_values2 = (x.pop(19))+(x.pop(18))+(x.pop(17))+(x.pop(16))+(x.pop(15))+(x.pop(14))+(x.pop(13))+(x.pop(12))+(x.pop(11))+(x.pop(10)) > temp_values3 = (x.pop(29))+(x.pop(28))+(x.pop(27))+(x.pop(26))+(x.pop(25))+(x.pop(24))+(x.pop(23))+(x.pop(22))+(x.pop(21))+(x.pop(20)) > temp_values4 = (x.pop(39))+(x.pop(38))+(x.pop(37))+(x.pop(36))+(x.pop(35))+(x.pop(34))+(x.pop(33))+(x.pop(32))+(x.pop(31))+(x.pop(30)) > temp_values5 = (x.pop(49))+(x.pop(48))+(x.pop(47))+(x.pop(46))+(x.pop(45))+(x.pop(44))+(x.pop(43))+(x.pop(42))+(x.pop(41))+(x.pop(40)) > temp_values6 = (x.pop(59))+(x.pop(58))+(x.pop(57))+(x.pop(56))+(x.pop(55))+(x.pop(54))+(x.pop(53))+(x.pop(52))+(x.pop(51))+(x.pop(50)) > temp_values7 = (x.pop(69))+(x.pop(68))+(x.pop(67))+(x.pop(66))+(x.pop(65))+(x.pop(64))+(x.pop(63))+(x.pop(62))+(x.pop(61))+(x.pop(60)) > temp_values8 = (x.pop(79))+(x.pop(78))+(x.pop(77))+(x.pop(76))+(x.pop(75))+(x.pop(74))+(x.pop(73))+(x.pop(72))+(x.pop(71))+(x.pop(70)) > temp_values9 = (x.pop(89))+(x.pop(88))+(x.pop(87))+(x.pop(86))+(x.pop(85))+(x.pop(84))+(x.pop(83))+(x.pop(82))+(x.pop(81))+(x.pop(80)) > temp_values10 = (x.pop(99))+(x.pop(98))+(x.pop(97))+(x.pop(96))+(x.pop(95))+(x.pop(94))+(x.pop(93))+(x.pop(92))+(x.pop(91))+(x.pop(90)) > temp_values11 = (x.pop(109))+(x.pop(108))+(x.pop(107))+(x.pop(106))+(x.pop(105))+(x.pop(104))+(x.pop(103))+(x.pop(102))+(x.pop(101))+(x.pop(100)) > temp_values12 = (x.pop(119))+(x.pop(118))+(x.pop(117))+(x.pop(116))+(x.pop(115))+(x.pop(114))+(x.pop(113))+(x.pop(112))+(x.pop(111))+(x.pop(110)) > temp_values13 = (x.pop(127))+(x.pop(126))+(x.pop(125))+(x.pop(124))+(x.pop(123))+(x.pop(122))+(x.pop(121))+(x.pop(120)) Try this instead. rows = [] counter = 1 # count row numbers for i in range(0, len(values), 128): # Step through the list of values, starting at 0, # taking 128 items at a time. temp = values[i:i+128] # Join the values into a string. s = ''.join(temp) # And make a row with a label. row = "Row" + str(counter) + " = " + s print row rows.append(row) -- Steven From candleband at gmail.com Sun Feb 13 20:36:35 2011 From: candleband at gmail.com (C or L Smith) Date: Mon, 14 Feb 2011 01:21:35 +0545 Subject: [Tutor] How to group data? References: Message-ID: <2B6AC8F42ED246FBB32BBBED56A96C01@csmith> >> temp_values1 = >> (x.pop(9))+(x.pop(8))+(x.pop(7))+(x.pop(6))+(x.pop(5))+(x.pop(4))+(x.pop(3))+(x.pop(2))+(x.pop(1))+(x.pop(0)) >> temp_values2 = >> (x.pop(19))+(x.pop(18))+(x.pop(17))+(x.pop(16))+(x.pop(15))+(x.pop(14))+(x.pop(13))+(x.pop(12))+(x.pop(11))+(x.pop(10)) When you pop a value, it is removed from the list. If you had a list with only two items and you tried to pop 0 and then you tried to pop item 1 you would get an error: after popping item 0 there would only by a single item left...which would also be item 0. If you want to take the popping approach, every line should be the same as your first which pops, in reverse order, the first 10 items from x. AFter popping the first 10, the next ten are now where the first 10 used to be. But you could also not pop them and take them something like this: >>> l=range(10) >>> l1 = reversed(l[0:5]);l1 [4, 3, 2, 1, 0] >>> l2 = reversed(l[5:10]);l2 [9, 8, 7, 6, 5] Here, you are not popping them, you are just taking a slice from the list l. HTH, /c From davea at ieee.org Sun Feb 13 23:52:03 2011 From: davea at ieee.org (Dave Angel) Date: Sun, 13 Feb 2011 17:52:03 -0500 Subject: [Tutor] How to group data? In-Reply-To: References: Message-ID: <4D586093.3050501@ieee.org> On 01/-10/-28163 02:59 PM, tee chwee liong wrote: > > hi, > > i'm using Python 2.5 and Win XP. > i want to extract the last column of the attached text file and group 128 characters to each row. want the result to look like: > Row1=XXXXX.............................1XXX (total of 128 char) > Row2=11XX...............................X1XX (total of 128 char) > > ###code > from __future__ import with_statement > def main(): > new_rows = {} > values = [] > with open('test2.txt') as f: > for line in f: > values.append(line.rstrip('\n')[-1]) > > x = [] # making a new list here, not only > x += values # a new reference to the same object > > for count in xrange(0,len(values),128): > > temp_values1 = (x.pop(9))+(x.pop(8))+(x.pop(7))+(x.pop(6))+(x.pop(5))+(x.pop(4))+(x.pop(3))+(x.pop(2))+(x.pop(1))+(x.pop(0)) > temp_values2 = (x.pop(19))+(x.pop(18))+(x.pop(17))+(x.pop(16))+(x.pop(15))+(x.pop(14))+(x.pop(13))+(x.pop(12))+(x.pop(11))+(x.pop(10)) > temp_values3 = (x.pop(29))+(x.pop(28))+(x.pop(27))+(x.pop(26))+(x.pop(25))+(x.pop(24))+(x.pop(23))+(x.pop(22))+(x.pop(21))+(x.pop(20)) > temp_values4 = (x.pop(39))+(x.pop(38))+(x.pop(37))+(x.pop(36))+(x.pop(35))+(x.pop(34))+(x.pop(33))+(x.pop(32))+(x.pop(31))+(x.pop(30)) > temp_values5 = (x.pop(49))+(x.pop(48))+(x.pop(47))+(x.pop(46))+(x.pop(45))+(x.pop(44))+(x.pop(43))+(x.pop(42))+(x.pop(41))+(x.pop(40)) > temp_values6 = (x.pop(59))+(x.pop(58))+(x.pop(57))+(x.pop(56))+(x.pop(55))+(x.pop(54))+(x.pop(53))+(x.pop(52))+(x.pop(51))+(x.pop(50)) > temp_values7 = (x.pop(69))+(x.pop(68))+(x.pop(67))+(x.pop(66))+(x.pop(65))+(x.pop(64))+(x.pop(63))+(x.pop(62))+(x.pop(61))+(x.pop(60)) > temp_values8 = (x.pop(79))+(x.pop(78))+(x.pop(77))+(x.pop(76))+(x.pop(75))+(x.pop(74))+(x.pop(73))+(x.pop(72))+(x.pop(71))+(x.pop(70)) > temp_values9 = (x.pop(89))+(x.pop(88))+(x.pop(87))+(x.pop(86))+(x.pop(85))+(x.pop(84))+(x.pop(83))+(x.pop(82))+(x.pop(81))+(x.pop(80)) > temp_values10 = (x.pop(99))+(x.pop(98))+(x.pop(97))+(x.pop(96))+(x.pop(95))+(x.pop(94))+(x.pop(93))+(x.pop(92))+(x.pop(91))+(x.pop(90)) > temp_values11 = (x.pop(109))+(x.pop(108))+(x.pop(107))+(x.pop(106))+(x.pop(105))+(x.pop(104))+(x.pop(103))+(x.pop(102))+(x.pop(101))+(x.pop(100)) > temp_values12 = (x.pop(119))+(x.pop(118))+(x.pop(117))+(x.pop(116))+(x.pop(115))+(x.pop(114))+(x.pop(113))+(x.pop(112))+(x.pop(111))+(x.pop(110)) > temp_values13 = (x.pop(127))+(x.pop(126))+(x.pop(125))+(x.pop(124))+(x.pop(123))+(x.pop(122))+(x.pop(121))+(x.pop(120)) > > > temp_values=temp_values1+temp_values2+temp_values3+temp_values4+temp_values5+temp_values6+temp_values7+temp_values8+temp_values9+temp_values10+temp_values11+temp_values12+temp_values13 > > new_rows['ROW'+str(count+1)] = temp_values > print new_rows > if __name__ == '__main__': > main() > ###### > > but getting error: >>>> > Traceback (most recent call last): > File "C:/Python25/myscript/group/group5.py", line 43, in > main() > File "C:/Python25/myscript/group/group5.py", line 26, in main > temp_values8 = (x.pop(79))+(x.pop(78))+(x.pop(77))+(x.pop(76))+(x.pop(75))+(x.pop(74))+(x.pop(73))+(x.pop(72))+(x.pop(71))+(x.pop(70)) > IndexError: pop index out of range > > pls advise. tq How about some clues as to what you're trying to accomplish? This code is surprisingly verbose, and probably totally wrong. Anyway, each time you pop an item from the list, all the following ones change their index. So presumably there weren't still 79 items in the list by the time you had removed and shuffled a bunch of them. You don't indicate how many times it went around the outer loop, but in any case, there won't be enough values the last time around. There are also a few surprises in the code. x += isn't the simplest way to build a new list from the old. Use the following: x = values[:] You have lots of redundant parentheses on all those similar lines. Are you really trying to process only the last character of each line? Are you assuming the file has an exact multiple of 128 lines? DaveA From tcl76 at hotmail.com Mon Feb 14 00:55:24 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 13 Feb 2011 23:55:24 +0000 Subject: [Tutor] How to group data? In-Reply-To: <4D580024.602@pearwood.info> References: , <4D580024.602@pearwood.info> Message-ID: > for i in range(0, len(values), 128): > # Step through the list of values, starting at 0, > # taking 128 items at a time. > temp = values[i:i+128] > # Join the values into a string. > s = ''.join(temp) > # And make a row with a label. > row = "Row" + str(counter) + " = " + s > print row > rows.append(row) modified the code to be but it didnt print out anything: ###code from __future__ import with_statement def main(): rows = [] counter=1 #count row numbers values = [] with open('test2.txt') as f: for i in range(0,len(values),128): #step through the list of values, starting at 0, #taking 128 items at a time temp=values[i:i+128] #join the values into a string s=''.join(temp) #and make a row with a label. values.append(line.rstrip('\n')[-1]) row = "Row" + str(counter) + " = " + s print row rows.append(row) if __name__ == '__main__': main() ##### pls advise. tq -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Mon Feb 14 01:03:55 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 14 Feb 2011 00:03:55 +0000 Subject: [Tutor] How to group data? In-Reply-To: <4D586093.3050501@ieee.org> References: , <4D586093.3050501@ieee.org> Message-ID: > How about some clues as to what you're trying to accomplish? This code > is surprisingly verbose, and probably totally wrong. Anyway, each time > you pop an item from the list, all the following ones change their > index. So presumably there weren't still 79 items in the list by the > time you had removed and shuffled a bunch of them. You don't indicate > how many times it went around the outer loop, but in any case, there > won't be enough values the last time around. > sorry for the confusion. i'm trying to get: >>> ROW1=1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ROW2=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ROW3=XX11111X11XXXXX11XXXXXX1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ROW4=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX0XXXXXXXXXX1XXXXXXXXXXXX111111XXXX whereby it will group the last column in the data file into each row with 128 characters in reverse order. for eg: in data below and if i group it into 4 characters in a row in reverse order will be: row1=XX11 row2=XXXX row3=XXXX row4=00XX 0 BC_4 SYSCLK_DN observe_only 1 1 BC_4 SYSCLK_DP observe_only 1 2 BC_4 QPI3_DRX_DN 19 input X 3 BC_4 QPI3_DRX_DP 19 input X 4 BC_4 QPI3_DRX_DN 18 input X 5 BC_4 QPI3_DRX_DP 18 input X 6 BC_4 QPI3_DRX_DN 17 input X 7 BC_4 QPI3_DRX_DP 17 input X 8 BC_4 QPI3_DRX_DN 16 input X 9 BC_4 QPI3_DRX_DP 16 input X 10 BC_4 QPI3_DRX_DN 15 input X 11 BC_4 QPI3_DRX_DP 15 input X 12 BC_4 QPI3_DRX_DN 14 input X 13 BC_4 QPI3_DRX_DP 14 input X 14 BC_4 QPI3_DRX_DN 13 input 0 15 BC_4 QPI3_DRX_DP 13 input 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Feb 14 01:15:31 2011 From: davea at ieee.org (Dave Angel) Date: Sun, 13 Feb 2011 19:15:31 -0500 Subject: [Tutor] How to group data? In-Reply-To: References: , <4D586093.3050501@ieee.org> Message-ID: <4D587423.7030908@ieee.org> On 02/13/2011 07:03 PM, tee chwee liong wrote: > >> How about some clues as to what you're trying to accomplish? This code >> is surprisingly verbose, and probably totally wrong. Anyway, each time >> you pop an item from the list, all the following ones change their >> index. So presumably there weren't still 79 items in the list by the >> time you had removed and shuffled a bunch of them. You don't indicate >> how many times it went around the outer loop, but in any case, there >> won't be enough values the last time around. >> > > sorry for the confusion. i'm trying to get: >>>> > ROW1=1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX > ROW2=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX > ROW3=XX11111X11XXXXX11XXXXXX1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX > ROW4=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX0XXXXXXXXXX1XXXXXXXXXXXX111111XXXX > > whereby it will group the last column in the data file into each row with 128 characters in reverse order. for eg: in data below and if i group it into 4 characters in a row in reverse order will be: > > row1=XX11 > row2=XXXX > row3=XXXX > row4=00XX > > 0 BC_4 SYSCLK_DN observe_only 1 > 1 BC_4 SYSCLK_DP observe_only 1 > 2 BC_4 QPI3_DRX_DN 19 input X > 3 BC_4 QPI3_DRX_DP 19 input X > 4 BC_4 QPI3_DRX_DN 18 input X > 5 BC_4 QPI3_DRX_DP 18 input X > 6 BC_4 QPI3_DRX_DN 17 input X > 7 BC_4 QPI3_DRX_DP 17 input X > 8 BC_4 QPI3_DRX_DN 16 input X > 9 BC_4 QPI3_DRX_DP 16 input X > 10 BC_4 QPI3_DRX_DN 15 input X > 11 BC_4 QPI3_DRX_DP 15 input X > 12 BC_4 QPI3_DRX_DN 14 input X > 13 BC_4 QPI3_DRX_DP 14 input X > 14 BC_4 QPI3_DRX_DN 13 input 0 > 15 BC_4 QPI3_DRX_DP 13 input 0 > It still makes no sense to me. If you need to reverse a string, use [::-1] idiom For example, a = "abcde" print a[::-1] will print edcba Hope that helps in some way. But I don't understand what you're trying to do, and the example above doesn't make it any clearer. DaveA From carlarjenkins at yahoo.com Mon Feb 14 03:46:52 2011 From: carlarjenkins at yahoo.com (Carla Jenkins) Date: Sun, 13 Feb 2011 18:46:52 -0800 (PST) Subject: [Tutor] Higher-Order Function Examples Message-ID: <249002.63802.qm@web31507.mail.mud.yahoo.com> Hello everyone: I am new to Python and?am looking for higher-order function programming examples.? The programming codes do not feature the corresponding equation so I am lost. Please help me. ? Sincerely, Carla Jenkins -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Feb 14 10:44:15 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 14 Feb 2011 20:44:15 +1100 Subject: [Tutor] How to group data? In-Reply-To: References: , <4D580024.602@pearwood.info> Message-ID: <4D58F96F.4040007@pearwood.info> tee chwee liong wrote: > modified the code to be but it didnt print out anything: That is because your list of values is empty. You have to collect the values, like your previous code did. *Then* process them. In the code below, you try to process values before you have any. > from __future__ import with_statement > def main(): > rows = [] > counter=1 #count row numbers > values = [] > with open('test2.txt') as f: > for i in range(0,len(values),128): > #step through the list of values, starting at 0, > #taking 128 items at a time > temp=values[i:i+128] > #join the values into a string > s=''.join(temp) > #and make a row with a label. > values.append(line.rstrip('\n')[-1]) > row = "Row" + str(counter) + " = " + s > print row > rows.append(row) -- Steven From alan.gauld at btinternet.com Mon Feb 14 10:46:47 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Feb 2011 09:46:47 -0000 Subject: [Tutor] Higher-Order Function Examples References: <249002.63802.qm@web31507.mail.mud.yahoo.com> Message-ID: "Carla Jenkins" wrote > I am new to Python and am looking for higher-order > function programming examples. This sounds like homework, if not I apologize, but as such I can only gicve you some pointers As with all concept type stuff wikipedia is a good place to start. Just search for "higher order function" Some of the examples are in Python... You could also try reading the Functional Programming topic in my tutorial. And maybe the GUI topic too. > The programming codes do not feature the corresponding > equation so I am lost. Please help me. I don't understand that. What programming codes are you referring to? What equation? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Mon Feb 14 12:15:26 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 14 Feb 2011 05:15:26 -0600 Subject: [Tutor] How to group data? In-Reply-To: References: <4D586093.3050501@ieee.org> Message-ID: On Sun, Feb 13, 2011 at 6:03 PM, tee chwee liong wrote: > > How about some clues as to what you're trying to accomplish? This code > > is surprisingly verbose, and probably totally wrong. Anyway, each time > > you pop an item from the list, all the following ones change their > > index. So presumably there weren't still 79 items in the list by the > > time you had removed and shuffled a bunch of them. You don't indicate > > how many times it went around the outer loop, but in any case, there > > won't be enough values the last time around. > > > > sorry for the confusion. i'm trying to get: > >>> > > ROW1=1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX > > ROW2=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX > > ROW3=XX11111X11XXXXX11XXXXXX1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX > > ROW4=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX0XXXXXXXXXX1XXXXXXXXXXXX111111XXXX > > whereby it will group the last column in the data file into each row with > 128 characters in reverse order. for eg: in data below and if i group it > into 4 characters in a row in reverse order will be: > >From this example it appears that what you would like to do is get the last character from a grouping of four lines. Then you would like to reverse each group of four. If this is true, what you're doing is most certainly the wrong way to go about it. You can easily break this problem down into several steps: 1) open a file and read four lines at a time. 2) Pull the last character from each line (you can use reverse indexing, i.e. '987654321'[-3] => '3') 3) group these characters into a string and reverse them - Dave Angel showed the most idiomatic way. 4) prepend "Row N=" to your string, replacing N with the number 5) Do something with all of those strings 6) Profit??? It appears that from the beginning you did *not* create an algorithm, or steps to solve your problem, but just started throwing code at it. This will usually produce terrible code that is both buggy and horrible to try to read. If it turns out that I misunderstood what your end goal was with the data, simply decide 1) What do I need? 2) What is the pattern in my data? 3) What are the easiest tools to use to get what I need, considering my pattern? And then you probably have your program. HTH, Wayne > row1=XX11 > row2=XXXX > row3=XXXX > row4=00XX > > > 0 BC_4 SYSCLK_DN observe_only 1 > 1 BC_4 SYSCLK_DP observe_only 1 > 2 BC_4 QPI3_DRX_DN 19 input X > 3 BC_4 QPI3_DRX_DP 19 input X > 4 BC_4 QPI3_DRX_DN 18 input X > 5 BC_4 QPI3_DRX_DP 18 input X > 6 BC_4 QPI3_DRX_DN 17 input X > 7 BC_4 QPI3_DRX_DP 17 input X > 8 BC_4 QPI3_DRX_DN 16 input X > 9 BC_4 QPI3_DRX_DP 16 input X > 10 BC_4 QPI3_DRX_DN 15 input X > 11 BC_4 QPI3_DRX_DP 15 input X > 12 BC_4 QPI3_DRX_DN 14 input X > 13 BC_4 QPI3_DRX_DP 14 input X > 14 BC_4 QPI3_DRX_DN 13 input 0 > 15 BC_4 QPI3_DRX_DP 13 input 0 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Feb 14 12:30:46 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 14 Feb 2011 22:30:46 +1100 Subject: [Tutor] Higher-Order Function Examples In-Reply-To: <249002.63802.qm@web31507.mail.mud.yahoo.com> References: <249002.63802.qm@web31507.mail.mud.yahoo.com> Message-ID: <4D591266.3050405@pearwood.info> Carla Jenkins wrote: > Hello everyone: I am new to Python and am looking for higher-order > function programming examples. The programming codes do not feature > the corresponding equation so I am lost. Please help me. The first thing you need to understand is the difference between *code* and *data*. Code, or programs, or functions, is the thing that does stuff. That's a bit vague, but you should get the idea: you can have a function to print a list of telephone addresses, or control a microwave oven, or delete unneeded records in a database. You know,... stuff. Data is the things that functions work on: numbers, strings, lists of data, addresses, and things like that. Data doesn't do anything, it just sits there in a file, or in a variable, waiting for a function to do stuff with it. The idea for "higher-order functions" came from one simple, but radical, concept: the idea that functions themselves can ALSO be data. The idea is simple: it's like the idea of building a tool to build the tool you actually need. But this was quite a radical idea, because many computer languages enforced a strict separation of functions and data. Fortunately Python is not one of those languages. In Python, we say that "functions are first-class objects" -- you can treat functions like numbers, or strings, or lists, or any other data. The difference is, you just refer to the function by name without following it with brackets: len # The built-in function itself. len(x) # Calling the function len on argument x. So you can write one function that takes another function as argument, and does something useful with that function: def draw_graph(function, x_min, x_max): # Draw a graph of function between x_min and x_max. ... You won't believe how hard that is in languages like Pascal that don't have first class functions! Here's a working example. Suppose you are doing a lot of string processing, using string.upper(), string.lower() etc. And you want to see what they do, when they get called. So you might write a function like this: def pr_upper(s): print(s) return str.upper(s) # you may be more familiar with the syntax # s.upper() instead of str.upper(s) and then instead of using str.upper, you use pr_upper instead. Now you want to do the same for str.lower, str.title, str.capitalize, and any other string functions you might have. This gets tedious and boring, writing all these little functions by hand. So, make a tool to make the tools you want! We write a *factory function* that creates new functions for us: def make_pr(function): # Return a new function that prints the argument first. def inner(s): print(s) return function(s) return inner # Return the inner function we just built. pr_upper = make_pr(str.upper) pr_lower = make_pr(str.lower) pr_split = make_pr(str.split) Of course, there's no reason why we're limited to built-in functions. It also works on our own functions: def spammer(food): return "spam and %s" % food spammer("eggs") # returns "spam and eggs" pr_spammer = make_pr(spammer) make_pr is a higher-order function -- it's a function that treats other functions as data. Python come with at least four higher-order functions built in, plus some more in various libraries. I'm not going to talk about them all, but I'll mention three of them: map, filter and reduce. (The fourth, apply, is obsolete and has been removed completely from Python 3. Don't worry about it, but if you care, you can look it up in the manual.) (1) map takes a function and a sequence of values, and it applies the function to each value in the sequence. For example: # convert items to strings map(str, [1, 2, 3]) # Python 2 => ['1', '2', '3'] In Python 3, map has been changed to be lazy. It no longer returns the new list all at once, but returns a special *iterator* object that gives one value at a time, on request. This is much more memory efficient, but you can get the old behaviour back by using the function list(): list(map(str, [1, 2, 3])) # Python 3 => ['1', '2', '3'] (2) filter takes a function and a sequence of values, and returns those values where function returns true. For example: # filter only uppercase strings filter(str.isupper, ['a', 'B', 'c', 'D']) # Python 2 => ['B', 'D'] Again, in Python 3, filter has become lazy. (3) reduce is perhaps the trickiest of the built-in high-order functions. Again, it takes a function and a sequence of values. It grabs the first two values, and feeds them to the function to get a result. Then it takes that result, and the next value, and feeds them into the function to get the next result. And repeats, until there's no more values. An example might help. Back in the old days, before Python had a sum() function, the easiest way to add up a list of numbers was to use reduce and a small function to add two numbers: def add(x, y): return x+y total = filter(add, [2, 4, 5, 9, 1]) Step by step, filter would do this: Take the first two values, 2 and 4, and feed them to add: add(2, 4) -> 6 Take it and the next value, 5, and feed them to add: add(6, 5) -> 11 Take it and the next value, 9, and feed them to add: add(11, 9) -> 20 Take it and the next value, 1, and feed them to add: add(20, 1) -> 21 So the final result is 21. A lot of people find reduce() too hard to understand, and so sadly in Python 3 it has been banished from the built-in functions into the functools library. Hope this helps, -- Steven From steve at pearwood.info Mon Feb 14 12:35:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 14 Feb 2011 22:35:48 +1100 Subject: [Tutor] Higher-Order Function Examples In-Reply-To: <4D591266.3050405@pearwood.info> References: <249002.63802.qm@web31507.mail.mud.yahoo.com> <4D591266.3050405@pearwood.info> Message-ID: <4D591394.6090508@pearwood.info> Steven D'Aprano wrote: > An example might help. Back in the old days, before Python had a sum() > function, the easiest way to add up a list of numbers was to use reduce > and a small function to add two numbers: > > def add(x, y): > return x+y > > total = filter(add, [2, 4, 5, 9, 1]) Arggggh! Of course, I meant *reduce* in that example, not filter. Sorry for any confusion! -- Steven From tcl76 at hotmail.com Mon Feb 14 15:05:59 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 14 Feb 2011 14:05:59 +0000 Subject: [Tutor] How to group data? In-Reply-To: References: <4D586093.3050501@ieee.org>, , Message-ID: thanks everyone for the advice. my code looks very messy... needs more practise. From: waynejwerner at gmail.com Date: Mon, 14 Feb 2011 05:15:26 -0600 Subject: Re: [Tutor] How to group data? To: tcl76 at hotmail.com CC: davea at ieee.org; tutor at python.org On Sun, Feb 13, 2011 at 6:03 PM, tee chwee liong wrote: > How about some clues as to what you're trying to accomplish? This code > is surprisingly verbose, and probably totally wrong. Anyway, each time > you pop an item from the list, all the following ones change their > index. So presumably there weren't still 79 items in the list by the > time you had removed and shuffled a bunch of them. You don't indicate > how many times it went around the outer loop, but in any case, there > won't be enough values the last time around. > sorry for the confusion. i'm trying to get: >>> ROW1=1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ROW2=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ROW3=XX11111X11XXXXX11XXXXXX1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ROW4=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX0XXXXXXXXXX1XXXXXXXXXXXX111111XXXX whereby it will group the last column in the data file into each row with 128 characters in reverse order. for eg: in data below and if i group it into 4 characters in a row in reverse order will be: >From this example it appears that what you would like to do is get the last character from a grouping of four lines. Then you would like to reverse each group of four. If this is true, what you're doing is most certainly the wrong way to go about it. You can easily break this problem down into several steps: 1) open a file and read four lines at a time. 2) Pull the last character from each line (you can use reverse indexing, i.e. '987654321'[-3] => '3') 3) group these characters into a string and reverse them - Dave Angel showed the most idiomatic way. 4) prepend "Row N=" to your string, replacing N with the number 5) Do something with all of those strings 6) Profit??? It appears that from the beginning you did *not* create an algorithm, or steps to solve your problem, but just started throwing code at it. This will usually produce terrible code that is both buggy and horrible to try to read. If it turns out that I misunderstood what your end goal was with the data, simply decide 1) What do I need? 2) What is the pattern in my data? 3) What are the easiest tools to use to get what I need, considering my pattern? And then you probably have your program. HTH, Wayne row1=XX11 row2=XXXX row3=XXXX row4=00XX 0 BC_4 SYSCLK_DN observe_only 1 1 BC_4 SYSCLK_DP observe_only 1 2 BC_4 QPI3_DRX_DN 19 input X 3 BC_4 QPI3_DRX_DP 19 input X 4 BC_4 QPI3_DRX_DN 18 input X 5 BC_4 QPI3_DRX_DP 18 input X 6 BC_4 QPI3_DRX_DN 17 input X 7 BC_4 QPI3_DRX_DP 17 input X 8 BC_4 QPI3_DRX_DN 16 input X 9 BC_4 QPI3_DRX_DP 16 input X 10 BC_4 QPI3_DRX_DN 15 input X 11 BC_4 QPI3_DRX_DP 15 input X 12 BC_4 QPI3_DRX_DN 14 input X 13 BC_4 QPI3_DRX_DP 14 input X 14 BC_4 QPI3_DRX_DN 13 input 0 15 BC_4 QPI3_DRX_DP 13 input 0 _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Mon Feb 14 17:04:16 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 14 Feb 2011 17:04:16 +0100 Subject: [Tutor] How to run another python script? In-Reply-To: <1ce97808-22d0-4ff8-b75d-2a57dd1958b8@o39g2000prb.googlegroups.com> References: <1ce97808-22d0-4ff8-b75d-2a57dd1958b8@o39g2000prb.googlegroups.com> Message-ID: <4D595280.8080809@free.fr> On 02/14/2011 04:51 PM, Dan Lee wrote: > Hi. > > I just knew what python is. > Now I'm about to write backup script.Now I got 2 scripts. > > AAA : generate zip file > BBB : delete old file. > > AAA is done. > Now I'm going to code BBB file. and I will fix AAA to call BBB to > delete dump file at the end. One possibility: exec( "/BBB" ) Or make import of BBB module as below: from BBB import main BBB.main() Regards Karim > Please let me know How can I call the BBB file from AAA file. > > Thanks in advance. > Dan From karim.liateni at free.fr Mon Feb 14 17:34:57 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 14 Feb 2011 17:34:57 +0100 Subject: [Tutor] How to run another python script? In-Reply-To: <4D595280.8080809@free.fr> References: <1ce97808-22d0-4ff8-b75d-2a57dd1958b8@o39g2000prb.googlegroups.com> <4D595280.8080809@free.fr> Message-ID: <4D5959B1.9040509@free.fr> Better way is to not have BBB but simply to use Exception (pseudo-code): try: ... catch IOError, e: print("Error encountered in generating zip file:", e) else: import os os.remove('') Regards Karim On 02/14/2011 05:04 PM, Karim wrote: > On 02/14/2011 04:51 PM, Dan Lee wrote: >> Hi. >> >> I just knew what python is. >> Now I'm about to write backup script.Now I got 2 scripts. >> >> AAA : generate zip file >> BBB : delete old file. >> >> AAA is done. >> Now I'm going to code BBB file. and I will fix AAA to call BBB to >> delete dump file at the end. > > One possibility: > > exec( "/BBB" ) > > Or make import of BBB module as below: > > from BBB import main > BBB.main() > > Regards > Karim > >> Please let me know How can I call the BBB file from AAA file. >> >> Thanks in advance. >> Dan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From rafadurancastaneda at gmail.com Mon Feb 14 20:16:02 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Mon, 14 Feb 2011 20:16:02 +0100 Subject: [Tutor] Higher-Order Function Examples In-Reply-To: <4D591394.6090508@pearwood.info> References: <249002.63802.qm@web31507.mail.mud.yahoo.com> <4D591266.3050405@pearwood.info> <4D591394.6090508@pearwood.info> Message-ID: Could we consider sorted as an high order function? sorted_list = sorted(list_strings, key = str.lower) 2011/2/14 Steven D'Aprano > Steven D'Aprano wrote: > > An example might help. Back in the old days, before Python had a sum() >> function, the easiest way to add up a list of numbers was to use reduce and >> a small function to add two numbers: >> >> def add(x, y): >> return x+y >> >> total = filter(add, [2, 4, 5, 9, 1]) >> > > Arggggh! Of course, I meant *reduce* in that example, not filter. Sorry for > any confusion! > > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Feb 14 21:06:34 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 14 Feb 2011 22:06:34 +0200 Subject: [Tutor] Higher-Order Function Examples In-Reply-To: References: <249002.63802.qm@web31507.mail.mud.yahoo.com> <4D591266.3050405@pearwood.info> <4D591394.6090508@pearwood.info> Message-ID: 2011/2/14 Rafael Dur?n Casta?eda > Could we consider sorted as an high order function? > > sorted_list = sorted(list_strings, key = str.lower) > > No because sorted() returns a list as a result. A higher order function produces another function as a result, or takes one or more functions as a parameter. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafadurancastaneda at gmail.com Mon Feb 14 21:23:54 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Mon, 14 Feb 2011 21:23:54 +0100 Subject: [Tutor] Higher-Order Function Examples In-Reply-To: References: <249002.63802.qm@web31507.mail.mud.yahoo.com> <4D591266.3050405@pearwood.info> <4D591394.6090508@pearwood.info> Message-ID: In the example I gave: sorted_list = sorted(list_strings, key = str.lower) sorted takes str.lower as a parameter, doesn't it? So, it should be a high order function El 14 de febrero de 2011 21:06, Walter Prins escribi?: > > > 2011/2/14 Rafael Dur?n Casta?eda > > Could we consider sorted as an high order function? >> >> sorted_list = sorted(list_strings, key = str.lower) >> >> > No because sorted() returns a list as a result. A higher order function > produces another function as a result, or takes one or more functions as a > parameter. > > Walter > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Feb 14 21:35:02 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 14 Feb 2011 22:35:02 +0200 Subject: [Tutor] Higher-Order Function Examples In-Reply-To: References: <249002.63802.qm@web31507.mail.mud.yahoo.com> <4D591266.3050405@pearwood.info> <4D591394.6090508@pearwood.info> Message-ID: 2011/2/14 Rafael Dur?n Casta?eda > In the example I gave: > > > sorted_list = sorted(list_strings, key = str.lower) > > sorted takes str.lower as a parameter, doesn't it? So, it should be a high > order function > My apologies! Yes, you are of course quite correct! :) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From mitchseymour at gmail.com Mon Feb 14 20:55:36 2011 From: mitchseymour at gmail.com (Mitch Seymour) Date: Mon, 14 Feb 2011 14:55:36 -0500 Subject: [Tutor] GUI + python program Message-ID: Hello, I am trying to design a program and GUI that will allow the user to select from a series of options and, depending on which options are selected in the GUI, information will then be placed in a html or pdf template. Here's an example. Option A Option B Option C If Option A, insert _____ into the template. If Option B, insert _____ into the template. If Option C, insert _____ into the template. The reason I used ______ is because the user needs to be able to edit, from the GUI, which information is associated with each option, and, subsequently, which information will be placed into the template. However, I am very new to python and I don't how to do this. A friend suggested that I create a python file that would store the user defined information, which would be read by the program before the information is placed into the template. So the user could select the options from the GUI, edit the associated information from a preferences tab, and then initiate the process of placing the info into the templates. My question is, how would you do this and, if I do create a file to store the information, could you please give me some examples of code to get me started? Thanks so much! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 14 21:47:51 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Feb 2011 20:47:51 -0000 Subject: [Tutor] Higher-Order Function Examples References: <249002.63802.qm@web31507.mail.mud.yahoo.com><4D591266.3050405@pearwood.info> <4D591394.6090508@pearwood.info> Message-ID: "Rafael Dur?n Casta?eda" wrote > Could we consider sorted as an high order function? > > sorted_list = sorted(list_strings, key = str.lower) Yes, there are lots of them All the GUI building functions in Tkinter that take command arguments are higher order functions too. And many functions in programming frameworks like Twisted and web frameworks take functions as arguments. They are alll around if you look fior them... Alan G From patrick.just4fun at gmail.com Mon Feb 14 22:15:30 2011 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Mon, 14 Feb 2011 22:15:30 +0100 Subject: [Tutor] GUI + python program In-Reply-To: References: Message-ID: <4D599B72.3060201@gmail.com> You have a lot of options: GUI: Any major gui toolkit will do the job. It's probobly easiest to stick with tkinter. HTML Template: Use a template language, e.g. mako or django templates Pdf Templates: Reportlab is an option. File Access: Of course you could just open a file and write to it, but it probably gets messy. I would recommend using a database. Sqlite is maybe a good choice, or sqlalchemy. - Patrick On 2011-02-14 20:55, Mitch Seymour wrote: > Hello, > > I am trying to design a program and GUI that will allow the user to > select from a series of options and, depending on which options are > selected in the GUI, information will then be placed in a html or pdf > template. > > Here's an example. > > Option A > Option B > Option C > > If Option A, insert _____ into the template. > If Option B, insert _____ into the template. > If Option C, insert _____ into the template. > > The reason I used ______ is because the user needs to be able to edit, > from the GUI, which information is associated with each option, and, > subsequently, which information will be placed into the template. > > However, I am very new to python and I don't how to do this. A friend > suggested that I create a python file that would store the user defined > information, which would be read by the program before the information > is placed into the template. So the user could select the options from > the GUI, edit the associated information from a preferences tab, and > then initiate the process of placing the info into the templates. > > My question is, how would you do this and, if I do create a file to > store the information, could you please give me some examples of code to > get me started? > > Thanks so much! > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From djotero at plymouth.edu Mon Feb 14 22:59:19 2011 From: djotero at plymouth.edu (Daniel Otero) Date: Mon, 14 Feb 2011 16:59:19 -0500 Subject: [Tutor] Tutor Digest, Vol 84, Issue 56 Message-ID: tutor-request at python.org wrote: >Send Tutor mailing list submissions to > tutor at python.org > >To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor >or, via email, send a message with subject or body 'help' to > tutor-request at python.org > >You can reach the person managing the list at > tutor-owner at python.org > >When replying, please edit your Subject line so it is more specific >than "Re: Contents of Tutor digest..." > > >Today's Topics: > > 1. Re: How to run another python script? (Karim) > 2. Re: How to run another python script? (Karim) > 3. Re: Higher-Order Function Examples (Rafael Dur?n Casta?eda) > 4. Re: Higher-Order Function Examples (Walter Prins) > 5. Re: Higher-Order Function Examples (Rafael Dur?n Casta?eda) > 6. Re: Higher-Order Function Examples (Walter Prins) > 7. GUI + python program (Mitch Seymour) > > >---------------------------------------------------------------------- > >Message: 1 >Date: Mon, 14 Feb 2011 17:04:16 +0100 >From: Karim >To: Dan Lee , python mail list > >Subject: Re: [Tutor] How to run another python script? >Message-ID: <4D595280.8080809 at free.fr> >Content-Type: text/plain; charset=ISO-8859-1; format=flowed > >On 02/14/2011 04:51 PM, Dan Lee wrote: >> Hi. >> >> I just knew what python is. >> Now I'm about to write backup script.Now I got 2 scripts. >> >> AAA : generate zip file >> BBB : delete old file. >> >> AAA is done. >> Now I'm going to code BBB file. and I will fix AAA to call BBB to >> delete dump file at the end. > >One possibility: > >exec( "/BBB" ) > >Or make import of BBB module as below: > >from BBB import main >BBB.main() > >Regards >Karim > >> Please let me know How can I call the BBB file from AAA file. >> >> Thanks in advance. >> Dan > > > >------------------------------ > >Message: 2 >Date: Mon, 14 Feb 2011 17:34:57 +0100 >From: Karim >To: Dan Lee , python mail list > >Subject: Re: [Tutor] How to run another python script? >Message-ID: <4D5959B1.9040509 at free.fr> >Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > >Better way is to not have BBB but simply to use Exception (pseudo-code): > >try: > > ... >catch IOError, e: > print("Error encountered in generating zip file:", e) >else: > import os > os.remove('') > >Regards >Karim > > >On 02/14/2011 05:04 PM, Karim wrote: >> On 02/14/2011 04:51 PM, Dan Lee wrote: >>> Hi. >>> >>> I just knew what python is. >>> Now I'm about to write backup script.Now I got 2 scripts. >>> >>> AAA : generate zip file >>> BBB : delete old file. >>> >>> AAA is done. >>> Now I'm going to code BBB file. and I will fix AAA to call BBB to >>> delete dump file at the end. >> >> One possibility: >> >> exec( "/BBB" ) >> >> Or make import of BBB module as below: >> >> from BBB import main >> BBB.main() >> >> Regards >> Karim >> >>> Please let me know How can I call the BBB file from AAA file. >>> >>> Thanks in advance. >>> Dan >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > >------------------------------ > >Message: 3 >Date: Mon, 14 Feb 2011 20:16:02 +0100 >From: Rafael Dur?n Casta?eda >To: Tutor at python.org >Subject: Re: [Tutor] Higher-Order Function Examples >Message-ID: > >Content-Type: text/plain; charset="iso-8859-1" > >Could we consider sorted as an high order function? > >sorted_list = sorted(list_strings, key = str.lower) > >2011/2/14 Steven D'Aprano > >> Steven D'Aprano wrote: >> >> An example might help. Back in the old days, before Python had a sum() >>> function, the easiest way to add up a list of numbers was to use reduce and >>> a small function to add two numbers: >>> >>> def add(x, y): >>> return x+y >>> >>> total = filter(add, [2, 4, 5, 9, 1]) >>> >> >> Arggggh! Of course, I meant *reduce* in that example, not filter. Sorry for >> any confusion! >> >> >> >> >> -- >> Steven >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >Message: 4 >Date: Mon, 14 Feb 2011 22:06:34 +0200 >From: Walter Prins >To: Rafael Dur?n Casta?eda >Cc: Tutor at python.org >Subject: Re: [Tutor] Higher-Order Function Examples >Message-ID: > >Content-Type: text/plain; charset="iso-8859-1" > >2011/2/14 Rafael Dur?n Casta?eda > >> Could we consider sorted as an high order function? >> >> sorted_list = sorted(list_strings, key = str.lower) >> >> >No because sorted() returns a list as a result. A higher order function >produces another function as a result, or takes one or more functions as a >parameter. > >Walter >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >Message: 5 >Date: Mon, 14 Feb 2011 21:23:54 +0100 >From: Rafael Dur?n Casta?eda >To: Tutor at python.org >Subject: Re: [Tutor] Higher-Order Function Examples >Message-ID: > >Content-Type: text/plain; charset="iso-8859-1" > >In the example I gave: > >sorted_list = sorted(list_strings, key = str.lower) > >sorted takes str.lower as a parameter, doesn't it? So, it should be a high >order function > >El 14 de febrero de 2011 21:06, Walter Prins escribi?: > >> >> >> 2011/2/14 Rafael Dur?n Casta?eda >> >> Could we consider sorted as an high order function? >>> >>> sorted_list = sorted(list_strings, key = str.lower) >>> >>> >> No because sorted() returns a list as a result. A higher order function >> produces another function as a result, or takes one or more functions as a >> parameter. >> >> Walter >> >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >Message: 6 >Date: Mon, 14 Feb 2011 22:35:02 +0200 >From: Walter Prins >To: Rafael Dur?n Casta?eda >Cc: Tutor at python.org >Subject: Re: [Tutor] Higher-Order Function Examples >Message-ID: > >Content-Type: text/plain; charset="iso-8859-1" > >2011/2/14 Rafael Dur?n Casta?eda > >> In the example I gave: >> >> >> sorted_list = sorted(list_strings, key = str.lower) >> >> sorted takes str.lower as a parameter, doesn't it? So, it should be a high >> order function >> > >My apologies! Yes, you are of course quite correct! :) > >Walter >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >Message: 7 >Date: Mon, 14 Feb 2011 14:55:36 -0500 >From: Mitch Seymour >To: tutor at python.org >Subject: [Tutor] GUI + python program >Message-ID: > >Content-Type: text/plain; charset="iso-8859-1" > >Hello, > >I am trying to design a program and GUI that will allow the user to select >from a series of options and, depending on which options are selected in the >GUI, information will then be placed in a html or pdf template. > >Here's an example. > >Option A >Option B >Option C > >If Option A, insert _____ into the template. >If Option B, insert _____ into the template. >If Option C, insert _____ into the template. > >The reason I used ______ is because the user needs to be able to edit, from >the GUI, which information is associated with each option, and, >subsequently, which information will be placed into the template. > >However, I am very new to python and I don't how to do this. A friend >suggested that I create a python file that would store the user defined >information, which would be read by the program before the information is >placed into the template. So the user could select the options from the GUI, >edit the associated information from a preferences tab, and then initiate >the process of placing the info into the templates. > >My question is, how would you do this and, if I do create a file to store >the information, could you please give me some examples of code to get me >started? > >Thanks so much! >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > >End of Tutor Digest, Vol 84, Issue 56 >************************************* From steve at pearwood.info Mon Feb 14 23:38:32 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 15 Feb 2011 09:38:32 +1100 Subject: [Tutor] Higher-Order Function Examples In-Reply-To: References: <249002.63802.qm@web31507.mail.mud.yahoo.com> <4D591266.3050405@pearwood.info> <4D591394.6090508@pearwood.info> Message-ID: <4D59AEE8.8080600@pearwood.info> Walter Prins wrote: > 2011/2/14 Rafael Dur?n Casta?eda > >> Could we consider sorted as an high order function? >> >> sorted_list = sorted(list_strings, key = str.lower) >> >> > No because sorted() returns a list as a result. A higher order function > produces another function as a result, or takes one or more functions as a > parameter. By that definition, sorted *is* a higher-order function as it takes a key function as a parameter. Typically, though, most people would consider that in order to count as a high order function, it must take another function as a main parameter, and not as an optional extra. E.g. sorted doesn't make the cut, because you can call sorted(list_strings) without giving a key function. The key function is an optional extra that merely modifies the action of sorted, rather than an essential part of it. On the other hand, once you really start to embrace the idea of functions-as-data, the distinction becomes less important. There are functions that take strings as arguments, and functions that take numbers as argument, and functions that take strings AND numbers as arguments... why should we single out functions that take functions as special? If functions are tools, then there's no fundamental difference between "ordinary tools" and "tools that make other tools". They're all just tools. The difference between "ordinary functions" and "higher-order functions" is most important in languages that don't have higher-order functions. -- Steven From bgailer at gmail.com Tue Feb 15 02:57:42 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 14 Feb 2011 20:57:42 -0500 Subject: [Tutor] Tutor Digest, Vol 84, Issue 56 In-Reply-To: References: Message-ID: <4D59DD96.20009@gmail.com> On 2/14/2011 4:59 PM, Daniel Otero wrote: Did you want something? If so state clearly and delete all non-relevant messages. Did you notice: When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." -- Bob Gailer 919-636-4239 Chapel Hill NC From tcl76 at hotmail.com Tue Feb 15 06:40:50 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Tue, 15 Feb 2011 05:40:50 +0000 Subject: [Tutor] Py script conversion to .dll or .exe Message-ID: hi all, pls advise on: Can Python 2.6.6 scripts be converted to .dll and read by C sharp? Can Python 2.6.6 scripts be converted to .exe and read by C sharp? thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Feb 15 06:58:44 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 14 Feb 2011 23:58:44 -0600 Subject: [Tutor] Py script conversion to .dll or .exe In-Reply-To: References: Message-ID: On Mon, Feb 14, 2011 at 11:40 PM, tee chwee liong wrote: > hi all, > > pls advise on: > > 1. Can Python 2.6.6 scripts be converted to .dll and read by C sharp? > 2. Can Python 2.6.6 scripts be converted to .exe and read by C sharp? > > Anything is possible. Of course, the easiest way to do *this* would be to use IronPython. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Tue Feb 15 07:31:43 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Tue, 15 Feb 2011 06:31:43 +0000 Subject: [Tutor] Py script conversion to .dll or .exe In-Reply-To: References: , Message-ID: any major differences using Iron Python vs Python 2.6.6? tq From: waynejwerner at gmail.com Date: Mon, 14 Feb 2011 23:58:44 -0600 Subject: Re: [Tutor] Py script conversion to .dll or .exe To: tcl76 at hotmail.com CC: tutor at python.org On Mon, Feb 14, 2011 at 11:40 PM, tee chwee liong wrote: hi all, pls advise on: Can Python 2.6.6 scripts be converted to .dll and read by C sharp? Can Python 2.6.6 scripts be converted to .exe and read by C sharp? Anything is possible. Of course, the easiest way to do *this* would be to use IronPython. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Tue Feb 15 08:08:07 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 15 Feb 2011 01:08:07 -0600 Subject: [Tutor] Py script conversion to .dll or .exe In-Reply-To: References: Message-ID: <201102150108.11309.cfuller084@thinkingplanet.net> Python already is a dll; You can load the Python26.dll and use it to run CPython programs with full compatibility. It would be more elegant to use IronPython if if you aren't using any compiled libraries; it would integrate neatly and not be running islolated/standalone. Cheers On Monday 14 February 2011, tee chwee liong wrote: > hi all, > > pls advise on: > > Can Python 2.6.6 scripts be converted to .dll and read by C sharp? > Can Python 2.6.6 scripts be converted to .exe and read by C sharp? > > thanks > tcl From coolankur2006 at gmail.com Tue Feb 15 10:23:02 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Tue, 15 Feb 2011 14:53:02 +0530 Subject: [Tutor] Update a button content on click Message-ID: Hey I am looking for a method using Tkinter module to update the button on the click. Suppose I have a button with "hello" print on it. I want that when i click on it "hello" got updated with the "hi". New value button should return on the its click should be "hi". I tried it through event handling but failed to do so. Any help would be appreciated. Thanks In Advance Ankur Aggarwal -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 15 13:28:47 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Feb 2011 12:28:47 -0000 Subject: [Tutor] Update a button content on click References: Message-ID: "ANKUR AGGARWAL" wrote > I am looking for a method using Tkinter module to update the button > on the > click. Define an event handler command for the button. Lets call it sayHi() def sayHi(self): self.myButton['text'] = 'hi' # Note:event handlers don't return results so store it as an attribute self.myButtonResult = 'hi' Now create the widget with spam as the handler. self.myButton = Button(parent, text='hello', command = spam) That's it. > the its click should be "hi". I tried it through event handling but > failed > to do so. It would be more helpful if you posted the code that you tried and a more detailed explanation of "failed to do so". What happened? Did it update but not store a value? Did you get an error message? Did anything happen? The more specific information you provide the more likely you are to get a specific solution that works. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lumtegis at gmail.com Tue Feb 15 14:31:23 2011 From: lumtegis at gmail.com (allan oware) Date: Tue, 15 Feb 2011 05:31:23 -0800 Subject: [Tutor] Creating xml documents Message-ID: Hi there, Which python modules can one use to create nicely formatted xml documents ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Feb 15 14:48:10 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 15 Feb 2011 14:48:10 +0100 Subject: [Tutor] Creating xml documents In-Reply-To: References: Message-ID: allan oware, 15.02.2011 14:31: > Which python modules can one use to create nicely formatted xml documents ? Depends on your exact needs, but xml.etree.ElementTree is usually a good thing to use anyway. If you care about formatting (a.k.a. pretty printing), look here: http://effbot.org/zone/element-lib.htm#prettyprint Stefan From karim.liateni at free.fr Tue Feb 15 17:24:12 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 15 Feb 2011 17:24:12 +0100 Subject: [Tutor] Creating xml documents In-Reply-To: References: Message-ID: <4D5AA8AC.9020801@free.fr> Hello, It seems stefan that version 1.3 still does not validate xml against xsd... Reg On 02/15/2011 02:48 PM, Stefan Behnel wrote: > allan oware, 15.02.2011 14:31: >> Which python modules can one use to create nicely formatted xml >> documents ? > > Depends on your exact needs, but xml.etree.ElementTree is usually a > good thing to use anyway. If you care about formatting (a.k.a. pretty > printing), look here: > > http://effbot.org/zone/element-lib.htm#prettyprint > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From karim.liateni at free.fr Tue Feb 15 17:24:26 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 15 Feb 2011 17:24:26 +0100 Subject: [Tutor] Creating xml documents In-Reply-To: References: Message-ID: <4D5AA8BA.3040202@free.fr> Hello, It seems stefan that version 1.3 still does not validate xml against xsd... Reg On 02/15/2011 02:48 PM, Stefan Behnel wrote: > allan oware, 15.02.2011 14:31: >> Which python modules can one use to create nicely formatted xml >> documents ? > > Depends on your exact needs, but xml.etree.ElementTree is usually a > good thing to use anyway. If you care about formatting (a.k.a. pretty > printing), look here: > > http://effbot.org/zone/element-lib.htm#prettyprint > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From coolankur2006 at gmail.com Tue Feb 15 17:28:10 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Tue, 15 Feb 2011 21:58:10 +0530 Subject: [Tutor] Update a button content on click In-Reply-To: References: Message-ID: hmmm... i got the point. I applied it in image case. b1=button(root,image=None,height=4,width=4,command=ok) and then ok defination is as follows : def ok(): b1["image"]=photo now problem is that after clicking on the button, image is coming up like a flash and then button becomes almost to zero size. I want to retain the height=4,width=4 along with the image after clicking on the button. Image size is smaller than the button size. On Tue, Feb 15, 2011 at 5:58 PM, Alan Gauld wrote: > > "ANKUR AGGARWAL" wrote > > > I am looking for a method using Tkinter module to update the button on the >> click. >> > > Define an event handler command for the button. > Lets call it sayHi() > > def sayHi(self): > self.myButton['text'] = 'hi' > # Note:event handlers don't return results so store it as an attribute > self.myButtonResult = 'hi' > > Now create the widget with spam as the handler. > > self.myButton = Button(parent, text='hello', command = spam) > > That's it. > > > the its click should be "hi". I tried it through event handling but failed >> to do so. >> > > It would be more helpful if you posted the code that you tried > and a more detailed explanation of "failed to do so". > What happened? Did it update but not store a value? > Did you get an error message? Did anything happen? > > The more specific information you provide the more likely you > are to get a specific solution that works. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Feb 15 17:52:51 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 15 Feb 2011 17:52:51 +0100 Subject: [Tutor] Creating xml documents In-Reply-To: <4D5AA8AC.9020801@free.fr> References: <4D5AA8AC.9020801@free.fr> Message-ID: Karim, 15.02.2011 17:24: > On 02/15/2011 02:48 PM, Stefan Behnel wrote: >> allan oware, 15.02.2011 14:31: >>> Which python modules can one use to create nicely formatted xml documents ? >> >> Depends on your exact needs, but xml.etree.ElementTree is usually a good >> thing to use anyway. If you care about formatting (a.k.a. pretty >> printing), look here: >> >> http://effbot.org/zone/element-lib.htm#prettyprint > > It seems stefan that version 1.3 still does not validate xml against xsd... I have no idea what this has to do with either the OP's thread (i.e. this thread) or with me. It's true, though, that ElementTree does not support validation against W3C XML Schema. If you need that, you can use lxml, but I do not see the OP needing this. Stefan From alan.gauld at btinternet.com Tue Feb 15 17:56:46 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 15 Feb 2011 16:56:46 +0000 (GMT) Subject: [Tutor] Update a button content on click In-Reply-To: References: Message-ID: <743429.80128.qm@web86702.mail.ird.yahoo.com> > b1=button(root,image=None,height=4,width=4,command=ok) This says you want the button to e 4 pixels squarte. Is that really what you want?, because.... and then ok defination is as follows : > def ok(): > b1["image"]=photo > > >now problem is that after clicking on the button, image is coming >up like a flash and then button becomes almost to zero size. > > Like to 4x4 pixels maybe, just as you asked? What happens if you change the size to something like 40x40? Also in Tkinter to display an image you usually have to firtst create a PhotoImage object and assign that to the image attribute. It's not clear from your code whether you are doing that or not. Is photo a PhotImage object? I want to retain the height=4,width=4 along with the image after >clicking on the button. Image size is smaller than the button size. >It sounds like your original size is greater than 4x4 and after setting the image it shrinks to 4x4... HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From coolankur2006 at gmail.com Tue Feb 15 18:04:06 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Tue, 15 Feb 2011 22:34:06 +0530 Subject: [Tutor] Update a button content on click In-Reply-To: <743429.80128.qm@web86702.mail.ird.yahoo.com> References: <743429.80128.qm@web86702.mail.ird.yahoo.com> Message-ID: from Tkinter import * root=Tk() photo=PhotoImage(file="Cross.gif") def ok(): b1["image"]=photo b1=Button(root,text="",image=None,command=ok) b1.grid() root.mainloop() Here's my code . Not getting the desired output On Tue, Feb 15, 2011 at 10:26 PM, ALAN GAULD wrote: > > b1=button(root,image=None,height=4,width=4,command=ok) > > This says you want the button to e 4 pixels squarte. Is that really > what you want?, because.... > > and then ok defination is as follows : > def ok(): > b1["image"]=photo > > now problem is that after clicking on the button, image is coming > up like a flash and then button becomes almost to zero size. > > Like to 4x4 pixels maybe, just as you asked? > What happens if you change the size to something like 40x40? > > Also in Tkinter to display an image you usually have to firtst create > a PhotoImage object and assign that to the image attribute. It's not > clear from your code whether you are doing that or not. > Is photo a PhotImage object? > > I want to retain the height=4,width=4 along with the image after > clicking on the button. Image size is smaller than the button size. > > It sounds like your original size is greater than 4x4 and after setting > the image it shrinks to 4x4... > > HTH, > > Alan G. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From coolankur2006 at gmail.com Tue Feb 15 18:14:38 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Tue, 15 Feb 2011 22:44:38 +0530 Subject: [Tutor] Update a button content on click In-Reply-To: References: <743429.80128.qm@web86702.mail.ird.yahoo.com> Message-ID: upper code posted earlier is running fine.... The problem is in the code below bcoz of the height nd width factor... from Tkinter import * root=Tk() photo=PhotoImage(file="Cross.gif") def ok(): b1["image"]=photo b1=Button(root,text="",image=None,height=4,width=4,command=ok) b1.grid() On Tue, Feb 15, 2011 at 10:34 PM, ANKUR AGGARWAL wrote: > from Tkinter import * > root=Tk() > > photo=PhotoImage(file="Cross.gif") > def ok(): > b1["image"]=photo > > b1=Button(root,text="",image=None,command=ok) > b1.grid() > root.mainloop() > > Here's my code . Not getting the desired output > > On Tue, Feb 15, 2011 at 10:26 PM, ALAN GAULD wrote: > >> > b1=button(root,image=None,height=4,width=4,command=ok) >> >> This says you want the button to e 4 pixels squarte. Is that really >> what you want?, because.... >> >> and then ok defination is as follows : >> def ok(): >> b1["image"]=photo >> >> now problem is that after clicking on the button, image is coming >> up like a flash and then button becomes almost to zero size. >> >> Like to 4x4 pixels maybe, just as you asked? >> What happens if you change the size to something like 40x40? >> >> Also in Tkinter to display an image you usually have to firtst create >> a PhotoImage object and assign that to the image attribute. It's not >> clear from your code whether you are doing that or not. >> Is photo a PhotImage object? >> >> I want to retain the height=4,width=4 along with the image after >> clicking on the button. Image size is smaller than the button size. >> >> It sounds like your original size is greater than 4x4 and after setting >> the image it shrinks to 4x4... >> >> HTH, >> >> Alan G. >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 15 18:50:51 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 15 Feb 2011 17:50:51 +0000 (GMT) Subject: [Tutor] Update a button content on click In-Reply-To: References: <743429.80128.qm@web86702.mail.ird.yahoo.com> Message-ID: <94548.2582.qm@web86705.mail.ird.yahoo.com> I modified your code slightly for Python 3.1 to this: ####################### from tkinter import * root=Tk() def ok(): b1["image"]=photo photo=PhotoImage(file=r"M:\Photos\TomMcM\Chris.GIF") b1=Button(root,text="",image=None,command=ok) b1.grid() root.mainloop() ######################### Which works perfectly for me. What happens for you? Do you get any error messages? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ > >From: ANKUR AGGARWAL >To: ALAN GAULD >Cc: tutor at python.org >Sent: Tuesday, 15 February, 2011 17:04:06 >Subject: Re: [Tutor] Update a button content on click > > >from Tkinter import * >root=Tk() > > >photo=PhotoImage(file="Cross.gif") >def ok(): > b1["image"]=photo > > >b1=Button(root,text="",image=None,command=ok) >b1.grid() >root.mainloop() > > >Here's my code . Not getting the desired output > >On Tue, Feb 15, 2011 at 10:26 PM, ALAN GAULD wrote: > >> b1=button(root,image=None,height=4,width=4,command=ok) >> >>This says you want the button to e 4 pixels squarte. Is that really >>what you want?, because.... >> >> >>and then ok defination is as follows : >>> def ok(): >>> b1["image"]=photo >>> >>> >>>now problem is that after clicking on the button, image is coming >>>up like a flash and then button becomes almost to zero size. >>> >>> >>Like to 4x4 pixels maybe, just as you asked? >>What happens if you change the size to something like 40x40? >> >>Also in Tkinter to display an image you usually have to firtst create >>a PhotoImage object and assign that to the image attribute. It's not >>clear from your code whether you are doing that or not. >>Is photo a PhotImage object? >> >> >>I want to retain the height=4,width=4 along with the image after >>>clicking on the button. Image size is smaller than the button size. >>>It sounds like your original size is greater than 4x4 and after setting >>the image it shrinks to 4x4... >> >> >>HTH, >> >>Alan G. >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From coolankur2006 at gmail.com Tue Feb 15 19:00:48 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Tue, 15 Feb 2011 23:30:48 +0530 Subject: [Tutor] Update a button content on click In-Reply-To: <94548.2582.qm@web86705.mail.ird.yahoo.com> References: <743429.80128.qm@web86702.mail.ird.yahoo.com> <94548.2582.qm@web86705.mail.ird.yahoo.com> Message-ID: your code was fine. I am having problem with this code from Tkinter import * root=Tk() photo=PhotoImage(file="Cross.gif") def ok(): b1["image"]=photo b1=Button(root,text="",image=None,height=4,width=4,command=ok) b1.grid() root.mainloop() On Tue, Feb 15, 2011 at 11:20 PM, ALAN GAULD wrote: > I modified your code slightly for Python 3.1 to this: > > ####################### > from tkinter import * > root=Tk() > > > def ok(): > b1["image"]=photo > > photo=PhotoImage(file=r"M:\Photos\TomMcM\Chris.GIF") > > b1=Button(root,text="",image=None,command=ok) > b1.grid() > > root.mainloop() > ######################### > > Which works perfectly for me. > What happens for you? > Do you get any error messages? > > Alan Gauld > Author of the Learn To Program website > > http://www.alan-g.me.uk/ > > > *From:* ANKUR AGGARWAL > *To:* ALAN GAULD > *Cc:* tutor at python.org > *Sent:* Tuesday, 15 February, 2011 17:04:06 > *Subject:* Re: [Tutor] Update a button content on click > > from Tkinter import * > root=Tk() > > photo=PhotoImage(file="Cross.gif") > def ok(): > b1["image"]=photo > > b1=Button(root,text="",image=None,command=ok) > b1.grid() > root.mainloop() > > Here's my code . Not getting the desired output > > On Tue, Feb 15, 2011 at 10:26 PM, ALAN GAULD wrote: > >> > b1=button(root,image=None,height=4,width=4,command=ok) >> >> This says you want the button to e 4 pixels squarte. Is that really >> what you want?, because.... >> >> and then ok defination is as follows : >> def ok(): >> b1["image"]=photo >> >> now problem is that after clicking on the button, image is coming >> up like a flash and then button becomes almost to zero size. >> >> Like to 4x4 pixels maybe, just as you asked? >> What happens if you change the size to something like 40x40? >> >> Also in Tkinter to display an image you usually have to firtst create >> a PhotoImage object and assign that to the image attribute. It's not >> clear from your code whether you are doing that or not. >> Is photo a PhotImage object? >> >> I want to retain the height=4,width=4 along with the image after >> clicking on the button. Image size is smaller than the button size. >> >> It sounds like your original size is greater than 4x4 and after setting >> the image it shrinks to 4x4... >> >> HTH, >> >> Alan G. >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 15 19:04:55 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 15 Feb 2011 18:04:55 +0000 (GMT) Subject: [Tutor] Update a button content on click In-Reply-To: References: <743429.80128.qm@web86702.mail.ird.yahoo.com> Message-ID: <875531.93180.qm@web86705.mail.ird.yahoo.com> It works fine for me. Except that the button is too big before I press it - I'm not sure why - but after pressing it it shrinks to 4x4 pixels with the image inside.(albeit too small to see!). OK, more experimenting... It seems that Tkinter is smart enough to use characters for sizes when displaying a text label but pixels for images. So in the event handler you need to reset the size. This works for me with a GIF size of 200x100 #################### from tkinter import * root=Tk() photo=PhotoImage(file=r"M:\Photos\TomMcM\Chris.GIF") def ok(): # reset size to pixels for image b1.configure(image=photo, height="90", width="140") # original size in chars b1=Button(root,text=" ", command=ok, height="6", width="20") b1.grid() root.mainloop() ######################### Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ > >From: ANKUR AGGARWAL >To: ALAN GAULD >Cc: tutor at python.org >Sent: Tuesday, 15 February, 2011 17:14:38 >Subject: Re: [Tutor] Update a button content on click > >upper code posted earlier is running fine.... > > >The problem is in the code below bcoz of the height nd width factor... > >from Tkinter import * >root=Tk() > > >photo=PhotoImage(file="Cross.gif") >def ok(): > b1["image"]=photo > > >b1=Button(root,text="",image=None,height=4,width=4,command=ok) >b1.grid() > > >On Tue, Feb 15, 2011 at 10:34 PM, ANKUR AGGARWAL >wrote: > >from Tkinter import * >>root=Tk() >> >> >>photo=PhotoImage(file="Cross.gif") >>def ok(): >> b1["image"]=photo >> >> >>b1=Button(root,text="",image=None,command=ok) >>b1.grid() >>root.mainloop() >> >> >>Here's my code . Not getting the desired output >> >> >>On Tue, Feb 15, 2011 at 10:26 PM, ALAN GAULD wrote: >> >>> b1=button(root,image=None,height=4,width=4,command=ok) >>> >>>This says you want the button to e 4 pixels squarte. Is that really >>>what you want?, because.... >>> >>> >>>and then ok defination is as follows : >>>> def ok(): >>>> b1["image"]=photo >>>> >>>> >>>>now problem is that after clicking on the button, image is coming >>>>up like a flash and then button becomes almost to zero size. >>>> >>>> >>>Like to 4x4 pixels maybe, just as you asked? >>>What happens if you change the size to something like 40x40? >>> >>>Also in Tkinter to display an image you usually have to firtst create >>>a PhotoImage object and assign that to the image attribute. It's not >>>clear from your code whether you are doing that or not. >>>Is photo a PhotImage object? >>> >>> >>>I want to retain the height=4,width=4 along with the image after >>>>clicking on the button. Image size is smaller than the button size. >>>>It sounds like your original size is greater than 4x4 and after setting >>>the image it shrinks to 4x4... >>> >>> >>>HTH, >>> >>>Alan G. >>> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyronoth at gmail.com Tue Feb 15 19:50:47 2011 From: kyronoth at gmail.com (S de Haan) Date: Tue, 15 Feb 2011 19:50:47 +0100 Subject: [Tutor] remote code execution Message-ID: Hi guys, I was wondering if there is a IDE or another environment that allows me to execute python code from my desktop computer on remote servers within my LAN without having to move the python files to and from the server. For instance, Im working on my local machine with Eclipse, but using the Interpreter that is on one of my Linux Servers. I hope i made my question clear enough. Thanks, Sebas -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Tue Feb 15 19:57:40 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Tue, 15 Feb 2011 10:57:40 -0800 Subject: [Tutor] remote code execution In-Reply-To: References: Message-ID: <4D5ACCA4.8070604@iandouglas.com> Sounds like it should be possible via SSH, but I have no idea how you'd set that up within Eclipse. On 02/15/2011 10:50 AM, S de Haan wrote: > For instance, Im working on my local machine with Eclipse, but using > the Interpreter that is on one of my Linux Servers. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Feb 15 20:11:15 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 15 Feb 2011 11:11:15 -0800 Subject: [Tutor] remote code execution In-Reply-To: References: Message-ID: On 2/15/2011 10:50 AM S de Haan said... > Hi guys, > > I was wondering if there is a IDE or another environment that allows me > to execute python code from my desktop computer on remote servers within > my LAN without having to move the python files to and from the server. > > For instance, Im working on my local machine with Eclipse, but using the > Interpreter that is on one of my Linux Servers. > > I hope i made my question clear enough. > I do that sort of thing routinely by exporting the python directory on the linux side to my local machine, editing with my local editor, and opening an ssh session to the server to run and test the code. Is that what you're after? Emile From izzaddin.ruhulessin at gmail.com Tue Feb 15 20:13:02 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Tue, 15 Feb 2011 20:13:02 +0100 Subject: [Tutor] remote code execution In-Reply-To: <4D5ACCA4.8070604@iandouglas.com> References: <4D5ACCA4.8070604@iandouglas.com> Message-ID: Send your code as a raw text string and use eval on it maybe 2011/2/15 ian douglas > Sounds like it should be possible via SSH, but I have no idea how you'd > set that up within Eclipse. > > > On 02/15/2011 10:50 AM, S de Haan wrote: > > For instance, Im working on my local machine with Eclipse, but using the > Interpreter that is on one of my Linux Servers. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Tue Feb 15 20:15:41 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Tue, 15 Feb 2011 20:15:41 +0100 Subject: [Tutor] remote code execution In-Reply-To: References: <4D5ACCA4.8070604@iandouglas.com> Message-ID: Just tested that, doesn't work. Have you considered installing SVN or any other version control system? 2011/2/15 Izz ad-Din Ruhulessin > Send your code as a raw text string and use eval on it maybe > > 2011/2/15 ian douglas > >> Sounds like it should be possible via SSH, but I have no idea how you'd >> set that up within Eclipse. >> >> >> On 02/15/2011 10:50 AM, S de Haan wrote: >> >> For instance, Im working on my local machine with Eclipse, but using the >> Interpreter that is on one of my Linux Servers. >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 15 20:26:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Feb 2011 19:26:02 -0000 Subject: [Tutor] remote code execution References: Message-ID: "S de Haan" wrote > I was wondering if there is a IDE or another environment that allows > me to > execute python code from my desktop computer on remote servers > within > my LAN without having to move the python files to and from the > server. So you have the Python interpreter on a server and you are working on scripts stored on a PC on the network? Since you mention Linux for the server can we assume Linux for the PC too? Can you mount the PC folder on the server? If so its just a case of running a ssh session on the server and accessing the mount. Otherwise it would be much easier to mount a server folder on your PC and edit the files there. Then you can use ssh to run both interpreter and scripts on the server... But I can't help asking, why not just install a local version of Python? Is there a lot of bespoke shared code on the server or somesuch? Alan G. From kyronoth at gmail.com Tue Feb 15 21:41:02 2011 From: kyronoth at gmail.com (S de Haan) Date: Tue, 15 Feb 2011 21:41:02 +0100 Subject: [Tutor] remote code execution In-Reply-To: References: Message-ID: On Tue, Feb 15, 2011 at 8:26 PM, Alan Gauld wrote: > > "S de Haan" wrote > > > I was wondering if there is a IDE or another environment that allows me to >> execute python code from my desktop computer on remote servers within >> my LAN without having to move the python files to and from the server. >> > > So you have the Python interpreter on a server and you are > working on scripts stored on a PC on the network? Since you > mention Linux for the server can we assume Linux for the > PC too? > > Can you mount the PC folder on the server? If so its just a case of > running a ssh session on the server and accessing the mount. > > Otherwise it would be much easier to mount a server folder > on your PC and edit the files there. Then you can use ssh to > run both interpreter and scripts on the server... > > But I can't help asking, why not just install a local version > of Python? Is there a lot of bespoke shared code on the server > or somesuch? > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thanks all for the Answers, and the desktop machine is running mostly Windows... So when building a Linux focussed application it becomes difficult to run in locally... However mounting the server share on the Desktop shouldn't be that difficult. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Feb 15 21:46:34 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 15 Feb 2011 12:46:34 -0800 Subject: [Tutor] remote code execution In-Reply-To: References: Message-ID: <4D5AE62A.3090106@alchemy.com> On 15-Feb-11 12:41, S de Haan wrote: > Thanks all for the Answers, and the desktop machine is running mostly > Windows... So when building a Linux focussed application it becomes > difficult to run in locally... > > However mounting the server share on the Desktop shouldn't be that > difficult. Thanks! It seems like the ideal case would be to run a remote desktop session onto the target system and develop there (e.g., run Eclipse or your favorite IDE on the Linux box, using it via VNC or something). Then you're running the real code on the real system. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From wallenpb at gmail.com Wed Feb 16 01:08:40 2011 From: wallenpb at gmail.com (Bill Allen) Date: Tue, 15 Feb 2011 18:08:40 -0600 Subject: [Tutor] remote code execution In-Reply-To: References: Message-ID: If SAMBA is available on the Linux server, create a share and put your source files there. Then, map that CIFS share on you Windows workstation and work on the files on the share with you local IDE. Run the code via a ssh or telnet connection session back to the Linux server. Editing and running would both be right on your desktop at that point. --Bill On Tue, Feb 15, 2011 at 12:50, S de Haan wrote: > Hi guys, > > I was wondering if there is a IDE or another environment that allows me to > execute python code from my desktop computer on remote servers within my LAN > without having to move the python files to and from the server. > > For instance, Im working on my local machine with Eclipse, but using the > Interpreter that is on one of my Linux Servers. > > I hope i made my question clear enough. > > Thanks, Sebas > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emekamicro at gmail.com Wed Feb 16 09:17:55 2011 From: emekamicro at gmail.com (Emeka) Date: Wed, 16 Feb 2011 09:17:55 +0100 Subject: [Tutor] Tkinter's Label Message-ID: Hello All, I have the following; root = Tk() label = Label(root , text = "pure") in order to change "text" , I could do the this label[text] = "pool" I do know that there is something like this.. label.config(text = "pool") Which one should I use? Regards, Emeka -------------- next part -------------- An HTML attachment was scrubbed... URL: From lumtegis at gmail.com Wed Feb 16 09:20:55 2011 From: lumtegis at gmail.com (allan oware) Date: Wed, 16 Feb 2011 00:20:55 -0800 Subject: [Tutor] Creating xml documents Message-ID: Alright, Am stuck with xml.dom.minidom, but is there correct usage for *Node.prettyxml() *resulting in less junky newlines and spaces ? i.e *from* 28.4258363792 -6.13557141177 46.1374243603 6.41013674147 *to* * * 28.477417 -4.936117 47.341236 5.267412 Regards, Allan. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Wed Feb 16 09:35:53 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 16 Feb 2011 09:35:53 +0100 Subject: [Tutor] Creating xml documents In-Reply-To: References: Message-ID: allan oware, 16.02.2011 09:20: > Alright, > Am stuck with xml.dom.minidom Interesting. Why would that be the case? >, but is there correct usage for *Node.prettyxml() > *resulting in less junky newlines and spaces ? > > i.e *from* > > > > 28.4258363792 > > > -6.13557141177 > > > 46.1374243603 > > > 6.41013674147 > > > > *to* > * > * > > 28.477417 > -4.936117 > 47.341236 > 5.267412 > See my reply to your original question: use ElementTree. Stefan From karim.liateni at free.fr Wed Feb 16 09:58:02 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 16 Feb 2011 09:58:02 +0100 Subject: [Tutor] Accessing query results html frame :The solution In-Reply-To: <4D5B7F6C.5050605@free.fr> References: <4D542AA0.5080801@free.fr> <4D54EA92.4030800@free.fr> <4D59230D.1030502@free.fr> <4D5B7F6C.5050605@free.fr> Message-ID: <4D5B919A.2090903@free.fr> On 02/16/2011 08:40 AM, Karim wrote: > On 02/14/2011 01:41 PM, Karim wrote: >> >> Hello, >> >> As I get no response from the tutor python list, I am continuing to >> investigate my problem. >> >> In fact the issue is that there are 2 forms in the interactive page >> and my request does nothing >> instead I get the interactive page not the submission I asked (query >> results). The 2 forms are: >> >> 1. > ENCTYPE="application/x-www-form-urlencoded" NAME="form1"> >> 2. > ENCTYPE="application/x-www-form-urlencoded" NAME="form9"> >> >> And the parameters for each are: >> >> 1) >> >> >> >> >>   >>   >>   >>   >> > ONCLICK="oncreate()">  >> >> >> >> >> 2) >> >> >> >> >> >> And I recall my data of the progam below: >> >> data = { >> 'init' : "", >> 'LastForm': "SavedQuery", >> 'prompted': "yes", >> 'class': "Development", >> 'personalQuery': "DKPV", >> 'REMOTE_USER': username, >> 'QS': " -p DKPVALIDATION_PLUGIN \(Class 'isequal' >> "Development" \)", >> 'use_field_defs':"false", >> 'QueryName': "DKPV", >> 'QueryType': "personal", >> 'ACTION': "Query" >> } >> >> So the question is how could I specify the correct FORM submission >> and how could I chose the correct action because >> there are several TYPE='submit' and I am only interested by this one >> VALUE="Query"? >> >> Regards >> Karim >> >> On 02/11/2011 08:51 AM, Karim wrote: >>> >>> Hello, >>> >>> In fact as found in the net: >>> >>> "The concept of browser frames is completely outside the scope of >>> HTTP. However, browser frames are defined in HTML, and so is the >>> target property on form elements: <form action="/somescript?x=y" >>> method="POST" target="_top"> This will make the form submit to >>> the _top frame, which means "use the full browser window" " >>> >>> That means that my post form: >>> >>> >> ENCTYPE="application/x-www-form-urlencoded" TARGET="rightframe"> >>> >>> has a target property to make the submit to the 'rightframe'. >>> >>> Any ideas how I can modified the code (I think the request data or >>> whatever) below to access without knowing the temporary html file >>> name generically. >>> >>> Regards >>> Karim >>> >>> On 02/10/2011 07:12 PM, Karim wrote: >>>> >>>> Hello All, >>>> >>>> I get from Steven an very useful link (void space) for http >>>> authentication. I added some codes to be >>>> able to POST FORM a query as I do it by clicking a query button to >>>> get a list of bug Id on a server. >>>> The problem is I get a html page which refers 2 frames. And I am >>>> interesting in one particular frame >>>> namely for example, >>>> http://{server}:{port}/wt/tmp/results:karim.liateni.31_3917.html'.format(server=server, >>>> port=port). >>>> But this pages is created every times in a tmp directory each time >>>> with a different name. >>>> >>>> 1) How can I get the name of this page because with python the page >>>> resulting of my query is not mentionned (hidden like)? >>>> Interactively there are 3 frames but only this one is of interest >>>> for me. But no name of this page is visible in the main html page. >>>> Is there a method to get all the nested frames locations? >>>> >>>> 2) I can see this page interactively when I click on a submit query >>>> button. Do I need to add 'ACTION': "Query" >>> in the query dictionnary to simulate a click for submission >>>> (type="submit" button) ? >>>> >>>> 3) Interactively I see that cgi arg NextForm is empty so I let it >>>> like that in my query and LastForm was set to "SavedQuery". I put the >>>> same value in my python code. Is this ok? >>>> >>>> import urllib >>>> import urllib2 >>>> >>>> server='dummy.com' >>>> port='8081' >>>> >>>> username = 'karim.liateni' >>>> password = 'dummy_pass' >>>> >>>> theurl = >>>> 'http://{server}:{port}/ddts/ddts_main'.format(server=server, >>>> port=port) >>>> #theurl = >>>> 'http://{server}:{port}:8081/wt/tmp/results:karim.liateni.31_3917.html'.format(server=server, >>>> port=port) >>>> >>>> #MEMO: >>>> #>>> ENCTYPE="application/x-www-form-urlencoded" TARGET="rightframe"> >>>> >>>> data = { >>>> 'NextForm': "", >>>> 'LastForm': "SavedQuery", >>>> 'prompted': "yes", >>>> 'class': "Development", >>>> 'personalQuery': "DKPV", >>>> 'REMOTE_USER': username, >>>> 'QS': " -p DKPVALIDATION_PLUGIN \(Class 'isequal' >>>> "Development" \)", >>>> 'use_field_defs':"false", >>>> 'QueryName': "DKPV", >>>> 'QueryType': "personal", >>>> 'ACTION': "Query" >>>> } >>>> >>>> query = urllib.urlencode(data) >>>> request = urllib2.Request(theurl, query) >>>> >>>> passman = urllib2.HTTPPasswordMgrWithDefaultRealm() >>>> passman.add_password(None, theurl, username, password) >>>> authhandler = urllib2.HTTPBasicAuthHandler(passman) >>>> >>>> opener = urllib2.build_opener(authhandler) >>>> urllib2.install_opener(opener) >>>> >>>> pagehandle = urllib2.urlopen(request) >>>> print(pagehandle.read()) >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >> >> > > The solution to handle multiple post forms in a same web page and to > submit a given one programmatically is > to use this very must have module ClientForm from > "http://wwwsearch.sourceforge.net/ClientForm" and maintained by John J.Lee > > Example from this module: > > response = > urllib2.urlopen("http://wwwsearch.sourceforge.net/ClientForm/example.html") > forms = ClientForm.ParseResponse(response, backwards_compat=False) > form = forms[0] > print form > > # set html widget value > form["comments"] = "Thanks, Gisle" > > #Controls are html widgets (Listbox, checkbutton, combobox, etc ...) > print "parmesan" in [item.name for item in > form.find_control("cheeses").items if item.selected] > > # select item labelled "Mozzarella" in control with id "chz" as the > same with a mouse-click: > form.find_control(id="chz").get(label="Mozzarella").selected = True > > # submit the form returns a urllib2.Request object > new_request = form.click() > new_response = urllib2.urlopen(new_request) > > > This is a very handy and easy module! > For whom it mays concern. > > Regards > Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 16 10:13:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Feb 2011 09:13:04 -0000 Subject: [Tutor] Tkinter's Label References: Message-ID: "Emeka" wrote > in order to change "text" , I could do the this > > label[text] = "pool" > > I do know that there is something like this.. > > label.configure(text = "pool") For singlealue changes it's largely a matter of taste but I personally use the dictionary form for a single value change and configure() where I am changing multiple values at the same time. (Otherwise I'd need to have multiple lines changing one value each...) Thus, if the new label were very long and you wanted to change the width of the control to accomodate it you could do label.configure(text='a very long message indeed', width=50) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From emekamicro at gmail.com Wed Feb 16 11:02:09 2011 From: emekamicro at gmail.com (Emeka) Date: Wed, 16 Feb 2011 11:02:09 +0100 Subject: [Tutor] Tkinter's Label In-Reply-To: References: Message-ID: Alan, Thanks so much. Is the below the standard way of checking the content of Label in "if" statement? root = Tk() label = Label(root , text = "pure") if label["pure"] == "pure": Regards, Emeka On Wed, Feb 16, 2011 at 10:13 AM, Alan Gauld wrote: > > "Emeka" wrote > > in order to change "text" , I could do the this >> >> label[text] = "pool" >> >> I do know that there is something like this.. >> >> label.configure(text = "pool") >> > > For singlealue changes it's largely a matter of taste but I personally use > the dictionary form for a single value change and configure() where I am > changing multiple values at the same time. (Otherwise I'd need to have > multiple lines changing one value each...) > > Thus, if the new label were very long and you wanted to change the width of > the control to accomodate it you could do > > label.configure(text='a very long message indeed', width=50) > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From bugcy013 at gmail.com Wed Feb 16 11:43:13 2011 From: bugcy013 at gmail.com (Ganesh Kumar) Date: Wed, 16 Feb 2011 16:13:13 +0530 Subject: [Tutor] Python GUI Tkinter Button arrangement In-Reply-To: References: Message-ID: Hi.. I am new to python , i have creating one application user agreement..using Tkinter, The Content of the agreement will reading one file...Agree button will click means enable next button. And activate script, Quit button for exit the program,, Dis agree means one warning message will show up.. all are working but one buttons are top of the screen. ?i want button in bottom of the frame plz. help me.. this my source code Source Code http://pastebin.com/Lm5teAtS Thanks in Advance -Ganesh. -- Did I learn something today? If not, I wasted it. From ahmedn82 at hotmail.com Wed Feb 16 12:46:56 2011 From: ahmedn82 at hotmail.com (Ahmed AL-Masri) Date: Wed, 16 Feb 2011 19:46:56 +0800 Subject: [Tutor] Python GUI Tkinter Button arrangement In-Reply-To: References: Message-ID: I suggest to use boa constructor if you are new learning. just google it. very easy tool to create your interface -------------------------------------------------- From: "Ganesh Kumar" Sent: Wednesday, February 16, 2011 6:43 PM To: Subject: [Tutor] Python GUI Tkinter Button arrangement > Hi.. > > I am new to python , i have creating one application user > agreement..using Tkinter, The Content > > of the agreement will reading one file...Agree button will click means > enable next button. And activate script, > > Quit button for exit the program,, Dis agree means one warning message > will show up.. > > all are working but one buttons are top of the screen. i want button > in bottom of the frame plz. help me.. > > this my source code > > > Source Code > > http://pastebin.com/Lm5teAtS > > Thanks in Advance > -Ganesh. > > > > > > -- > Did I learn something today? If not, I wasted it. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From rdmoores at gmail.com Wed Feb 16 18:39:36 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 16 Feb 2011 09:39:36 -0800 Subject: [Tutor] Python3 Tutorial question about a[:] = [] Message-ID: from : >>> # Clear the list: replace all items with an empty list >>> a[:] = [] >>> a [] I've been using >>> a = [] >>> a [] What's the difference? Thanks, Dick Moores From swiftone at swiftone.org Wed Feb 16 18:50:38 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Wed, 16 Feb 2011 12:50:38 -0500 Subject: [Tutor] Python3 Tutorial question about a[:] = [] In-Reply-To: References: Message-ID: On Wed, Feb 16, 2011 at 12:39 PM, Richard D. Moores wrote: > from : > >>>> # Clear the list: replace all items with an empty list >>>> a[:] = [] >>>> a > [] > > I've been using >>>> a = [] >>>> a > [] > > What's the difference? a = [] This sets the variable "a" to refer to a new list a[:] = [] This replaces the existing content of a with empty contents. Check out this example in interactive mode >>> a = [1,2,3] >>> b = a >>> a = [] >>> print a [] >>> print b [1, 2, 3] Versus: >>> a = [1,2,3] >>> b = a >>> a[:] = [] >>> print a [] >>> print b [] -- Brett Ritter / SwiftOne swiftone at swiftone.org From rdmoores at gmail.com Wed Feb 16 19:45:25 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 16 Feb 2011 10:45:25 -0800 Subject: [Tutor] Python3 Tutorial question about a[:] = [] In-Reply-To: References: Message-ID: On Wed, Feb 16, 2011 at 09:50, Brett Ritter wrote: > On Wed, Feb 16, 2011 at 12:39 PM, Richard D. Moores wrote: >> from : >> >>>>> # Clear the list: replace all items with an empty list >>>>> a[:] = [] >>>>> a >> [] >> >> I've been using >>>>> a = [] >>>>> a >> [] >> >> What's the difference? > > a = [] > > This sets the variable "a" to refer to a new list > > a[:] = [] > > This replaces the existing content of a with empty contents. > > Check out this example in interactive mode > >>>> a = [1,2,3] >>>> b = a >>>> a = [] >>>> print a > [] >>>> print b > [1, 2, 3] > > > Versus: > >>>> a = [1,2,3] >>>> b = a >>>> a[:] = [] >>>> print a > [] >>>> print b > [] Ah, got it! Thanks very much. Dick From alan.gauld at btinternet.com Thu Feb 17 00:47:09 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Feb 2011 23:47:09 -0000 Subject: [Tutor] Tkinter's Label References: Message-ID: "Emeka" wrote > Is the below the standard way of checking the content of Label in > "if" > statement? > > root = Tk() > label = Label(root , text = "pure") > > if label["pure"] == "pure": Almost, but the index should be 'text': if label["text"] == "pure": HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Feb 17 01:13:13 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Feb 2011 00:13:13 -0000 Subject: [Tutor] Python GUI Tkinter Button arrangement References: Message-ID: "Ganesh Kumar" wrote > I am new to python , i have creating one application user > agreement..using Tkinter, The Content > of the agreement will reading one file...Agree button will click > means > enable next button. And activate script, I'm assuming by User Agreement you mean User Interface? Maybe some translation software giving strange results? > all are working but one buttons are top of the screen. > i want button in bottom of the frame plz. help me.. It would help if you were a bit more explicit. Which button is in the wrong place? > this my source code > http://pastebin.com/Lm5teAtS There are lots of strange things here. Can I suggest you keep it as simple as possible to start with. And you should certainly not mix GUI tookits. You have Tkinter, wx and GTk all included here. If you use Tkinter stick with that. Also there is no real need for ttk here yet - once you get it working you can add some ttk to make it look pretty but for now I'd stick with plain old Tkinter. (In fact I'd do the same with PMW, but it does at least give you the scrolling text box...) I'm not sure what you think you are doing with the sys.path line: sys.path[:0] = ['../../..'] but I strongly suspect its not what you want! Also it will help if you give your widgets meaningful names. For example: widget = Tkinter.Button(self1, text='Next', command = lambda b='dhana': buttonPress(b) ) why not call it nextButton instead of widget. (personally I just add one or two letters so here it would be a b for Button and the name would be: bNext) It makes the code much easier to understand. You do it for the other buttons, why not that one? Also its usually better to keep all the widget construction in a single place. You have widgets being constructed in 2 different functions: init and initUI. I have no idea what defaultKey() is doing. It defines a function internally which is never used then calls the main Tk() function (I assume tk() is a mistake?) But Tk() should only be called once in an app. I think the line if a1 == 1: should be indented. Finally, it's slightly unusual in a Tkinter app to define the event handler functions inside the GUI building function. It will work but it does mean those evenmt handlers are invisible to the rest of the app which might limit your flexibility to reuse them later All in all it seems like a lot of complexity for what should be a very simple application. Of course you may be intending to change the structure to include much more complex handler functions later. But as it stands it seems complex for what it does. . HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ryan.strunk at gmail.com Thu Feb 17 04:33:29 2011 From: ryan.strunk at gmail.com (Ryan Strunk) Date: Wed, 16 Feb 2011 21:33:29 -0600 Subject: [Tutor] Working with some sort of Timer Message-ID: <5BAF30CF829E453B92152EA75414B4CE@RSTRUNKPC> Hello everyone, I'm a first-time poster and--in fact--first time programmer, so a lot of this is new to me. I hope to learn a lot about programming from this list, and I hope you all won't be shy about such feedback as "you're top-posting again, silly newbie." I am currently in the midst of producing an audio-only boxing game similar to Nintendo's Mike Tyson's Punch-Out!!, and I'm running into difficulty when it comes to working with timed events. I have begun developing a round class whose job it is to keep an eye on the clock and the match as a whole, checking for things like how long a fighter has been lying on the canvas. The relevant code currently looks like this: def heartbeat(self): if self.round_clock_counter > self.round_clock_max: #todo, call end_round return if global_vars.player.fatigue < 100: global_vars.player.fatigue += 1 self.round_clock = delay(1, heartbeat) (My delay function simply encompasses calling a Timer and starting it.) I am hoping to use the above-referenced self.round_clock as a measuring stick to call various punching methods which I programmed into an Opponent class. For example: at 1 minute, 30 seconds, perform maneuver x. It strikes me that using threading.Timer to set up all of the possible maneuvers would be an inelegant solution to the problem, but I'm not certain which other modules/functions I could use to better carry this out. My first question, then, pertains to the above implementation of a round clock. I know that this code can work, and it has the additional benefit of eventually keeping the round alive even when a fighter is being counted after the bell rings. At the same time, however, the code carries the burden of being infinitely recursive without the proper checks in place. Nevertheless, would the code generally be considered acceptable, or is there a more elegant solution I should use? Second, I would welcome any suggestions anyone has as to how I might time events within a round. Even pointers to specific modules or sections of the Python documentation would be greatly appreciated. Thank you all for any help you can provide, and I look forward to learning and growing with everyone. Best, Ryan From alan.gauld at btinternet.com Thu Feb 17 09:19:12 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Feb 2011 08:19:12 -0000 Subject: [Tutor] Working with some sort of Timer References: <5BAF30CF829E453B92152EA75414B4CE@RSTRUNKPC> Message-ID: "Ryan Strunk" wrote > def heartbeat(self): > if self.round_clock_counter > self.round_clock_max: > #todo, call end_round > return > if global_vars.player.fatigue < 100: > global_vars.player.fatigue += 1 > self.round_clock = delay(1, heartbeat) > > after the bell rings. At the same time, however, the code carries > the burden > of being infinitely recursive without the proper checks in place. Its not really recursive. It passes itself as an argument to timer which will eventually call it again. But that is not the same as recursion which actually makes the call inside the function. So this should not encounter the usual problems with recursive limits being reached. 'll leave others to comment on your other issues regarding the use of Threading.timer because I have no real experience of its use. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Thu Feb 17 22:19:21 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 17 Feb 2011 13:19:21 -0800 (PST) Subject: [Tutor] regex questions Message-ID: <634802.72877.qm@web110715.mail.gq1.yahoo.com> Hello, I have a couple of regex questions: 1 -- In the code below, how can I match the connecting words 'van de' , 'van der', etc. (all quite common in Dutch family names)? 2 -- It is quite hard to make a regex for all surnames, but easier to make regexes for the initials and the connecting words. How could I ' subtract' those two regexes to end up with something that matches the surnames (I used two .replaces() in my code, which roughly work, but I'm thinking there's a re way to do it, perhaps with carets (^). 3 -- Suppose I want to yank up my nerd rating by adding a re.NONDIACRITIC flag to the re module (matches letters independent of their accents), how would I go about? Should I subclass from re and implement the method, using the other existing methods as an example? I would find this a very useful addition. Thanks in advance for your thoughts! Python 2.7.0+ (r27:82500, Sep 15 2010, 18:04:55) [GCC 4.4.5] on linux2 >>> import re >>> names = ["J. van der Meer", "J. van den Meer", "J. van Meer", "Meer, J. van >>>der", "Meer, J. van den", "Meer, J. van de", "Meer, J. van"] >>> for name in names: print re.search("(van? de[nr]?)\b? ?", name, re.IGNORECASE).group(1) van der van den Traceback (most recent call last): File "", line 2, in print re.search("(van? de[nr]?)\b? ?", name, re.IGNORECASE).group(1) AttributeError: 'NoneType' object has no attribute 'group' Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Feb 18 04:45:42 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Feb 2011 14:45:42 +1100 Subject: [Tutor] regex questions In-Reply-To: <634802.72877.qm@web110715.mail.gq1.yahoo.com> References: <634802.72877.qm@web110715.mail.gq1.yahoo.com> Message-ID: <4D5DEB66.9040706@pearwood.info> Albert-Jan Roskam wrote: > Hello, > > I have a couple of regex questions: > > 1 -- In the code below, how can I match the connecting words 'van de' , 'van > der', etc. (all quite common in Dutch family names)? You need to step back a little bit and ask, what is this regex supposed to accomplish? What is your input data? Do you expect this to tell the difference between van used as a connecting word in a name, and van used otherwise? In other words, do you want: re.search(???, "J. van Meer") # matches re.search(???, "The van stopped") # doesn't match You might say, "Don't be silly, of course not!" *but* if you expect this regex to detect names in arbitrary pieces of text, that is exactly what you are hoping for. It is beyond the powers of a regex alone to distinguish between arbitrary text containing a name: "... and to my nephew Johann van Meer I leave my collection of books..." and arbitrary text without a name: "... and the white van merely touched the side of the building..." You need a proper parser for that. I will assume that your input data will already be names, and you just want to determine the connecting words: van der van den van de van wherever they appear. That's easy: the only compulsory part is "van": pattern = r"\bvan\b( de[rn]?)?" Note the use of a raw string. Otherwise, \b doesn't mean "backslash b", but instead means "ASCII backspace". Here's a helper function for testing: def search(pattern, string): mo = re.search(pattern, string, re.IGNORECASE) if mo: return mo.group(0) return "--no match--" And the result is: >>> names = ["J. van der Meer", "J. van den Meer", "J. van Meer", ... "Meer, J. van der", "Meer, J. van den", "Meer, J. van de", ... "Meer, J. van"] >>> >>> for name in names: ... print search(pattern, name) ... van der van den van van der van den van de van Don't forget to test things which should fail: >>> search(pattern, "Fred Smith") '--no match--' >>> search(pattern, "Fred Vanderbilt") '--no match--' > 2 -- It is quite hard to make a regex for all surnames, but easier to make "\b[a-z]+[-']?[a-z]*\b" should pretty much match all surnames using only English letters, apostrophes and hyphens. You can add in accented letters as need. (I'm lazy, so I haven't tested that.) > regexes for the initials and the connecting words. How could I ' subtract' > those two regexes to end up with something that matches the surnames (I used two > .replaces() in my code, which roughly work, but I'm thinking there's a re way to > do it, perhaps with carets (^). Don't try to use regexes to do too much. Regexes are a programming language, but the syntax is crap and there's a lot they can't do. They make a good tool for *parts* of your program, not the whole thing! The best approach, I think, is something like this: def detect_dutch_name(phrase): """Return (Initial, Connecting-words, Surname) from a potential Dutch name in the form "Initial [Connecting-words] Surname" or "Surname, Initial Connecting-words". """ pattern = ( r"(?P.*?), " r"(?P[a-z]\.) ?(?Pvan (de[rn]?))?" ) mo = re.match(pattern, phrase, re.IGNORECASE) if mo: return (mo.group('initial'), mo.group('connect') or '', mo.group('surname')) # Try again. pattern = ( r"(?P[a-z]\.) " r"(?Pvan (de[rn]? ))?(?P.*)" ) # Note: due to laziness, I accept any character at all in surnames. mo = re.match(pattern, phrase, re.IGNORECASE) if mo: return (mo.group('initial'), mo.group('connect') or '', mo.group('surname')) return ('', '', '') Note that this is BUGGY -- it doesn't do exactly what you want, although it is close: >>> detect_dutch_name("Meer, J. van der") # Works fine ('J.', 'van der', 'Meer') but: >>> detect_dutch_name("J. van der Meer") # almost, except for the space ('J.', 'van der ', 'Meer') >>> detect_dutch_name("J. van Meer") # not so good ('J.', '', 'van Meer') Debugging regexes is a PITA and I'm going to handball the hard part to you :) > 3 -- Suppose I want to yank up my nerd rating by adding a re.NONDIACRITIC flag > to the re module (matches letters independent of their accents), how would I go > about? Should I subclass from re and implement the method, using the other > existing methods as an example? I would find this a very useful addition. As would lots of people, but it's not easy, and it's not even certain to me that it is always meaningful. In English, and (I believe) Dutch, diacritics are modifiers, and so accented letters like ? are considered just a variant of e. (This is not surprising, for English is closely related to Dutch.) But this is not a general rule -- many languages which use diacritics consider the accented letters to be as distinct. See, for example, http://en.wikipedia.org/wiki/Diacritic for a discussion of which diacritics are considered different letters and which are not. You might like to read this: http://www.regular-expressions.info/unicode.html You can also look at "The Unicode Hammer" (a.k.a. "The Stupid American") recipe: http://code.activestate.com/recipes/251871-latin1-to-ascii-the-unicode-hammer/ Also this snippet: http://snippets.dzone.com/posts/show/5499 As for modifying the regex engine itself, it is written in C and is quite a complex beast. It's not just a matter of subclassing it, but feel free to try: >>> x = re.compile("x") >>> type(x) First warning -- the engine itself is flagged as a private implementation detail! >>> import _sre >>> class X(_sre.SRE_Pattern): ... pass ... Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'SRE_Pattern' Second warning -- the regex class is not available from the top level of the module. >>> class X(type(x)): ... pass ... Traceback (most recent call last): File "", line 1, in TypeError: type '_sre.SRE_Pattern' is not an acceptable base type And the final problem: the C-based type is not suitable for subclassing in pure Python. You could try using delegation, or working on it in C. Good luck! -- Steven From doggy_lollipop at hotmail.com Fri Feb 18 09:42:59 2011 From: doggy_lollipop at hotmail.com (lim chee siong) Date: Fri, 18 Feb 2011 16:42:59 +0800 Subject: [Tutor] urgent help required! invalid syntax Message-ID: Hi, I was writing a module for the black-scholes pricing model in python, but I keep getting this error message: Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\blackscholes.py", line 25 d2=d1-v*sqrt(t) This is the code in my blackscholes.py file:#Black-Scholes model import mathimport numpyimport scipy #Cumulative normal distribution def CND(x): (a1,a2,a3,a4,a5)=(0.31938153,-0.356563782,1.781477937,-1.821255978,1.330274429) L=abs(x) K=1.0/(1.0+0.2316419*L) w=1.0-1.0/sqrt(2*pi)*exp(-L*L/2)*(a1*K+a2*K*K+a3*pow(K,3)+a4*pow(K,4)+a5*pow(K,5)) if x<0: w=1.0-w return w #s: price of underlying stock x:strike price#r: continuously compounded risk free interest rate#t: time in years until expiration of option#v: implied volatility of underlying stock def dividend(s,x,r,t,v): d1=(log(s/x)+((r+v**2/2)*t)/(v*sqrt(t)) d2=d1-v*sqrt(t) def BS(s,x,r,t,v): c=s*CND(d1)-x*exp(-r*t)*CND(d2) p=x*exp(-r*t)*CND(-d2)-s*CND(-d1) delta=CND(d1)-1 gamma=CND(d1)/(s*v*sqrt(t)) vega=s*CND(d1)*sqrt(t) theta=-((s*CND(d1)*v)/(2*sqrt(t))+r*x*exp(-r*t)*CND(-d2) rho=-x*t*exp(-r*t)*CND(-d2) What is wrong here? What do I need to change? Thanks! Quick reply will be much appreciated because the deadline is tomorrow! -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Fri Feb 18 10:01:13 2011 From: timomlists at gmail.com (Timo) Date: Fri, 18 Feb 2011 10:01:13 +0100 Subject: [Tutor] urgent help required! invalid syntax In-Reply-To: References: Message-ID: <4D5E3559.3060409@gmail.com> On 18-02-11 09:42, lim chee siong wrote: > > > Hi, > > I was writing a module for the black-scholes pricing model in python, > but I keep getting this error message: > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python26\lib\blackscholes.py", line 25 > d2=d1-v*sqrt(t) That's not the whole traceback, is it? > > This is the code in my blackscholes.py file: > #Black-Scholes model > > [snip] > > def dividend(s,x,r,t,v): > d1=(log(s/x)+((r+v**2/2)*t)/(v*sqrt(t)) > d2=d1-v*sqrt(t) > > [snip] > > > What is wrong here? What do I need to change? Check the line before the line which throws a syntax error. Have a good look at it and you will see you are missing a character. Cheers, Timo > Thanks! Quick reply will be much appreciated because the deadline is > tomorrow! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From bigjohnexpress at gmail.com Fri Feb 18 01:31:19 2011 From: bigjohnexpress at gmail.com (John) Date: Thu, 17 Feb 2011 19:31:19 -0500 Subject: [Tutor] Odd behavior with eval, list comps, and name lookup Message-ID: I noticed some odd behavior relating to eval(). First, a baseline case for behavior: >>> def test(): ... x = 5 ... return [a for a in range(10) if a == x] ... >>> test() [5] So far so good. Now let's try eval: >>> c = compile('[a for a in range(10) if a == x]', '', 'single') >>> eval(c, globals(), {'x': 5}) Traceback (most recent call last): File "", line 1, in File "", line 1, in File "", line 1, in NameError: global name 'x' is not defined Looks like 'x' is searched for only among the globals, bypassing the locals. The same behavior is seen between exec and eval, with and without compile, and between 3.1.3 and 3.2rc2. Given simpler code without a list comp, the locals are used just fine: >>> c = compile('a=5; a==x', '', 'single') >>> eval(c, {}, {'x': 5}) True Could anyone help me understand these scoping rules? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Fri Feb 18 10:36:07 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 18 Feb 2011 01:36:07 -0800 (PST) Subject: [Tutor] regex questions In-Reply-To: <4D5DEB66.9040706@pearwood.info> References: <634802.72877.qm@web110715.mail.gq1.yahoo.com> <4D5DEB66.9040706@pearwood.info> Message-ID: <918766.79376.qm@web110711.mail.gq1.yahoo.com> Hi Steven, Thanks a BUNCH for helping me! Yes, you were correct in assuming that my input data are already names. They're names in a column in a csv file. They're the names of GPs, in various formats. Besides the forms I've mentioned already there are examples such as 'Doctor's office Duh, J. & Dah, J.', with or without initials and/or connecting words. There are also offices with names as Doctor's Office 'Under the Oaks'. I want to normalise those cases too till 'Doctor's office J. Duh & J. Dah', etc. Currently I use " & ".split() and apply my regexes (I use three, so I will certainly study your very fancy function!). So the raw string \b means means "ASCII backspace". Is that another way of saying that it means 'Word boundary'? You're right: debugging regexes is a PIA. One teeny weeny mistake makes all the difference. Could one say that, in general, it's better to use a Divide and Conquer strategy and use a series of regexes and other string operations to reach one's goal? http://code.activestate.com/recipes/251871-latin1-to-ascii-the-unicode-hammer/ is interesting. I did something similar with unicode.translate(). Many people here have their keyboard settings as US, so accented letters are not typed very easily, and are therefore likely to be omitted (e.g. enqu?te vs enquete). Thanks again! Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ________________________________ From: Steven D'Aprano To: Python Mailing List Sent: Fri, February 18, 2011 4:45:42 AM Subject: Re: [Tutor] regex questions Albert-Jan Roskam wrote: > Hello, > > I have a couple of regex questions: > > 1 -- In the code below, how can I match the connecting words 'van de' , 'van >der', etc. (all quite common in Dutch family names)? You need to step back a little bit and ask, what is this regex supposed to accomplish? What is your input data? Do you expect this to tell the difference between van used as a connecting word in a name, and van used otherwise? In other words, do you want: re.search(???, "J. van Meer") # matches re.search(???, "The van stopped") # doesn't match You might say, "Don't be silly, of course not!" *but* if you expect this regex to detect names in arbitrary pieces of text, that is exactly what you are hoping for. It is beyond the powers of a regex alone to distinguish between arbitrary text containing a name: "... and to my nephew Johann van Meer I leave my collection of books..." and arbitrary text without a name: "... and the white van merely touched the side of the building..." You need a proper parser for that. I will assume that your input data will already be names, and you just want to determine the connecting words: van der van den van de van wherever they appear. That's easy: the only compulsory part is "van": pattern = r"\bvan\b( de[rn]?)?" Note the use of a raw string. Otherwise, \b doesn't mean "backslash b", but instead means "ASCII backspace". Here's a helper function for testing: def search(pattern, string): mo = re.search(pattern, string, re.IGNORECASE) if mo: return mo.group(0) return "--no match--" And the result is: >>> names = ["J. van der Meer", "J. van den Meer", "J. van Meer", ... "Meer, J. van der", "Meer, J. van den", "Meer, J. van de", ... "Meer, J. van"] >>> >>> for name in names: ... print search(pattern, name) ... van der van den van van der van den van de van Don't forget to test things which should fail: >>> search(pattern, "Fred Smith") '--no match--' >>> search(pattern, "Fred Vanderbilt") '--no match--' > 2 -- It is quite hard to make a regex for all surnames, but easier to make "\b[a-z]+[-']?[a-z]*\b" should pretty much match all surnames using only English letters, apostrophes and hyphens. You can add in accented letters as need. (I'm lazy, so I haven't tested that.) > regexes for the initials and the connecting words. How could I ' subtract' >those two regexes to end up with something that matches the surnames (I used two >.replaces() in my code, which roughly work, but I'm thinking there's a re way to >do it, perhaps with carets (^). Don't try to use regexes to do too much. Regexes are a programming language, but the syntax is crap and there's a lot they can't do. They make a good tool for *parts* of your program, not the whole thing! The best approach, I think, is something like this: def detect_dutch_name(phrase): """Return (Initial, Connecting-words, Surname) from a potential Dutch name in the form "Initial [Connecting-words] Surname" or "Surname, Initial Connecting-words". """ pattern = ( r"(?P.*?), " r"(?P[a-z]\.) ?(?Pvan (de[rn]?))?" ) mo = re.match(pattern, phrase, re.IGNORECASE) if mo: return (mo.group('initial'), mo.group('connect') or '', mo.group('surname')) # Try again. pattern = ( r"(?P[a-z]\.) " r"(?Pvan (de[rn]? ))?(?P.*)" ) # Note: due to laziness, I accept any character at all in surnames. mo = re.match(pattern, phrase, re.IGNORECASE) if mo: return (mo.group('initial'), mo.group('connect') or '', mo.group('surname')) return ('', '', '') Note that this is BUGGY -- it doesn't do exactly what you want, although it is close: >>> detect_dutch_name("Meer, J. van der") # Works fine ('J.', 'van der', 'Meer') but: >>> detect_dutch_name("J. van der Meer") # almost, except for the space ('J.', 'van der ', 'Meer') >>> detect_dutch_name("J. van Meer") # not so good ('J.', '', 'van Meer') Debugging regexes is a PITA and I'm going to handball the hard part to you :) > 3 -- Suppose I want to yank up my nerd rating by adding a re.NONDIACRITIC flag >to the re module (matches letters independent of their accents), how would I go >about? Should I subclass from re and implement the method, using the other >existing methods as an example? I would find this a very useful addition. As would lots of people, but it's not easy, and it's not even certain to me that it is always meaningful. In English, and (I believe) Dutch, diacritics are modifiers, and so accented letters like ? are considered just a variant of e. (This is not surprising, for English is closely related to Dutch.) But this is not a general rule -- many languages which use diacritics consider the accented letters to be as distinct. See, for example, http://en.wikipedia.org/wiki/Diacritic for a discussion of which diacritics are considered different letters and which are not. You might like to read this: http://www.regular-expressions.info/unicode.html You can also look at "The Unicode Hammer" (a.k.a. "The Stupid American") recipe: http://code.activestate.com/recipes/251871-latin1-to-ascii-the-unicode-hammer/ Also this snippet: http://snippets.dzone.com/posts/show/5499 As for modifying the regex engine itself, it is written in C and is quite a complex beast. It's not just a matter of subclassing it, but feel free to try: >>> x = re.compile("x") >>> type(x) First warning -- the engine itself is flagged as a private implementation detail! >>> import _sre >>> class X(_sre.SRE_Pattern): ... pass ... Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'SRE_Pattern' Second warning -- the regex class is not available from the top level of the module. >>> class X(type(x)): ... pass ... Traceback (most recent call last): File "", line 1, in TypeError: type '_sre.SRE_Pattern' is not an acceptable base type And the final problem: the C-based type is not suitable for subclassing in pure Python. You could try using delegation, or working on it in C. Good luck! -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Feb 18 10:56:10 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Feb 2011 20:56:10 +1100 Subject: [Tutor] urgent help required! invalid syntax In-Reply-To: References: Message-ID: <4D5E423A.4080300@pearwood.info> lim chee siong wrote: > > > Hi, > I was writing a module for the black-scholes pricing model in python, but I keep getting this error message: > Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\blackscholes.py", line 25 d2=d1-v*sqrt(t) Please COPY AND PASTE the FULL error message, including the entire traceback. Do not re-type it, summarise it, simplify it, or change it in any other way. But my guess is that you're probably missing a closing bracket ) on that line, or the one before it. -- Steven From steve at pearwood.info Fri Feb 18 11:13:09 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Feb 2011 21:13:09 +1100 Subject: [Tutor] regex questions In-Reply-To: <918766.79376.qm@web110711.mail.gq1.yahoo.com> References: <634802.72877.qm@web110715.mail.gq1.yahoo.com> <4D5DEB66.9040706@pearwood.info> <918766.79376.qm@web110711.mail.gq1.yahoo.com> Message-ID: <4D5E4635.2090501@pearwood.info> Albert-Jan Roskam wrote: > So the raw string \b means means "ASCII backspace". Is that another way of > saying that it means 'Word boundary'? No. Python string literals use backslash escapes for special characters, similar to what many other computer languages, including C, do. So when you type "hello world\n" as a *literal* in source code, the \n doesn't mean backslash-n, but it means a newline character. The special escapes used by Python include: \0 NULL (ASCII code 0) \a BELL character (ASCII code 7) \b BACKSPACE (ASCII code 8) \n newline \t tab \r carriage return \' single quote (does not close string) \" double quote (does not close string) \\ backslash \0nn character with ASCII code nn in octal \xXX character with ASCII code XX in hex \b (backspace) doesn't have anything to do with word boundaries. Regexes, however, are a computer language in themselves, and they use an *actual backslash* to introduce special meaning. Because that backslash clashes with the use of backslashes in Python string literals, you have to work around the clash. You could do any of these: # Escape the backslash, so Python won't treat it as special: pattern = '\\bword\\b' # Use chr() to build up a non-literal string: pattern = chr(92) + 'bword' + chr(92) + 'b' # Use raw strings: pattern = r'\bword\b' The Python compiler treats backslashes as just an ordinary character when it compiles raw strings. So that's the simplest and best solution. > You're right: debugging regexes is a PIA. One teeny weeny mistake makes all the > difference. Could one say that, in general, it's better to use a Divide and > Conquer strategy and use a series of regexes and other string operations to > reach one's goal? Absolutely! -- Steven From __peter__ at web.de Fri Feb 18 11:16:52 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Feb 2011 11:16:52 +0100 Subject: [Tutor] Odd behavior with eval, list comps, and name lookup References: Message-ID: John wrote: > I noticed some odd behavior relating to eval(). First, a baseline case for > behavior: > >>>> def test(): > ... x = 5 > ... return [a for a in range(10) if a == x] > ... >>>> test() > [5] > > So far so good. Now let's try eval: > >>>> c = compile('[a for a in range(10) if a == x]', '', 'single') >>>> eval(c, globals(), {'x': 5}) > Traceback (most recent call last): > File "", line 1, in > File "", line 1, in > File "", line 1, in > NameError: global name 'x' is not defined > > Looks like 'x' is searched for only among the globals, bypassing the > locals. The same behavior is seen between exec and eval, with and without > compile, and between 3.1.3 and 3.2rc2. Given simpler code without a list > comp, the locals are used just fine: > >>>> c = compile('a=5; a==x', '', 'single') >>>> eval(c, {}, {'x': 5}) > True > > Could anyone help me understand these scoping rules? Thanks. Except for class definitions the compiler statically determines whether a variable is global or local (or a closure). List comprehensions and generator expressions are realized as functions; therefore they have their own local scope that you cannot provide via eval/exec. You could argue that in the following example >>> exec("x = 2; print([a for a in range(3) if a == x])", {}, {}) Traceback (most recent call last): File "", line 1, in File "", line 1, in File "", line 1, in NameError: global name 'x' is not defined the assignment x = 2 should give the compiler a clue that x is supposed to be a local name, just like in def f(): x = 2 print([a for a in range(3) if a == x]) My *guess* is that this is an implementation restriction rather than a conscious decision. It works for the common case of module-level code because there local and global namespace are identical: >>> exec("x = 2; print([a for a in range(3) if a == x])", {}) [2] Peter From eire1130 at gmail.com Fri Feb 18 15:27:59 2011 From: eire1130 at gmail.com (James Reynolds) Date: Fri, 18 Feb 2011 09:27:59 -0500 Subject: [Tutor] urgent help required! invalid syntax In-Reply-To: References: Message-ID: There's a few things I've noticed: 1. I would recommend using an IDE of some sort. I copy and pasted this into eclipse, and it told me straight away that you had a parenthesis problem on this line: d1=(log(s/x)+((r+v**2/2)*t)/(v*sqrt(t)) 2. Your function "dividend" isn't returning a value. 3. Unless there is more to the program that you haven't shown us, all of the math stuff that I can see, such as sqrt, pi, log, exp and possibly others I'm not thinking of should be prefixed with math.xxxx. 4. The function BS isn't returning anything. 5. Lastly, if you are a familiar with object oriented programing, the black scholes is better suited towards OOP. 2011/2/18 lim chee siong > > > Hi, > > I was writing a module for the black-scholes pricing model in python, but I > keep getting this error message: > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python26\lib\blackscholes.py", line 25 > d2=d1-v*sqrt(t) > > > This is the code in my blackscholes.py file: > #Black-Scholes model > > import math > import numpy > import scipy > > #Cumulative normal distribution > > def CND(x): > > (a1,a2,a3,a4,a5)=(0.31938153,-0.356563782,1.781477937,-1.821255978,1.330274429) > L=abs(x) > K=1.0/(1.0+0.2316419*L) > w=1.0-1.0/sqrt(2*pi)*exp(-L*L/2)*(a1*K+a2*K*K+a3*pow(K,3)+a4*pow(K,4)+a5*pow(K, > 5)) > if x<0: > w=1.0-w > return w > > #s: price of underlying stock x:strike price > #r: continuously compounded risk free interest rate > #t: time in years until expiration of option > #v: implied volatility of underlying stock > > def dividend(s,x,r,t,v): > d1=(log(s/x)+((r+v**2/2)*t)/(v*sqrt(t)) > d2=d1-v*sqrt(t) > > def BS(s,x,r,t,v): > c=s*CND(d1)-x*exp(-r*t)*CND(d2) > p=x*exp(-r*t)*CND(-d2)-s*CND(-d1) > delta=CND(d1)-1 > gamma=CND(d1)/(s*v*sqrt(t)) > vega=s*CND(d1)*sqrt(t) > theta=-((s*CND(d1)*v)/(2*sqrt(t))+r*x*exp(-r*t)*CND(-d2) > rho=-x*t*exp(-r*t)*CND(-d2) > > > What is wrong here? What do I need to change? Thanks! Quick reply will be > much appreciated because the deadline is tomorrow! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jyatesster at gmail.com Sat Feb 19 19:06:47 2011 From: jyatesster at gmail.com (jyatesster) Date: Sat, 19 Feb 2011 10:06:47 -0800 Subject: [Tutor] Having Troubles with For Loops Message-ID: I am refreshing my memory of Python programming after taking a class this past fall. I am using the book, *Python Programming for the absolute beginner*. I am at chapter 4, challenge 4 which instructs me to create a program that picks a random word and the player has to guess the word. The computer tells the player how mnay letters are in the word. Then the player gets five chances to ask if a letter is in the word. The computer can only respond with "yes" or "no." Then, the player must guess the word. Here is what I have so far. I think I am doing something wrong with the for loops as the program is not reading whether the letter is in the constant and giving the appropriate response. #Word Randomizer #This program picks the word and the user has to figure out what the computer #picked. The computer tells how many letters are in the word. The player #gets five chances to guess the correct word. import random # create a sequence of words to choose from PYTHON = "python" JUMBLES = "jumbles" EASY = "easy" DIFFICULT = "difficult" XYLOPHONES = "xylophones" WORDS = (PYTHON, JUMBLES, EASY, DIFFICULT, XYLOPHONES) # pick one word randomly from the sequence word = random.choice(WORDS) # create a variable to use later to see if the guess is correct correct = word #intial values tries = 1 max_tries = 5 #start the game print( """ Welcome to Word Randomizer! Guess the word the computer picks. (Press the enter key at the prompt to quit.) """ ) #The computer picks the word and gives a hint if correct == PYTHON: print ("This word has six letters.") elif correct == JUMBLES: print ("This word has seven letters.") elif correct == EASY: print ("This word has four letters.") elif correct == DIFFICULT: print ("This word has nine letters.") elif correct == XYLOPHONES: print ("This word has ten letters.") else: raw_input("Press Enter to Exit the Program.") guess_letter = raw_input("Guess a letter: ") #The player gets five chances to see if a letter is in the word. for letter in PYTHON: if letter.lower() not in PYTHON: print ("No") guess_letter = raw_input("Guess a letter: ") else: print ("Yes") guess_letter = raw_input("Guess a letter :") tries +=1 if tries == max_tries: guess_word = raw_input("Guess the word: ") for letter in JUMBLES: if letter.lower() not in JUMBLES: print ("No") guess_letter = raw_input("Guess a letter: ") else: print ("Yes") guess_letter = raw_input("Guess a letter :") tries +=1 if tries == max_tries: guess_word = raw_input("Guess the word: ") for letter in EASY: if letter.lower() not in EASY: print ("No") guess_letter = raw_input("Guess a letter: ") else: print ("Yes") guess_letter = raw_input("Guess a letter :") tries +=1 if tries == max_tries: guess_word = raw_input("Guess the word: ") for letter in DIFFICULT: if letter.lower() not in DIFFICULT: print ("No") guess_letter = raw_input("Guess a letter: ") else: print ("Yes") guess_letter = raw_input("Guess a letter :") tries +=1 if tries == max_tries: guess_word = raw_input("Guess the word: ") for letter in XYLOPHONES: if letter.lower() not in XYLOPHONES: print ("No") guess_letter = raw_input("Guess a letter: ") else: print ("Yes") guess_letter = raw_input("Guess a letter :") tries +=1 if tries == max_tries: guess_word = raw_input("Guess the word: ") -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Sat Feb 19 19:22:25 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 19 Feb 2011 13:22:25 -0500 Subject: [Tutor] Having Troubles with For Loops In-Reply-To: References: Message-ID: <4D600A61.6090308@aim.com> On 02/19/2011 01:06 PM, jyatesster wrote: > I am refreshing my memory of Python programming after taking a class this > past fall. I am using the book, *Python Programming for the absolute > beginner*. I am at chapter 4, challenge 4 which instructs me to create a > program that picks a random word and the player has to guess the word. The > computer tells the player how mnay letters are in the word. Then the player > gets five chances to ask if a letter is in the word. The computer can only > respond with "yes" or "no." Then, the player must guess the word. > > Here is what I have so far. I think I am doing something wrong with the for > loops as the program is not reading whether the letter is in the constant > and giving the appropriate response. > [snip] You're going about it wrong. You should look into the len() function. For example: print("This word has %d letters" % (len(word)) ) for i in range(5): letter = input("Guess a letter: ") if letter.lower() in word.lower(): print("Yes") else: print("No") Your for loops in the end don't do what you think they do. for letter in XYLOPHONES: # Loops through XYLOPHONES if letter.lower() not in XYLOPHONES: # Always will return false, print("No") # because you are looping through the word itself # etc. You are also mixing Python 3's print() with Python 2's raw_input(), so it's hard to tell which you are using. I'm assuming Python 2 because you didn't report the raw_input() failing. If that's the case, you don't need the ()'s around the text you are printing. I also suggest you look into lists and list indexing. You should go through the Python Tutorial [0] if you haven't before. [0] - http://docs.python.org/tutorial/ -- Corey Richardson I've never known any trouble which an hour's reading didn't assuage. -Charles De Secondat From alan.gauld at btinternet.com Sat Feb 19 20:15:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Feb 2011 19:15:58 -0000 Subject: [Tutor] Having Troubles with For Loops References: Message-ID: "jyatesster" wrote > Here is what I have so far. I think I am doing something wrong with > the for > loops as the program is not reading whether the letter is in the > constant > and giving the appropriate response. Instead of having us guess it would be useful if you told us (or better cut n paste) what actually happened and why you thought it was wrong. Besides helping us understand putting it in words will often help you to understand to the point of seeing the solution... > #Word Randomizer > import random > # create a sequence of words to choose from > PYTHON = "python" > JUMBLES = "jumbles" > EASY = "easy" > DIFFICULT = "difficult" > XYLOPHONES = "xylophones" > WORDS = (PYTHON, JUMBLES, EASY, DIFFICULT, XYLOPHONES) Its easier to ,miss out the constants and just do words = ('python', 'jumbles',....) > word = random.choice(WORDS) > # create a variable to use later to see if the guess is correct > correct = word You shouldn't need correct since you aren't changing word, so just use word directly. > #intial values > tries = 1 > max_tries = 5 You don't really need these either, see below... > > #The computer picks the word and gives a hint The comment is misleading since the computer picked the word further up. Move the random function to here... > if correct == PYTHON: > print ("This word has six letters.") > elif correct == JUMBLES: > print ("This word has seven letters.") You can use len(word) to get the letters without all the repetition. print "This word has", len(word), "letters" > guess_letter = raw_input("Guess a letter: ") > #The player gets five chances to see if a letter is in the word. > for letter in PYTHON: > if letter.lower() not in PYTHON: You need to use guess_letter not letter. letter will be each of the letters in 'python'... But you don't really want to test the guesses against python (unless python is the word). Better to just use word, and you don't need a loop over the letters you need a loop that repeats up 5 times: for try in range(5): > print ("No") > guess_letter = raw_input("Guess a letter: ") and then use 'in' to find out if the guess_letter is in the word > guess_word = raw_input("Guess the word: ") And you never check to see if the guessed word is the word!. So the user never actually wins or loses... You are heading in the right general direction but you are making it much more complex than it needs to be. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From delegbede at dudupay.com Sat Feb 19 20:33:54 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sat, 19 Feb 2011 19:33:54 +0000 Subject: [Tutor] Having Troubles with For Loops In-Reply-To: <4D600A61.6090308@aim.com> References: <4D600A61.6090308@aim.com> Message-ID: <213024826-1298144035-cardhu_decombobulator_blackberry.rim.net-453357617-@b18.c12.bise7.blackberry> To start with, you don't need to do so much for loop. You have already set the chosen word, word to correct. Every randomly selected word becomes the value of correct so, you need to only check for word in correct. So, after initiating the random selector, you print the number of letters in the word using the syntax like this: The player has 5 tries, depending on the approach you intend to adopt, you may not have to use max_tries. Say you go for the while loop. Set tries to 1 correct=word[random.randrange(len(word)-1)] word = a list of words you want the player to choose from print 'The word has %d letters' % len(correct) while tries <= 5: guess=raw_input('Guess a letter: ') if guess in correct: print 'yes' else: print 'no' tries += 1 What you would achieve with the above is that, immediately the player does 5 guesses, the game exits. How do you expect a player to guess a 7 letter word with just 5 tries. Second, the player should after 5 tries, if you insist on that, have a chance to guess the word itself assuming he has he has made two or three guesses, atleast give him a chance to make a wild guess. You can then tell him if he is right or wrong and go ahead to tell him the word. This is just a game logic from my own perspective. Do the necessary tweak to the cold. If there are other problems, please let's know. I hope this helps. Regards. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Corey Richardson Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Sat, 19 Feb 2011 13:22:25 To: Subject: Re: [Tutor] Having Troubles with For Loops On 02/19/2011 01:06 PM, jyatesster wrote: > I am refreshing my memory of Python programming after taking a class this > past fall. I am using the book, *Python Programming for the absolute > beginner*. I am at chapter 4, challenge 4 which instructs me to create a > program that picks a random word and the player has to guess the word. The > computer tells the player how mnay letters are in the word. Then the player > gets five chances to ask if a letter is in the word. The computer can only > respond with "yes" or "no." Then, the player must guess the word. > > Here is what I have so far. I think I am doing something wrong with the for > loops as the program is not reading whether the letter is in the constant > and giving the appropriate response. > [snip] You're going about it wrong. You should look into the len() function. For example: print("This word has %d letters" % (len(word)) ) for i in range(5): letter = input("Guess a letter: ") if letter.lower() in word.lower(): print("Yes") else: print("No") Your for loops in the end don't do what you think they do. for letter in XYLOPHONES: # Loops through XYLOPHONES if letter.lower() not in XYLOPHONES: # Always will return false, print("No") # because you are looping through the word itself # etc. You are also mixing Python 3's print() with Python 2's raw_input(), so it's hard to tell which you are using. I'm assuming Python 2 because you didn't report the raw_input() failing. If that's the case, you don't need the ()'s around the text you are printing. I also suggest you look into lists and list indexing. You should go through the Python Tutorial [0] if you haven't before. [0] - http://docs.python.org/tutorial/ -- Corey Richardson I've never known any trouble which an hour's reading didn't assuage. -Charles De Secondat _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From ben.ganzfried at gmail.com Sat Feb 19 21:49:06 2011 From: ben.ganzfried at gmail.com (Ben Ganzfried) Date: Sat, 19 Feb 2011 15:49:06 -0500 Subject: [Tutor] Tic-Tac-Toe Message-ID: Hey, I *think* that everything is working except my function gameWon. I keep getting the following error: " line 67, in gameWon if (cell % 3 == 0) and (self.__mycells[cell] == self.__mycells[cell + 1]) and (self.__mycells[cell + 1]== self.__mycells[cell + 2]): TypeError: unsupported operand type(s) for %: 'instance' and 'int' >>> " My thinking was the following: I wanted to check the verticals, horizontals, and diagonals to see if they were the same. If so, then the game is won. I'm not sure why I'm not actually comparing the value inside the appropriate cells, but clearly the error means that what I'm trying to do is not what is actually happening. My full code is below and I would greatly appreciate any help you can provide. Thanks, Ben _____________- #Ben Ganzfried #2/18/11 #Tic-Tac-Toe class Player: def __init__(self, name, type): self.__name = name self.__type = type def move(self): cell_index = input("%s's (%s) move: " & (self.__name, self.__type)) cell_index = int(cell_index) while cell_index > 8 and cell_index < 0: print("Please retry...") cell_index = input("%s's (%s) move: " & (self.__name, self.__type)) return cell_index def getName(self): return self.__name def getType(self): return self.__type class Board: def __init__(self): self.__mycells = [] for i in range(0, 9): current_cell = Cell() self.__mycells.append(current_cell) def print1(self): counter = 0 for cell in self.__mycells: cell.print1() counter +=1 if counter % 3 == 0: print("\n----") def setCellToX(self, cell_number): cell = self.__mycells[cell_number] if not cell.isOccupied(): cell.setToX() return True else: return False def setCelltoO(self, cell_number): cell = self.__mycells[cell_number] if not cell.isOccupied(): cell.setToO() return True else: return False def isTied(self): for cell in self.__mycells: if not cell.isOccupied(): return False return True def gameWon(self): for cell in self.__mycells: #horizontals if (cell % 3 == 0) and (self.__mycells[cell] == self.__mycells[cell + 1]) and (self.__mycells[cell + 1]== self.__mycells[cell + 2]): return True #verticals elif (cell < 3) and (self._mycells[cell] == self._mycells[cell + 3]) and (self._mycells[cell] == self.__mycells[cell + 6]): return True #diagonals elif (cell == 0) and (self.__mycells[cell] == self.__mycells[cell + 4]) and (self.__mycells[cell] == self.__mycells[cell + 8]): return True elif (cell == 2) and (self.__mycells[cell] == self.__mycells[cell + 2]) and (self.__mycells[cell] == self.mycells[cell + 4]): return True return False class Cell: def __init__(self): self.__value = " " def setToX(self): self.__value = "X" def setToO(self): self.__value = "O" def print1(self): print(self.__value,) #add a predicate (start in terms of question, not action) def isOccupied(self): return not self.__value == " " def main(): #initialize game #draw board #create two players #enter a loop-- prompt each player for a loop...stops when a player wins or a tie board = Board() board.print1() pX = Player("Ben", "X") pO = Player("Sam", "O") while not board.gameWon() and not board.isTied(): c1 = pX.move() success = board.setCellToX(c1) while not success: c1 = pX.move() success = board.setCellToX(c1) board.print1() c1 = pO.move() success = board.setCellToO(c1) while not success: c1 = pO.move() success = board.setCellToO(c1) board.print1() print("Game Over") if __name__ == "__main__": main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Feb 20 01:35:23 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 19 Feb 2011 19:35:23 -0500 Subject: [Tutor] Tic-Tac-Toe In-Reply-To: References: Message-ID: <4D6061CB.7070407@gmail.com> On 2/19/2011 3:49 PM, Ben Ganzfried wrote: > Hey, > > I *think* that everything is working except my function gameWon. I > keep getting the following error: " line 67, in gameWon > if (cell % 3 == 0) and (self.__mycells[cell] == > self.__mycells[cell + 1]) and (self.__mycells[cell + 1]== > self.__mycells[cell + 2]): > TypeError: unsupported operand type(s) for %: 'instance' and 'int' Learn to fish? unsupported operand type(s) for %: 'instance' and 'int' What is that telling you? Take a moment to read each word / symbol and relate it to the statement. PAUSE while you actually do that. If you figure it out hooray. The message is very explicit. If you are stuck then scroll down. Is there a % operator in the statement? Yes. The message tells you that its operand are of type instance and int. instance is the left operand type, int is the right operand type. Which of those types is not valid for %? PAUSE while you actually do that. If you figure it out hooray. The message is very explicit. If you are still stuck then scroll down. the expression being complained about is cell % 0 0 is an int, and that is OK for %. cell is an instance. Do you know why? instances are not valid for %. All of your references to cell in that statement and the ones following expect integers, not instances. You want to, as you say below, examine the cell value. > My thinking was the following: I wanted to check the verticals, > horizontals, and diagonals to see if they were the same. If so, then > the game is won. I'm not sure why I'm not actually comparing the > value inside the appropriate cells, but clearly the error means that > what I'm trying to do is not what is actually happening. My full code > is below and I would greatly appreciate any help you can provide. > > Thanks, > > Ben > > _____________- > > #Ben Ganzfried > #2/18/11 > #Tic-Tac-Toe > > class Player: > > > def __init__(self, name, type): > self.__name = name > self.__type = type > > def move(self): > cell_index = input("%s's (%s) move: " & (self.__name, > self.__type)) > cell_index = int(cell_index) > while cell_index > 8 and cell_index < 0: > print("Please retry...") > cell_index = input("%s's (%s) move: " & (self.__name, > self.__type)) > return cell_index > > def getName(self): > return self.__name > > def getType(self): > return self.__type > > class Board: > > def __init__(self): > self.__mycells = [] > for i in range(0, 9): > current_cell = Cell() > self.__mycells.append(current_cell) > > def print1(self): > counter = 0 > for cell in self.__mycells: > cell.print1() > counter +=1 > if counter % 3 == 0: > print("\n----") > > def setCellToX(self, cell_number): > cell = self.__mycells[cell_number] > if not cell.isOccupied(): > cell.setToX() > return True > else: > return False > > def setCelltoO(self, cell_number): > cell = self.__mycells[cell_number] > if not cell.isOccupied(): > cell.setToO() > return True > else: > return False > > def isTied(self): > for cell in self.__mycells: > if not cell.isOccupied(): > return False > return True > > def gameWon(self): > for cell in self.__mycells: > #horizontals > if (cell % 3 == 0) and (self.__mycells[cell] == > self.__mycells[cell + 1]) and (self.__mycells[cell + 1]== > self.__mycells[cell + 2]): > return True > #verticals > elif (cell < 3) and (self._mycells[cell] == > self._mycells[cell + 3]) and (self._mycells[cell] == > self.__mycells[cell + 6]): > return True > #diagonals > elif (cell == 0) and (self.__mycells[cell] == > self.__mycells[cell + 4]) and (self.__mycells[cell] == > self.__mycells[cell + 8]): > return True > elif (cell == 2) and (self.__mycells[cell] == > self.__mycells[cell + 2]) and (self.__mycells[cell] == > self.mycells[cell + 4]): > return True > return False > > > class Cell: > > def __init__(self): > self.__value = " " > > def setToX(self): > self.__value = "X" > > def setToO(self): > self.__value = "O" > > def print1(self): > print(self.__value,) > #add a predicate (start in terms of question, not action) > def isOccupied(self): > return not self.__value == " " > > def main(): > #initialize game > #draw board > #create two players > #enter a loop-- prompt each player for a loop...stops when a > player wins or a tie > board = Board() > board.print1() > pX = Player("Ben", "X") > pO = Player("Sam", "O") > while not board.gameWon() and not board.isTied(): > c1 = pX.move() > success = board.setCellToX(c1) > while not success: > c1 = pX.move() > success = board.setCellToX(c1) > board.print1() > c1 = pO.move() > success = board.setCellToO(c1) > while not success: > c1 = pO.move() > success = board.setCellToO(c1) > board.print1() > print("Game Over") > > > > if __name__ == "__main__": > main() > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 20 01:34:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Feb 2011 00:34:54 -0000 Subject: [Tutor] Tic-Tac-Toe References: Message-ID: "Ben Ganzfried" wrote > if (cell % 3 == 0) and (self.__mycells[cell] == > self.__mycells[cell + > 1]) and (self.__mycells[cell + 1]== self.__mycells[cell + 2]): > TypeError: unsupported operand type(s) for %: 'instance' and 'int' The error is in the first expression and the message tells you what is wrong. You are trying to use the % operator on an instance. Looking at your code, sure enough... > def gameWon(self): > for cell in self.__mycells: > if (cell % 3 == 0) and (self.__mycells[cell] == cell is one of __mycells which are objects. You need to rethink this test. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Sun Feb 20 05:06:11 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 19 Feb 2011 23:06:11 -0500 Subject: [Tutor] Tic-Tac-Toe In-Reply-To: References: Message-ID: <4D609333.9090400@gmail.com> I got stimulated to create a minimal tic-tac-toe program. No functions, no classes. board = [" "]*9 player = 'X' prompt = "Player %s cell #, Q=quit, B=display board>" while True: cell = raw_input(prompt % player) if cell in 'qQ': break elif cell in 'bB': print ('+---+' + '\n|%s%s%s|'*3 + '\n+---+') % tuple(board) elif not(len(cell) == 1 and cell.isdigit() and '1' <= cell <= '9'): print "Cell must be a number between 1 and 9." elif board[int(cell)-1] != " ": print "Cell is occupied." else: board[int(cell)-1] = player if any(1 for a,b,c in ((0,3,1), (3,6,1), (6,9,1), (0,7,3), (1,8,3), (2,9,3), (0,9,4), (2,7,2)) if board[a:b:c] == [player]*3): print player, "wins" break player = 'O' if player == 'X' else 'X' -- Bob Gailer 919-636-4239 Chapel Hill NC From max at niecap.com Sun Feb 20 05:14:46 2011 From: max at niecap.com (Max Niederhofer) Date: Sun, 20 Feb 2011 04:14:46 +0000 Subject: [Tutor] dict['_find'] Message-ID: Hello all, first post, please be gentle. I'm having serious trouble finding an alternative for the deprecated find module for dictionaries. The code (from Zed Shaw's Hard Way, exercise 40) goes something like this. Hope indentation survives. cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} def find_city(themap, state): if state in themap: return themap[state] else: return "Not found." cities['_find'] = find_city while True: print "State? (ENTER to quit)", state = raw_input("> ") if not state: break city_found = cities['_find'](cities, state) print city_found My question is - how do I rewrite this using an alternate module given find is deprecated? Grateful for all suggestions or pointers. For reference, I'm using 2.6.1 on darwin. Thanks so much for your help. Best, Max -- Dr. Maximilian Niederhofer Founder, Qwerly http://qwerly.com/ | http://qwerly.com/max +44 78 3783 8227 From steve at pearwood.info Sun Feb 20 06:20:10 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 20 Feb 2011 16:20:10 +1100 Subject: [Tutor] dict['_find'] In-Reply-To: References: Message-ID: <4D60A48A.5080904@pearwood.info> Max Niederhofer wrote: > Hello all, > > first post, please be gentle. I'm having serious trouble finding an > alternative for the deprecated find module for dictionaries. What find module for dictionaries? > The code (from Zed Shaw's Hard Way, exercise 40) goes something like > this. Hope indentation survives. > > cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} > > def find_city(themap, state): > if state in themap: > return themap[state] > else: > return "Not found." > > cities['_find'] = find_city What is the purpose of this? You have a dictionary called "cities" that contains four items. The first three are pairs of State:City, which makes sense. The fourth is a pair of the word "_find" matched with a function find_city. I don't understand what the purpose of this is. > while True: > print "State? (ENTER to quit)", > state = raw_input("> ") > if not state: break > > city_found = cities['_find'](cities, state) > print city_found I think you need to include the actual search inside the while loop. Otherwise, the loop keeps asking for a new state, but doesn't do anything with it until you exit the loop. while True: print "State? (ENTER to quit)", state = raw_input("> ") if not state: break city_found = cities['_find'](cities, state) print city_found But I don't understand the purpose of placing the function inside the dictionary. Much clearer and simpler is: while True: print "State? (ENTER to quit)", state = raw_input("> ") if not state: break print find_city(cities, state) -- Steven From alan.gauld at btinternet.com Sun Feb 20 10:32:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Feb 2011 09:32:56 -0000 Subject: [Tutor] dict['_find'] References: Message-ID: "Max Niederhofer" wrote > first post, please be gentle. I'm having serious trouble finding an > alternative for the deprecated find module for dictionaries. I think you are misunderstanding some of the terminology. There is no deprecated find module. You are not using any modules in your code. And you are not doing anything special with "_fnd", it is just a string which you use as a key in your dictionary. > cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': > 'Jacksonville'} > > def find_city(themap, state): > if state in themap: > return themap[state] > else: > return "Not found." > > cities['_find'] = find_city What this does is assign the function find_city as the value corresponding to the key "_find" in your dictionary. You could use any name you like: 'check' would be one meaningful example... However, there is no obvious reason to put the function in the dictionary at all...? > while True: > print "State? (ENTER to quit)", > state = raw_input("> ") > > if not state: break This loops round collecting state names from the user and throwing them away until the user eventually gets fed up and hits enter. At that point state holds an empty string. I don't think you want that. > city_found = cities['_find'](cities, state) > print city_found I think you want this inside the loop above... > My question is - how do I rewrite this using an alternate module > given > find is deprecated? '_find' is just a key, as such it is not deprecated. What made you think it was? Did you get an error message? If so always post the entire error text, it helps us enormously. > reference, I'm using 2.6.1 on darwin. With the slight change to the indentyation of the last two lines your code should work. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From knacktus at googlemail.com Sun Feb 20 10:40:18 2011 From: knacktus at googlemail.com (Knacktus) Date: Sun, 20 Feb 2011 10:40:18 +0100 Subject: [Tutor] dict['_find'] In-Reply-To: References: Message-ID: <4D60E182.8060807@googlemail.com> Am 20.02.2011 05:14, schrieb Max Niederhofer: > Hello all, Hello Max, > > first post, please be gentle. I'm having serious trouble finding an > alternative for the deprecated find module for dictionaries. > > The code (from Zed Shaw's Hard Way, exercise 40) goes something like > this. Hope indentation survives. > > cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} I use a naming convention for dicts that has made me very happy on several occasion ;-): key_to_value, in your case state_to_city = {...} > > def find_city(themap, state): > if state in themap: > return themap[state] > else: > return "Not found." > > cities['_find'] = find_city Did you put this entry into the same dictionary as the data on purpose? Or is the purpose a kind of dispatch? Something that could be a dict on its own, like private_function_name_to_function = {'_find': find_city} You should try to keep things seperate and explicit. > > while True: > print "State? (ENTER to quit)", > state = raw_input("> ") > > if not state: break > > city_found = cities['_find'](cities, state) > print city_found > > My question is - how do I rewrite this using an alternate module given > find is deprecated? Grateful for all suggestions or pointers. For > reference, I'm using 2.6.1 on darwin. > > Thanks so much for your help. > > Best, > Max > > -- > Dr. Maximilian Niederhofer > Founder, Qwerly > http://qwerly.com/ | http://qwerly.com/max > +44 78 3783 8227 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From max at niecap.com Sun Feb 20 14:30:40 2011 From: max at niecap.com (Max Niederhofer) Date: Sun, 20 Feb 2011 13:30:40 +0000 Subject: [Tutor] dict['_find'] In-Reply-To: <4D60E182.8060807@googlemail.com> References: <4D60E182.8060807@googlemail.com> Message-ID: Steven, Alan, Knacktus, thanks for your help. I was indeed very confused because I thought '_find' was calling something special instead of just being added to the dictionary (the confusion stemming from http://www.python.org/dev/peps/pep-0004/ where find module is obsolete). When I ran the code, the error I got was: max:python max$ python ex40.py State? (ENTER to quit) > CA Traceback (most recent call last): File "ex40.py", line 22, in city_found = cities['_find'](cities, state) File "ex40.py", line 8, in find_city return themap(state) TypeError: 'dict' object is not callable Two main mistakes: (1) not including the actual search in the while loop and (2) wrong parentheses in return themap(state) instead of return themap[state]. Fixed version which runs: cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} def find_city(themap, state): if state in themap: return themap[state] else: return "Not found." cities['_find'] = find_city while True: print "State? (ENTER to quit)", state = raw_input ("> ") if not state: break city_found = cities['_find'](cities, state) print city_found Thanks for your help, especially the comments about keeping things separate and explicit. Now to find out why Zed Shaw thinks this is a good way of doing it... Best, Max On Sun, Feb 20, 2011 at 9:40 AM, Knacktus wrote: > Am 20.02.2011 05:14, schrieb Max Niederhofer: > >> Hello all, > > Hello Max, >> >> first post, please be gentle. I'm having serious trouble finding an >> alternative for the deprecated find module for dictionaries. >> >> The code (from Zed Shaw's Hard Way, exercise 40) goes something like >> this. Hope indentation survives. >> >> cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} > > I use a naming convention for dicts that has made me very happy on several > occasion ;-): > key_to_value, in your case > state_to_city = {...} >> >> def find_city(themap, state): >> ? ? if state in themap: >> ? ? ? ? return themap[state] >> ? ? else: >> ? ? ? ? return "Not found." >> >> cities['_find'] = find_city > > Did you put this entry into the same dictionary as the data on purpose? > Or is the purpose a kind of dispatch? Something that could be a dict on its > own, like > private_function_name_to_function = {'_find': find_city} > You should try to keep things seperate and explicit. >> >> while True: >> ? ? print "State? (ENTER to quit)", >> ? ? state = raw_input("> ?") >> >> ? ? if not state: break >> >> city_found = cities['_find'](cities, state) >> print city_found >> >> My question is - how do I rewrite this using an alternate module given >> find is deprecated? Grateful for all suggestions or pointers. For >> reference, I'm using 2.6.1 on darwin. >> >> Thanks so much for your help. >> >> Best, >> Max >> >> -- >> Dr. Maximilian Niederhofer >> Founder, Qwerly >> http://qwerly.com/ | http://qwerly.com/max >> +44 78 3783 8227 >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Dr. Maximilian Niederhofer Founder, Qwerly http://qwerly.com/ | http://qwerly.com/max +44 78 3783 8227 From brightstaar385 at yahoo.com Sun Feb 20 19:03:32 2011 From: brightstaar385 at yahoo.com (shaheryar ali) Date: Sun, 20 Feb 2011 10:03:32 -0800 (PST) Subject: [Tutor] how to connect to Django's irc In-Reply-To: References: Message-ID: <195691.93370.qm@web110101.mail.gq1.yahoo.com> hi guys, does anyone know how to connect to the Django's irc, As django is based on python there asking from you guys, thanks ________________________________ From: Alan Gauld To: tutor at python.org Sent: Wed, January 19, 2011 8:04:23 PM Subject: Re: [Tutor] Decoding from strange symbols "Oleg Oltar" wrote > I am trying to decode a string I took from file: > > file = open ("./Downloads/lamp-post.csv", 'r') I assume you know what its supposed to represent? What the columns etc are intended to be? Otherwise it will be a challenge! There is a section here that looks like the months of the year (English) in reverse: \x00S\x00e\x00a\x00r\x00c\x00h\x00e\x00s\x00\t\x00D\x00e\x00c\x00 \x002\x000\x001\x000\x00\t\x00N\x00o\x00v\x00 \x002\x000\x001\x000\x00\t\x00O\x00c\x00t\x00 \x002\x000\x001\x000\x00\t\x00S\x00e\x00p\x00 \x002\x000\x001\x000\x00\t\x00A\x00u\x00g\x00 \x002\x000\x001\x000\x00\t\x00J\x00u\x00l\x00 \x002\x000\x001\x000\x00\t\x00J\x00u\x00n\x00 \x002\x000\x001\x000\x00\t\x00M\x00a\x00y\x00 \x002\x000\x001\x000\x00\t\x00A\x00p\x00r\x00 \x002\x000\x001\x000\x00\t\x00M\x00a\x00r\x00 \x002\x000\x001\x000\x00\t\x00F\x00e\x00b\x00 \x002\x000\x001\x000\x00\t\x00J\x00a\x00n\x00 Otherwise its all a bit arbitrary... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Sun Feb 20 20:32:21 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 20 Feb 2011 14:32:21 -0500 Subject: [Tutor] how to connect to Django's irc In-Reply-To: <195691.93370.qm@web110101.mail.gq1.yahoo.com> References: <195691.93370.qm@web110101.mail.gq1.yahoo.com> Message-ID: <4D616C45.8080500@aim.com> On 02/20/2011 01:03 PM, shaheryar ali wrote: > hi guys, > > does anyone know how to connect to the Django's irc, > As django is based on python there asking from you guys, > > > thanks > Point your favorite client at irc.freenode.net or use http://webchat.freenode.net/. #django You'll have better luck with django-specific questions on the django mailing list. -- Corey Richardson I've never known any trouble which an hour's reading didn't assuage. -Charles De Secondat From bgailer at gmail.com Sun Feb 20 20:34:25 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 20 Feb 2011 14:34:25 -0500 Subject: [Tutor] how to connect to Django's irc In-Reply-To: <195691.93370.qm@web110101.mail.gq1.yahoo.com> References: <195691.93370.qm@web110101.mail.gq1.yahoo.com> Message-ID: <4D616CC1.6060704@gmail.com> On 2/20/2011 1:03 PM, shaheryar ali wrote: > hi guys, > > does anyone know how to connect to the Django's irc, > As django is based on python there asking from you guys, > > > thanks > I don't know BUT what is the relevance of the following to your question? If it is not relevant why did you include it? Please in the future start a new email - do NOT spring off an existing one. > ------------------------------------------------------------------------ > *From:* Alan Gauld > *To:* tutor at python.org > *Sent:* Wed, January 19, 2011 8:04:23 PM > *Subject:* Re: [Tutor] Decoding from strange symbols > > > "Oleg Oltar" > wrote > > I am trying to decode a string I took from file: > > > > file = open ("./Downloads/lamp-post.csv", 'r') > > I assume you know what its supposed to represent? What the columns etc > are intended to be? Otherwise it will be a challenge! > > There is a section here that looks like the months of the year > (English) in reverse: > > > \x00S\x00e\x00a\x00r\x00c\x00h\x00e\x00s\x00\t\x00D\x00e\x00c\x00 > \x002\x000\x001\x000\x00\t\x00N\x00o\x00v\x00 > \x002\x000\x001\x000\x00\t\x00O\x00c\x00t\x00 > \x002\x000\x001\x000\x00\t\x00S\x00e\x00p\x00 > \x002\x000\x001\x000\x00\t\x00A\x00u\x00g\x00 > \x002\x000\x001\x000\x00\t\x00J\x00u\x00l\x00 > \x002\x000\x001\x000\x00\t\x00J\x00u\x00n\x00 > \x002\x000\x001\x000\x00\t\x00M\x00a\x00y\x00 > \x002\x000\x001\x000\x00\t\x00A\x00p\x00r\x00 > \x002\x000\x001\x000\x00\t\x00M\x00a\x00r\x00 > \x002\x000\x001\x000\x00\t\x00F\x00e\x00b\x00 > \x002\x000\x001\x000\x00\t\x00J\x00a\x00n\x00 > > Otherwise its all a bit arbitrary... > > HTH, > > > -- Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Feb 20 20:37:34 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 20 Feb 2011 14:37:34 -0500 Subject: [Tutor] tic tac toe In-Reply-To: References: Message-ID: <4D616D7E.4010602@gmail.com> On 2/20/2011 9:49 AM, Ben Ganzfried wrote: > Thanks, Bob. I'd love some specific feedback. Exactly what did I offer that you found useful? Also please always reply-all so a copy goes to the list. -- Bob Gailer 919-636-4239 Chapel Hill NC From wallenpb at gmail.com Mon Feb 21 00:12:20 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sun, 20 Feb 2011 17:12:20 -0600 Subject: [Tutor] creating classes while coding Message-ID: I know that Python not only supports OOP, but is fundamentally OOP in its design. Just in using the language and standard library, that much becomes obvious. However, I do wonder a bit about the practice I have seen of some Python programmers to implement relatively short bits of code, that would be quite simple using functions and procedural code, with classes. Some such code appears far more complicated than the job at hand really demands. I know there is not always a single right or wrong way of accomplishing programming task, but why implement using classes unnecessarily? When is it necessary? When is it best practice? I'll freely admit that I do not come from an OOP programming background, so designing classes is not my first impulse when writing code. Am I missing something? --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From amonroe at columbus.rr.com Mon Feb 21 02:01:46 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 20 Feb 2011 20:01:46 -0500 Subject: [Tutor] creating classes while coding In-Reply-To: References: Message-ID: <116823553697.20110220200146@columbus.rr.com> > I'll freely admit that I do not come from an OOP programming > background, so designing classes is not my first impulse when > writing code. Am I missing something? In my book, no, you're not missing something. I refer to it as "drinking the OO kool-aid". It's not compulsory. I just use it when it makes sense. Alan From wallenpb at gmail.com Mon Feb 21 02:20:37 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sun, 20 Feb 2011 19:20:37 -0600 Subject: [Tutor] creating classes while coding In-Reply-To: <116823553697.20110220200146@columbus.rr.com> References: <116823553697.20110220200146@columbus.rr.com> Message-ID: That raises my next question. Under what sort of programming circumstances does it make sense? --Bill On Sun, Feb 20, 2011 at 19:01, R. Alan Monroe wrote: > > I'll freely admit that I do not come from an OOP programming > > background, so designing classes is not my first impulse when > > writing code. Am I missing something? > > In my book, no, you're not missing something. I refer to it as > "drinking the OO kool-aid". It's not compulsory. I just use it when it > makes sense. > > Alan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 21 02:59:47 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Feb 2011 01:59:47 -0000 Subject: [Tutor] creating classes while coding References: Message-ID: "Bill Allen" wrote > However, I do wonder a bit about the practice I have seen of some > Python programmers to implement relatively short bits of code, that > would be > quite simple using functions and procedural code, with classes. OOP is often overkill, but if its the normal way of programming - and for many recent students its all they get taught - then using classes is the natural approach. "When all you have is a hammer everything looks like a nail..." However, there may be good reasons. Classes make reuse easier, in general, than functions. So if the task may become a building block for a future project, or even an extended version of the current one then building a class makes sense. > code appears far more complicated than the job at hand really > demands. I > know there is not always a single right or wrong way of > accomplishing > programming task, but why implement using classes unnecessarily? Why do anything unnecessarily? 1) You may not know another way. 2) You may have an extended use case in mind that is not directly related to the task at hand 3) Somebody said it was "the right way to do it" 4) A learning exercise (do we really need so many text editors?!) 5) Obstinacy - I've started so I'll finish! and probably more... > When is it necessary? When is it best practice? When reuse is an issue, When multiple instances of the problem need to be created (think parallel processing), When it has to fit with a bigger project context (which is using OOP). When objects naturally fit a complex problem domain - think GUIs. > I'll freely admit that I do not come from an OOP programming > background, so designing classes is not my first > impulse when writing code. Am I missing something? Yes, but not as much as you might think! But when you do start to think OOP before functions you will probably find it less surprising! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wallenpb at gmail.com Mon Feb 21 03:36:54 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sun, 20 Feb 2011 20:36:54 -0600 Subject: [Tutor] creating classes while coding In-Reply-To: References: Message-ID: On Sun, Feb 20, 2011 at 19:59, Alan Gauld wrote: > > "Bill Allen" wrote > > > However, I do wonder a bit about the practice I have seen of some >> Python programmers to implement relatively short bits of code, that would >> be >> quite simple using functions and procedural code, with classes. >> > > OOP is often overkill, but if its the normal way of programming > - and for many recent students its all they get taught - then using > classes is the natural approach. "When all you have is a hammer > everything looks like a nail..." However, there may be good reasons. > Classes make reuse easier, in general, than functions. So if the > task may become a building block for a future project, or even > an extended version of the current one then building a class > makes sense. > Thanks for the feedback. Particularly when it comes to reuse of code, I can see it could be worth my time to look into designing classes a bit more. I am starting to write enough code now that I am beginning to reuse some bits of it regularly. I have not yet taken the reuse of code further than packaging up some functions into modules. I'll look into this further. You mentioned the programming methods being taught programming students nowadays. That OOP is a basic programming method being taught sure leaves me in the dust. The last formal programming class I took in college was way back in the early 90s and it was to learn IBM 370 Assembly Language. OOP was not only not on the radar, it was not even in the same solar system! :-D feeling kinda old, and I am not all that old... --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafadurancastaneda at gmail.com Mon Feb 21 10:02:19 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Mon, 21 Feb 2011 10:02:19 +0100 Subject: [Tutor] Rebuild jpg Message-ID: Hi all, I'm using Python 3.1 and I have an image of an animal that has been broken it into many narrow vertical stripe images, and now i want to rebuild the original one, how can i get it? P.S.: It's not homework, but i'd prefer just some help rather than the whole sollution -------------- next part -------------- An HTML attachment was scrubbed... URL: From liam at steelsky.co.nz Mon Feb 21 10:21:38 2011 From: liam at steelsky.co.nz (Liam Clarke-Hutchinson) Date: Mon, 21 Feb 2011 22:21:38 +1300 Subject: [Tutor] Rebuild jpg In-Reply-To: References: Message-ID: Hi Rafael, Do you need to use Python 3.x? If you can use Python 2.6, the Python Imaging Library is a great image manipulation module. http://www.pythonware.com/products/pil/ Regards, Liam Clarke 2011/2/21 Rafael Dur?n Casta?eda > Hi all, > > I'm using Python 3.1 and I have an image of an animal that has been broken > it into many narrow vertical stripe images, and now i want to rebuild the > original one, how can i get it? > > P.S.: It's not homework, but i'd prefer just some help rather than the > whole sollution > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From japhy at pearachute.com Mon Feb 21 03:52:33 2011 From: japhy at pearachute.com (Japhy Bartlett) Date: Sun, 20 Feb 2011 21:52:33 -0500 Subject: [Tutor] creating classes while coding In-Reply-To: References: Message-ID: I think OOP makes it easy for new programmers to set up programs, and it can make for some pretty neat English looking code, but a more functional approach generally makes for much leaner, faster performing code. I find them most useful when you have several functions that might need to share some variables that the rest of the program doesn't care about, especially if you might need to load that information at run-time. Just my two cents though, this is mostly a personal style thing, if your code works. :) - Japhy On Sun, Feb 20, 2011 at 9:36 PM, Bill Allen wrote: > On Sun, Feb 20, 2011 at 19:59, Alan Gauld wrote: >> >> "Bill Allen" wrote >> >>> However, I do wonder a bit about the practice I have seen of some >>> Python programmers to implement relatively short bits of code, that would >>> be >>> quite simple using functions and procedural code, with classes. >> >> OOP is often overkill, but if its the normal way of programming >> - and for many recent students its all they get taught - then using >> classes is the natural approach. "When all you have is a hammer >> everything looks like a nail..." However, there may be good reasons. >> Classes make reuse easier, in general, than functions. So if the >> task may become a building block for a future project, or even >> an extended version of the current one then building a class >> makes sense. > > Thanks for the feedback. ? Particularly when it comes to reuse of code, I > can see it could be worth my time to look into designing classes a bit more. > ? I am starting to write enough code now that I am beginning to reuse some > bits of it regularly.? I have not yet taken the reuse of code further than > packaging up some functions into modules.? I'll look into this further. > > You mentioned the programming methods being taught programming students > nowadays.?? That OOP is a basic programming method being taught sure leaves > me in the dust.?? The last formal programming class I took in college was > way back in the early 90s and it was to learn IBM 370 Assembly Language. > OOP was not only not on the radar, it was not even in the same solar > system!??? :-D > > feeling kinda old, and I am not all that old... > > --Bill > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From steve at pearwood.info Mon Feb 21 12:44:04 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Feb 2011 22:44:04 +1100 Subject: [Tutor] creating classes while coding In-Reply-To: References: Message-ID: <4D625004.5020602@pearwood.info> Bill Allen wrote: > I know that Python not only supports OOP, but is fundamentally OOP in its > design. Just in using the language and standard library, that much becomes > obvious. However, I do wonder a bit about the practice I have seen of some > Python programmers to implement relatively short bits of code, that would be > quite simple using functions and procedural code, with classes. Some such > code appears far more complicated than the job at hand really demands. I > know there is not always a single right or wrong way of accomplishing > programming task, but why implement using classes unnecessarily? When is it > necessary? When is it best practice? I'll freely admit that I do not come > from an OOP programming background, so designing classes is not my first > impulse when writing code. Am I missing something? No, I don't think you're missing anything. Too many people come from Java, where (virtually) everything *must* be a class. There's a wonderful essay about the "Kingdom of the Nouns": http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html Don't get me wrong -- object oriented programming has much to say for it, but it's not the be-all and end-all of programming. Python makes it easy to mix imperative, object-oriented and functional programming idioms into the one program. (The only major idiom that Python doesn't support well is logic programming, as used by Prolog.) -- Steven From steve at pearwood.info Mon Feb 21 12:49:04 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Feb 2011 22:49:04 +1100 Subject: [Tutor] creating classes while coding In-Reply-To: References: <116823553697.20110220200146@columbus.rr.com> Message-ID: <4D625130.3000203@pearwood.info> Bill Allen wrote: > That raises my next question. Under what sort of programming circumstances > does it make sense? "It" being object oriented programming. OO is good for encapsulation and code-reuse. One good sign you should consider a class is if you start building up many global variables. Instead of: spam = 1 ham = 2 eggs = 3 def cook_spam(): pass def slice_ham(): pass def scramble_eggs(): pass there may be something to say for putting those related functions into a class: class Breakfast: spam = 1 ham = 2 eggs = 3 def cook_spam(self): pass def slice_ham(self): pass def scramble_eggs(self): pass This then allows you to have two Breakfasts, each one of which could modify their own copies of spam, ham and eggs without effecting the other. -- Steven From rafadurancastaneda at gmail.com Mon Feb 21 14:21:05 2011 From: rafadurancastaneda at gmail.com (=?ISO-8859-1?Q?Rafael_Dur=E1n_Casta=F1eda?=) Date: Mon, 21 Feb 2011 14:21:05 +0100 Subject: [Tutor] Rebuild jpg In-Reply-To: References: Message-ID: I could use any python, so I'll try to solve using Image from 2.6, but what about python 3.1? El 21 de febrero de 2011 10:21, Liam Clarke-Hutchinson escribi?: > Hi Rafael, > > Do you need to use Python 3.x? If you can use Python 2.6, the Python > Imaging Library is a great image manipulation module. > http://www.pythonware.com/products/pil/ > > Regards, > > Liam Clarke > > 2011/2/21 Rafael Dur?n Casta?eda > >> Hi all, >> >> I'm using Python 3.1 and I have an image of an animal that has been >> broken it into many narrow vertical stripe images, and now i want to rebuild >> the original one, how can i get it? >> >> P.S.: It's not homework, but i'd prefer just some help rather than the >> whole sollution >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Feb 21 15:07:59 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 21 Feb 2011 08:07:59 -0600 Subject: [Tutor] Rebuild jpg In-Reply-To: References: Message-ID: 2011/2/21 Rafael Dur?n Casta?eda > I could use any python, so I'll try to solve using Image from 2.6, but what > about python 3.1? > This post: http://stackoverflow.com/questions/3896286/image-library-for-python-3 may be of some use to you. My guess is that you may need to use some type of clustering or edge-detection algorithm - unless the strips are overlapping, in which case it's easy ;) Of course this also assumes that you want to do it automatically and not manually tell the computer "this goes here and that goes there", but teach it to solve the problem on its own. I'm not terribly familiar with this problem domain, I just have some passing knowledge because it's an interesting field to me. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bugcy013 at gmail.com Mon Feb 21 13:06:55 2011 From: bugcy013 at gmail.com (Ganesh Kumar) Date: Mon, 21 Feb 2011 17:36:55 +0530 Subject: [Tutor] PY-Tkinter Title Bar Icon Message-ID: Hai.. I am new to python Tkinter..I want Title Bar Icon.. plz..Guide me to set up icon in Title Bar. Advance Thanks Thanks -Ganesh. -- Did I learn something today? If not, I wasted it. From alan.gauld at btinternet.com Tue Feb 22 03:51:24 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Feb 2011 02:51:24 -0000 Subject: [Tutor] PY-Tkinter Title Bar Icon References: Message-ID: "Ganesh Kumar" wrote > I am new to python Tkinter..I want Title Bar Icon.. > plz..Guide me to set up icon in Title Bar. Last time I looked it was possible to do that under X Windows but not under MS Windows. (I dont know about MacOS/Quartz) It was a bug in the underlying Tk toolkit. But there has been a new release of Tk since then so it may be fixed... Try experimenting with: self.top.iconbitmap() self.top.iconname() self.top.iconwindow() # and use an image Label... You might get lucky... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From tcl76 at hotmail.com Tue Feb 22 14:46:22 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Tue, 22 Feb 2011 13:46:22 +0000 Subject: [Tutor] Concatenating string Message-ID: hi, >>> bin(0xff0) '111111110000' >>> bin(0xff1) '111111110001' >>> a=bin(0xff0)+bin(0xff1) >>> a '111111110000111111110001' >>> b=0xff0 >>> c=0xff1 >>> d=b+c >>> d 8161 >>> bin(d) '1111111100001' question: 1) why is it that a and d values are different? i'm using Python 2.5. 2) how to convert hex to bin in Python 2.5? thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.jtm30 at gmail.com Tue Feb 22 15:07:52 2011 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 22 Feb 2011 14:07:52 +0000 Subject: [Tutor] Concatenating string In-Reply-To: References: Message-ID: <4D63C338.6020101@gmail.com> On 22/02/11 13:46, tee chwee liong wrote: > hi, > > >>> bin(0xff0) > '111111110000' > >>> bin(0xff1) > '111111110001' > >>> a=bin(0xff0)+bin(0xff1) > >>> a > '111111110000111111110001' > >>> b=0xff0 > >>> c=0xff1 > >>> d=b+c > >>> d > 8161 > >>> bin(d) > '1111111100001' > > question: > 1) why is it that a and d values are different? i'm using Python 2.5. > 2) how to convert hex to bin in Python 2.5? > > > thanks > tcl Hi, 1) As you can see bin() returns a binary representation of the number you pass to it as a string. Thus when you do a=bin(0xff0)+bin(0xff1) you are concatenating the two strings returned by bin. For d you are carrying out the mathematical addition operation on the two numbers before converting it to binary. 2) You've already done that several times, just use bin() HTH, Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Feb 22 15:15:24 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 22 Feb 2011 09:15:24 -0500 Subject: [Tutor] Concatenating string In-Reply-To: References: Message-ID: <4D63C4FC.4020309@gmail.com> On 2/22/2011 8:46 AM, tee chwee liong wrote: > hi, > > >>> bin(0xff0) > '111111110000' > >>> bin(0xff1) > '111111110001' > >>> a=bin(0xff0)+bin(0xff1) > >>> a > '111111110000111111110001' > >>> b=0xff0 > >>> c=0xff1 > >>> d=b+c > >>> d > 8161 > >>> bin(d) > '1111111100001' > > question: > 1) why is it that a and d values are different? i'm using Python 2.5. Why would you expect otherwise? What are the types of a and d? They are not the same type; therefore you get different results. How do you determine the type of an object? 1 - Use the type() function. 2 - notice '' around a and not around d 3 - Read the documentation: bin(/x/) Convert an integer number to a binary string. The documentation is weak here, but at least it tells you that the result is a string. 0x is covered under (at least for Python 2.6) in 2.4.4. Integer and long integer literals. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From fal at libero.it Tue Feb 22 18:45:52 2011 From: fal at libero.it (Francesco Loffredo) Date: Tue, 22 Feb 2011 18:45:52 +0100 Subject: [Tutor] Concatenating string In-Reply-To: References: Message-ID: <4D63F650.10708@libero.it> On 22/02/2011 14.46, tee chwee liong wrote: > hi, > > >>> bin(0xff0) > '111111110000' > >>> bin(0xff1) > '111111110001' > >>> a=bin(0xff0)+bin(0xff1) > >>> a > '111111110000111111110001' > >>> b=0xff0 > >>> c=0xff1 > >>> d=b+c > >>> d > 8161 > >>> bin(d) > '1111111100001' > > question: > 1) why is it that a and d values are different? i'm using Python 2.5. > 2) how to convert hex to bin in Python 2.5? As Adam and Bob already pointed out, you are using two different conversion tools and obtain two different types. If you need a binary representation of a number AS A STRING, you can use bin(n) as you did. Or you can use hex(n) to see an hexadecimal view of the same number, again AS A STRING. If you want a binary or hex NUMBER, you already have it: EVERY number is stored internally as a binary value, even if you enter or see it in decimal or in a different base. Look at the following transcript from the Python interpreter, and please pay attention to the presence or absence of the quotes: ......................................... . >>> hex(0b1001001001001001001) . '0x49249.' . >>> 0b1001001001001001001 . 299593 . >>> 0x49249 . 299593 . >>> bin(0x49249) . '0b1001001001001001001' . >>> ........................................ Hope this will help you. Francesco Loffredo ----- Nessun virus nel messaggio. Controllato da AVG - www.avg.com Versione: 10.0.1204 / Database dei virus: 1435/3457 - Data di rilascio: 21/02/2011 From tcl76 at hotmail.com Wed Feb 23 02:57:06 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Wed, 23 Feb 2011 01:57:06 +0000 Subject: [Tutor] Concatenating string In-Reply-To: <4D63C338.6020101@gmail.com> References: , <4D63C338.6020101@gmail.com> Message-ID: hi, i dont know why when i re-run bin(0xff0) today at IDLE Python 2.5, it gives me traceback error. >>> bin(0xff0) Traceback (most recent call last): File "", line 1, in bin(0xff0) NameError: name 'bin' is not defined i guess Python 2.5 doesn't support binary conversion of hex. confuse why it worked yesterday when i tried out. thanks tcl ###################################### 2) You've already done that several times, just use bin() HTH, Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Wed Feb 23 03:02:40 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Wed, 23 Feb 2011 02:02:40 +0000 Subject: [Tutor] Concatenating string In-Reply-To: <4D63F650.10708@libero.it> References: , <4D63F650.10708@libero.it> Message-ID: hi Francesco, couldnt get hex of bin working on IDLE Python 2.5 when i type: >>> hex(0b1001001001001001001) SyntaxError: invalid syntax >>> bin(0x49249) Traceback (most recent call last): File "", line 1, in bin(0x49249) NameError: name 'bin' is not defined pls advise. thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed Feb 23 03:20:53 2011 From: davea at ieee.org (Dave Angel) Date: Tue, 22 Feb 2011 21:20:53 -0500 Subject: [Tutor] Concatenating string In-Reply-To: References: , <4D63F650.10708@libero.it> Message-ID: <4D646F05.7060709@ieee.org> On 01/-10/-28163 02:59 PM, tee chwee liong wrote: > > hi Francesco, > > couldnt get hex of bin working on IDLE Python 2.5 when i type: > >>>> hex(0b1001001001001001001) > SyntaxError: invalid syntax >>>> bin(0x49249) > Traceback (most recent call last): > File "", line 1, in > bin(0x49249) > NameError: name 'bin' is not defined > > pls advise. > > thanks > tcl > Just read the docs: http://docs.python.org/library/functions.html#bin According to that page, this function was new in version 2.6 DaveA From dack.bugs at gmail.com Wed Feb 23 03:59:10 2011 From: dack.bugs at gmail.com (Daniel Bankston) Date: Tue, 22 Feb 2011 20:59:10 -0600 Subject: [Tutor] Tutor Digest, Vol 84, Issue 78 In-Reply-To: References: Message-ID: <4D6477FE.3050406@gmail.com> On 2/22/2011 8:03 PM, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Concatenating string (tee chwee liong) > 2. Re: Concatenating string (Adam Bark) > 3. Re: Concatenating string (bob gailer) > 4. Re: Concatenating string (Francesco Loffredo) > 5. Re: Concatenating string (tee chwee liong) > 6. Re: Concatenating string (tee chwee liong) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 22 Feb 2011 13:46:22 +0000 > From: tee chwee liong > To: > Subject: [Tutor] Concatenating string > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > > hi, > >>>> bin(0xff0) > '111111110000' >>>> bin(0xff1) > '111111110001' >>>> a=bin(0xff0)+bin(0xff1) >>>> a > '111111110000111111110001' >>>> b=0xff0 >>>> c=0xff1 >>>> d=b+c >>>> d > 8161 >>>> bin(d) > '1111111100001' > > question: > 1) why is it that a and d values are different? i'm using Python 2.5. > 2) how to convert hex to bin in Python 2.5? > > > thanks > tcl > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 2 > Date: Tue, 22 Feb 2011 14:07:52 +0000 > From: Adam Bark > To: tee chwee liong > Cc: tutor at python.org > Subject: Re: [Tutor] Concatenating string > Message-ID:<4D63C338.6020101 at gmail.com> > Content-Type: text/plain; charset="iso-8859-1"; Format="flowed" > > On 22/02/11 13:46, tee chwee liong wrote: >> hi, >> >>>>> bin(0xff0) >> '111111110000' >>>>> bin(0xff1) >> '111111110001' >>>>> a=bin(0xff0)+bin(0xff1) >>>>> a >> '111111110000111111110001' >>>>> b=0xff0 >>>>> c=0xff1 >>>>> d=b+c >>>>> d >> 8161 >>>>> bin(d) >> '1111111100001' >> >> question: >> 1) why is it that a and d values are different? i'm using Python 2.5. >> 2) how to convert hex to bin in Python 2.5? >> >> >> thanks >> tcl > Hi, > > 1) As you can see bin() returns a binary representation of the number > you pass to it as a string. Thus when you do a=bin(0xff0)+bin(0xff1) you > are concatenating the two strings returned by bin. For d you are > carrying out the mathematical addition operation on the two numbers > before converting it to binary. > 2) You've already done that several times, just use bin() > > HTH, > Adam. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 3 > Date: Tue, 22 Feb 2011 09:15:24 -0500 > From: bob gailer > To: tee chwee liong > Cc: tutor at python.org > Subject: Re: [Tutor] Concatenating string > Message-ID:<4D63C4FC.4020309 at gmail.com> > Content-Type: text/plain; charset="iso-8859-1"; Format="flowed" > > On 2/22/2011 8:46 AM, tee chwee liong wrote: >> hi, >> >>>>> bin(0xff0) >> '111111110000' >>>>> bin(0xff1) >> '111111110001' >>>>> a=bin(0xff0)+bin(0xff1) >>>>> a >> '111111110000111111110001' >>>>> b=0xff0 >>>>> c=0xff1 >>>>> d=b+c >>>>> d >> 8161 >>>>> bin(d) >> '1111111100001' >> >> question: >> 1) why is it that a and d values are different? i'm using Python 2.5. > Why would you expect otherwise? > > What are the types of a and d? They are not the same type; therefore you > get different results. > > How do you determine the type of an object? > 1 - Use the type() function. > 2 - notice '' around a and not around d > 3 - Read the documentation: > bin(/x/) Convert an integer number to a binary string. The > documentation is weak here, but at least it tells you that the result is > a string. > 0x is covered under (at least for Python 2.6) in 2.4.4. Integer and long > integer literals. > From deshpande.jaidev at gmail.com Wed Feb 23 07:14:16 2011 From: deshpande.jaidev at gmail.com (Jaidev Deshpande) Date: Wed, 23 Feb 2011 11:44:16 +0530 Subject: [Tutor] reading large text file as numpy array Message-ID: Dear All I have a large text file with more than 50k lines and about 784 floats in each line. How can I read the whole file as a single numpy array? Also, is it possible to save a session (like in MATLAB) and reload it later? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From anulavidyalaya at sltnet.lk Tue Feb 22 04:51:40 2011 From: anulavidyalaya at sltnet.lk (anulavidyalaya) Date: Tue, 22 Feb 2011 09:21:40 +0530 Subject: [Tutor] subprocessor startup error Message-ID: <000001cbd2ff$a2ca2000$0201a8c0@acer279f1c7a31> I have a problem when openning python (GUI) , There is a message "IDLE's subprocessor didn't make connection." -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Feb 23 10:28:15 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Feb 2011 10:28:15 +0100 Subject: [Tutor] reading large text file as numpy array References: Message-ID: Jaidev Deshpande wrote: > I have a large text file with more than 50k lines and about 784 floats in > each line. > > How can I read the whole file as a single numpy array? Have you tried numpy.loadtxt()? From alan.gauld at btinternet.com Wed Feb 23 11:00:46 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 Feb 2011 10:00:46 -0000 Subject: [Tutor] subprocessor startup error References: <000001cbd2ff$a2ca2000$0201a8c0@acer279f1c7a31> Message-ID: "anulavidyalaya" wrote >I have a problem when openning python (GUI) , > There is a message "IDLE's subprocessor didn't make connection." Which version of Python on which Operating System? This may be a firewall issue but I thought they had fixed that in recent versions of Python... Alan G. From fal at libero.it Wed Feb 23 11:48:24 2011 From: fal at libero.it (Francesco Loffredo) Date: Wed, 23 Feb 2011 11:48:24 +0100 Subject: [Tutor] Concatenating string In-Reply-To: References: , <4D63F650.10708@libero.it> Message-ID: <4D64E5F8.3030602@libero.it> On 23/02/2011 3.02, tee chwee liong wrote: > hi Francesco, > > couldnt get hex of bin working on IDLE Python 2.5 when i type: > > >>> hex(0b1001001001001001001) > SyntaxError: invalid syntax > >>> bin(0x49249) > Traceback (most recent call last): > File "", line 1, in > bin(0x49249) > NameError: name 'bin' is not defined > > pls advise. Python 2.5 had no built-in binary conversion tools. bin() was introduced in 2.6. The interesting questions are: 1- are you SURE you were using 2.5 yesterday? If so: 2- did you import some modules? Which ones? On my phone I have Python 2.5 too, and it gives the same errors to me. Is it possible that you upgrade to 2.6 or 2.7 ? > > thanks > tcl You're welcome! FAL ----- Nessun virus nel messaggio. Controllato da AVG - www.avg.com Versione: 10.0.1204 / Database dei virus: 1435/3460 - Data di rilascio: 22/02/2011 From steve at pearwood.info Wed Feb 23 13:35:06 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Feb 2011 23:35:06 +1100 Subject: [Tutor] subprocessor startup error In-Reply-To: <000001cbd2ff$a2ca2000$0201a8c0@acer279f1c7a31> References: <000001cbd2ff$a2ca2000$0201a8c0@acer279f1c7a31> Message-ID: <4D64FEFA.1060801@pearwood.info> anulavidyalaya wrote: > I have a problem when openning python (GUI) , There is a message "IDLE's subprocessor didn't make connection." Google is your friend. http://www.google.co.uk/search?hl=en&q=IDLE%27s+subprocess+didn%27t+make+connection (By the way, don't re-type error messages, if you can avoid it. Copy and paste them. If you must re-type them, make sure you type them correctly -- it's not "subprocessor", but subprocess.) What version of Python are you using, what operating system, what have you already tried? -- Steven From joel.goldstick at gmail.com Wed Feb 23 15:12:44 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 23 Feb 2011 09:12:44 -0500 Subject: [Tutor] Concatenating string In-Reply-To: References: <4D63F650.10708@libero.it> Message-ID: On Tue, Feb 22, 2011 at 9:02 PM, tee chwee liong wrote: > hi Francesco, > > couldnt get hex of bin working on IDLE Python 2.5 when i type: > > >>> hex(0b1001001001001001001) > SyntaxError: invalid syntax > >>> bin(0x49249) > > Traceback (most recent call last): > File "", line 1, in > bin(0x49249) > > NameError: name 'bin' is not defined > > pls advise. > > thanks > tcl > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > bin is new in 2.6 .. check your version -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Wed Feb 23 15:21:45 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Wed, 23 Feb 2011 14:21:45 +0000 Subject: [Tutor] Concatenating string In-Reply-To: <4D64E5F8.3030602@libero.it> References: , <4D63F650.10708@libero.it> , <4D64E5F8.3030602@libero.it> Message-ID: > The interesting questions are: > 1- are you SURE you were using 2.5 yesterday? > If so: > 2- did you import some modules? Which ones? > On my phone I have Python 2.5 too, and it gives the same errors to me. > > Is it possible that you upgrade to 2.6 or 2.7 ? > hi, yes i'm sure using Python 2.5 because that's the only version i have. however i was playing around on how to convert hex to bin, can't remember whether imported special module. anyway here is the code that converts hex to bin: import binascii def byte_to_binary(n): return ''.join(str((n & (1 << i)) and 1) for i in reversed(range(8))) def hex_to_binary(h): return ''.join(byte_to_binary(ord(b)) for b in binascii.unhexlify(h)) array0 = '000a00000003c0000030000c1f800000' a=hex_to_binary(array0) print "a:",a thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Wed Feb 23 15:54:22 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Wed, 23 Feb 2011 14:54:22 +0000 Subject: [Tutor] Convert bin to hex Message-ID: hi, i have a script that converts hex to bin and bin to hex back. however, when converting back to hex the leading 0s are truncated. how to maintain the leading 0s? tq import binascii import string def byte_to_binary(n): return ''.join(str((n & (1 << i)) and 1) for i in reversed(range(8))) def hex_to_binary(h): return ''.join(byte_to_binary(ord(b)) for b in binascii.unhexlify(h)) def bintohex(s): return ''.join([ "%x"%string.atoi(bin,2) for bin in s.split() ]) array0 = '000a00000003c0000030000c1f800000' a=hex_to_binary(array0) print "Convert array0 to bin:",a print "Convert array0 back to hex:",bintohex(a) if bintohex(a)==array0: print "Match" else: print "Not match" #########result###################### >>> Convert array0 to bin: 00000000000010100000000000000000000000000000001111000000000000000000000000110000000000000000110000011111100000000000000000000000 Convert array0 back to hex: a00000003c0000030000c1f800000 Not match >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From npowell3 at gmail.com Wed Feb 23 18:01:15 2011 From: npowell3 at gmail.com (Nelson Powell) Date: Wed, 23 Feb 2011 12:01:15 -0500 Subject: [Tutor] Trouble installing numpy on QNX Message-ID: I'm currently using QNX 6.4.1 with Python 2.5. I went to install numpy 1.4.1, but the install kicks bakc an error saying that it cannot find Python.h and that I should install python-dev|python-devel. I look online and I can only find those two packages in relation to Ubuntu, which obviously will not work. Has anyone experienced this or know what's up? -------------- next part -------------- An HTML attachment was scrubbed... URL: From deshpande.jaidev at gmail.com Wed Feb 23 20:30:41 2011 From: deshpande.jaidev at gmail.com (Jaidev Deshpande) Date: Thu, 24 Feb 2011 01:00:41 +0530 Subject: [Tutor] PCA on sparse matrices, tolerance of eigenvalues Message-ID: Dear all, I tried using the 'scipy.sparse.eigs' tool for performing principal component analysis on a matrix which is roughly 80% sparse. First of all, is that a good way to go about it? Second, the operation failed when the function failed to converge on accurate eigenvalues. I noticed the 'tol' attribute in the function, but how does one define a reasonable tolerance and calculate it? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 24 02:31:12 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Feb 2011 01:31:12 -0000 Subject: [Tutor] PCA on sparse matrices, tolerance of eigenvalues References: Message-ID: "Jaidev Deshpande" wrote > I tried using the 'scipy.sparse.eigs' tool for performing principal > component analysis on a matrix which is roughly 80% sparse. > > First of all, is that a good way to go about it? Umm, I remember the term eigenvalue from University math. Other than that the first sentence could be in Chinese! :-) I suspect you might get a better resoponse on a scipy or numpy mailing list or forum. Although there are a few users of that here it sounds like your queries are likely to be more scipy oriented than general Python. There is a list of options here: http://www.scipy.org/Mailing_Lists > Second, the operation failed when the function failed to converge on > accurate eigenvalues. I noticed the 'tol' attribute in the function, > but how > does one define a reasonable tolerance and calculate it? Sorry, I understand the sentence this time but again its more a scipy question than a Python one. Alan G. From tcl76 at hotmail.com Thu Feb 24 03:17:55 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Thu, 24 Feb 2011 02:17:55 +0000 Subject: [Tutor] Convert string to long Message-ID: hi, is there a way to convert from string to long? for eg: i want to concatenate all the arrays into data and make it same type (long) as data1. ####code: a='0x' array0 = '00000018000004000000000000000000' array1 = '00000000000000000000000000000000' array2 = 'fe000000000000000000000000000000' array3 = '00000000000000000000000000ffffff' data = a+array0+array1+array2+array3 print data print type(data) data1 = 0x0000001800000400000000000000000000000000000000000000000000000000fe00000000000000000000000000000000000000000000000000000000ffffff print type(data1) ###result: 0x0000001800000400000000000000000000000000000000000000000000000000fe00000000000000000000000000000000000000000000000000000000ffffff ###### thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Thu Feb 24 03:38:01 2011 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 23 Feb 2011 21:38:01 -0500 Subject: [Tutor] licensing python work? Message-ID: Hi all, This is not strictly on topic and probably has a very obvious answer, but I want to make sure I do it right. How do I license something I write? I have that Bookshare wrapper done, at least as far as I can tell, and I want to give it to Bookshare so they can provide it to whomever wants it. Basically, anyone can copy or modify it in any way, in part or in whole, whether they make money off it or not. Realistically it seems pointless to make a big deal out of someone making money off of this wrapper since it is only a few hundred lines. What license do you recommend, and do I just point people to the license in a comment in the code, or is there something else I have to do? Thanks. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From waynejwerner at gmail.com Thu Feb 24 04:05:09 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 23 Feb 2011 21:05:09 -0600 Subject: [Tutor] licensing python work? In-Reply-To: References: Message-ID: If you don't care how people use it at all, just release your code into the public domain, then it doesn't matter how they use it. HTH, Wayne On Wed, Feb 23, 2011 at 8:38 PM, Alex Hall wrote: > Hi all, > This is not strictly on topic and probably has a very obvious answer, > but I want to make sure I do it right. How do I license something I > write? I have that Bookshare wrapper done, at least as far as I can > tell, and I want to give it to Bookshare so they can provide it to > whomever wants it. Basically, anyone can copy or modify it in any way, > in part or in whole, whether they make money off it or not. > Realistically it seems pointless to make a big deal out of someone > making money off of this wrapper since it is only a few hundred lines. > What license do you recommend, and do I just point people to the > license in a comment in the code, or is there something else I have to > do? Thanks. > > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com; http://www.facebook.com/mehgcap > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Thu Feb 24 04:19:38 2011 From: smokefloat at gmail.com (David Hutto) Date: Wed, 23 Feb 2011 22:19:38 -0500 Subject: [Tutor] licensing python work? In-Reply-To: References: Message-ID: Read the licenses, and see which one fits your needs, or just put your own conditions at the top of each file. They can use it under your stated terms. http://www.google.com/search?client=ubuntu&channel=fs&q=open+source+licensing&ie=utf-8&oe=utf-8 On Wed, Feb 23, 2011 at 10:05 PM, Wayne Werner wrote: > If you don't care how people use it at all, just release your code into the > public domain, then it doesn't matter how they use it. > HTH, > Wayne > > On Wed, Feb 23, 2011 at 8:38 PM, Alex Hall wrote: >> >> Hi all, >> This is not strictly on topic and probably has a very obvious answer, >> but I want to make sure I do it right. How do I license something I >> write? I have that Bookshare wrapper done, at least as far as I can >> tell, and I want to give it to Bookshare so they can provide it to >> whomever wants it. Basically, anyone can copy or modify it in any way, >> in part or in whole, whether they make money off it or not. >> Realistically it seems pointless to make a big deal out of someone >> making money off of this wrapper since it is only a few hundred lines. >> What license do you recommend, and do I just point people to the >> license in a comment in the code, or is there something else I have to >> do? Thanks. >> >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehgcap at gmail.com; http://www.facebook.com/mehgcap >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From edwardcru1 at aol.com Thu Feb 24 04:22:02 2011 From: edwardcru1 at aol.com (Edward Martinez) Date: Wed, 23 Feb 2011 19:22:02 -0800 Subject: [Tutor] comparing strings Message-ID: <4D65CEDA.1020707@aol.com> Hi, I'm new to the list and programming. i have a question, why when i evaluate strings ie 'a' > '3' it reports true, how does python come up with that? Regards, Edward From kb1pkl at aim.com Thu Feb 24 04:29:58 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 23 Feb 2011 22:29:58 -0500 Subject: [Tutor] comparing strings In-Reply-To: <4D65CEDA.1020707@aol.com> References: <4D65CEDA.1020707@aol.com> Message-ID: <4D65D0B6.2090400@aim.com> On 02/23/2011 10:22 PM, Edward Martinez wrote: > Hi, > > I'm new to the list and programming. > i have a question, why when i evaluate strings ie 'a' > '3' it reports > true, how does python come up with that? Welcome! As far as I know, it compares the value of the ord()'s. >>>ord('a') 97 >>>ord('3') 51 This is their number in the ASCII system. You can also do this: >>>chr(97) 'a' >>>chr(51) '3' -- Corey Richardson From wallenpb at gmail.com Thu Feb 24 04:53:07 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 23 Feb 2011 21:53:07 -0600 Subject: [Tutor] accessing another system's environment Message-ID: I know that I can use the following to get a listing of the environment of my own system. How can I do similar for another system on my network. This is for administrative purposes. >>> import os >>> for param in os.environ.keys(): print(param, os.environ[param]) --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From edwardcru1 at aol.com Thu Feb 24 04:54:25 2011 From: edwardcru1 at aol.com (Edward Martinez) Date: Wed, 23 Feb 2011 19:54:25 -0800 Subject: [Tutor] comparing strings In-Reply-To: <4D65D0B6.2090400@aim.com> References: <4D65CEDA.1020707@aol.com> <4D65D0B6.2090400@aim.com> Message-ID: <4D65D671.1010808@aol.com> On 02/23/11 19:29, Corey Richardson wrote: > On 02/23/2011 10:22 PM, Edward Martinez wrote: >> Hi, >> >> I'm new to the list and programming. >> i have a question, why when i evaluate strings ie 'a'> '3' it reports >> true, how does python come up with that? > Welcome! As far as I know, it compares the value of the ord()'s. > >>>> ord('a') > 97 >>>> ord('3') > 51 > > This is their number in the ASCII system. You can also do this: > >>>> chr(97) > 'a' >>>> chr(51) > '3' > Hi, Thank you!. I better read on ASCII and unicode and try a few using char() and ord(). Regards, Edward From cfuller084 at thinkingplanet.net Thu Feb 24 04:00:34 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 23 Feb 2011 21:00:34 -0600 Subject: [Tutor] licensing python work? In-Reply-To: References: Message-ID: <201102232100.40534.cfuller084@thinkingplanet.net> I'd recommend the Apache license, for BSD/X11/MIT type permissive licensing, because it's compatible with contributions to Python (maybe not this code, but you might want to contribute something else in the future). http://wiki.python.org/moin/PythonSoftwareFoundationLicenseFaq#Contributing_Code_to_Python http://www.opensource.org/licenses/apache2.0.php Cheers On Wednesday 23 February 2011, Alex Hall wrote: > Hi all, > This is not strictly on topic and probably has a very obvious answer, > but I want to make sure I do it right. How do I license something I > write? I have that Bookshare wrapper done, at least as far as I can > tell, and I want to give it to Bookshare so they can provide it to > whomever wants it. Basically, anyone can copy or modify it in any way, > in part or in whole, whether they make money off it or not. > Realistically it seems pointless to make a big deal out of someone > making money off of this wrapper since it is only a few hundred lines. > What license do you recommend, and do I just point people to the > license in a comment in the code, or is there something else I have to > do? Thanks. From smokefloat at gmail.com Thu Feb 24 05:10:15 2011 From: smokefloat at gmail.com (David Hutto) Date: Wed, 23 Feb 2011 23:10:15 -0500 Subject: [Tutor] licensing python work? In-Reply-To: <201102232100.40534.cfuller084@thinkingplanet.net> References: <201102232100.40534.cfuller084@thinkingplanet.net> Message-ID: Remember to check the licenses of what your wrapper utilizes. According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From smokefloat at gmail.com Thu Feb 24 05:15:18 2011 From: smokefloat at gmail.com (David Hutto) Date: Wed, 23 Feb 2011 23:15:18 -0500 Subject: [Tutor] licensing python work? In-Reply-To: References: <201102232100.40534.cfuller084@thinkingplanet.net> Message-ID: And in the end it is called open source, for a reason, so if you're not worried, just throw your name at the top, and don't even use a license, unless you want your name to be kept, in which case you might want to include"whether copied in whole, or part". We all scavenge for examples, until we can do it ourselves, and even then, when working with multiple interlanguage processes, you need libraries of functions, references and examples to "vulturize". From cfuller084 at thinkingplanet.net Thu Feb 24 04:29:50 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 23 Feb 2011 21:29:50 -0600 Subject: [Tutor] licensing python work? In-Reply-To: References: Message-ID: <201102232129.56817.cfuller084@thinkingplanet.net> Invoking the public domain isn't as simple as you might naively think. Tread with care! http://www.linuxjournal.com/article/6225 Cheers On Wednesday 23 February 2011, Wayne Werner wrote: > If you don't care how people use it at all, just release your code into the > public domain, then it doesn't matter how they use it. > > HTH, > Wayne > > On Wed, Feb 23, 2011 at 8:38 PM, Alex Hall wrote: > > Hi all, > > This is not strictly on topic and probably has a very obvious answer, > > but I want to make sure I do it right. How do I license something I > > write? I have that Bookshare wrapper done, at least as far as I can > > tell, and I want to give it to Bookshare so they can provide it to > > whomever wants it. Basically, anyone can copy or modify it in any way, > > in part or in whole, whether they make money off it or not. > > Realistically it seems pointless to make a big deal out of someone > > making money off of this wrapper since it is only a few hundred lines. > > What license do you recommend, and do I just point people to the > > license in a comment in the code, or is there something else I have to > > do? Thanks. > > > > -- > > Have a great day, > > Alex (msg sent from GMail website) > > mehgcap at gmail.com; http://www.facebook.com/mehgcap > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor From smokefloat at gmail.com Thu Feb 24 05:35:16 2011 From: smokefloat at gmail.com (David Hutto) Date: Wed, 23 Feb 2011 23:35:16 -0500 Subject: [Tutor] licensing python work? In-Reply-To: <201102232129.56817.cfuller084@thinkingplanet.net> References: <201102232129.56817.cfuller084@thinkingplanet.net> Message-ID: That's why I said to check the licenses from what you work upon(that gives more insight into what license you should use, and how you use it). More and more it's just docs, and functions for me, but initially, all of your "great" beginner projects, utilize what you find, and tutorials online are usually just that - scavengable. From mehgcap at gmail.com Thu Feb 24 05:45:59 2011 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 23 Feb 2011 23:45:59 -0500 Subject: [Tutor] licensing python work? In-Reply-To: References: <201102232129.56817.cfuller084@thinkingplanet.net> Message-ID: Thanks, everyone, for the feedback. I went with the suggestion of adding my name to it, mentioning that I am not responsible for anything that happens, a request for credit somewhere in an application that uses the wrapper (though not a requirement), and that's pretty much it. I think this thing has about five hundred lines, so it is nothing too big, but hopefully it will help someone in the future who goes googling for a python implementation of the Bookshare api. Now to send it off... On 2/23/11, David Hutto wrote: > That's why I said to check the licenses from what you work upon(that > gives more insight into what license you should use, and how you use > it). More and more it's just docs, and functions for me, but > initially, all of your "great" beginner projects, utilize what you > find, and tutorials online are usually just that - scavengable. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From cschiro.gc at gmail.com Thu Feb 24 05:15:39 2011 From: cschiro.gc at gmail.com (Chris Schiro) Date: Wed, 23 Feb 2011 20:15:39 -0800 Subject: [Tutor] help Message-ID: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> Hi, I am completely new to programming aside from working with basic many years ago. I purchased a Python book for beginners so I could start from scratch which has been walking me through just fine until: writing a program to interact with user for feedback: name=input("What is your name? ") I have found that this line will return an error every time while running the completed program, unless I enter a number. If I enter a numeric value the program will continue on as written. I have followed the code exactly per the book. What is the proper coding in this scenario? Thank you, Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 24 09:52:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Feb 2011 08:52:55 -0000 Subject: [Tutor] Convert string to long References: Message-ID: "tee chwee liong" wrote > is there a way to convert from string to long? for eg: i want to > concatenate all the arrays into data and make it same type (long) as > data1. int() should work ok. Just remember to supply the base: eg. int(s,16) for a hex string HTH, Alan G. From nitinpawar432 at gmail.com Thu Feb 24 09:53:23 2011 From: nitinpawar432 at gmail.com (Nitin Pawar) Date: Thu, 24 Feb 2011 14:23:23 +0530 Subject: [Tutor] help In-Reply-To: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> References: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> Message-ID: instead of input ... use raw_input() On Thu, Feb 24, 2011 at 9:45 AM, Chris Schiro wrote: > Hi, > > I am completely new to programming aside from working with basic many years > ago. I purchased a Python book for beginners so I could start from scratch > which has been walking me through just fine until: writing a program to > interact with user for feedback: > > > > name=input(?What is your name? ?) > > > > I have found that this line will return an error every time while running > the completed program, unless I enter a number. If I enter a numeric value > the program will continue on as written. > > > > I have followed the code exactly per the book. What is the proper coding in > this scenario? > > > > Thank you, > > > > Chris > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Nitin Pawar -------------- next part -------------- An HTML attachment was scrubbed... URL: From enalicho at gmail.com Thu Feb 24 09:58:25 2011 From: enalicho at gmail.com (Noah Hall) Date: Thu, 24 Feb 2011 08:58:25 +0000 Subject: [Tutor] help In-Reply-To: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> References: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> Message-ID: > I have found that this line will return an error every time while running > the completed program, unless I enter a number. If I enter a numeric value > the program will continue on as written. When it comes to things like error messages, you need to post enough code and the _exact_ error message in order for us to easily help you. > name=input(?What is your name? ?) I imagine it's because you're using Python 2.*, where as the guide is using the 3.* version. The function you want in 2.7 is "raw_input", not "input". In 2.7, "input" takes the string given then runs eval on it. If you want to know more about this, read http://docs.python.org/library/functions.html?#input and http://docs.python.org/library/functions.html?#eval Otherwise, you can either change your Python installation to Python 3.* to follow your guide, or you can carry on with 2.* and hope for the best :) From andreengels at gmail.com Thu Feb 24 09:58:47 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 24 Feb 2011 09:58:47 +0100 Subject: [Tutor] help In-Reply-To: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> References: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> Message-ID: On Thu, Feb 24, 2011 at 5:15 AM, Chris Schiro wrote: > Hi, > > I am completely new to programming aside from working with basic many years > ago. I purchased a Python book for beginners so I could start from scratch > which has been walking me through just fine until: writing a program to > interact with user for feedback: > > > > name=input(?What is your name? ?) > > > > I have found that this line will return an error every time while running > the completed program, unless I enter a number. If I enter a numeric value > the program will continue on as written. > > > > I have followed the code exactly per the book. What is the proper coding in > this scenario? What is going on is that you are presumably running some version of Python 2, whereas the book you are using is intended for Python 3. In Python 2, to get the same result as input() in Python 3, you have to use raw_input instead. name=raw_input(?What is your name? ?) Alternatively, you could of course install Python 3.1 instead of Python 2.7 (or whatever version you are running). -- Andr? Engels, andreengels at gmail.com From emadnawfal at gmail.com Thu Feb 24 09:59:42 2011 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXZgCDZhtmI2YHZhCDZgNin2K8p?=) Date: Thu, 24 Feb 2011 10:59:42 +0200 Subject: [Tutor] help In-Reply-To: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> References: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> Message-ID: On 2/24/11, Chris Schiro wrote: > Hi, > > I am completely new to programming aside from working with basic many years > ago. I purchased a Python book for beginners so I could start from scratch > which has been walking me through just fine until: writing a program to > interact with user for feedback: > > > > name=input("What is your name? ") > > > > I have found that this line will return an error every time while running > the completed program, unless I enter a number. If I enter a numeric value > the program will continue on as written. > > > > I have followed the code exactly per the book. What is the proper coding in > this scenario? > > > > Thank you, > > > > Chris > > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- From alan.gauld at btinternet.com Thu Feb 24 10:00:12 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Feb 2011 09:00:12 -0000 Subject: [Tutor] accessing another system's environment References: Message-ID: "Bill Allen" wrote >I know that I can use the following to get a listing of the >environment of > my own system. How can I do similar for another system on my > network. > This is for administrative purposes. Environments are user and process specific so you would need to access the remote machine, access the user account, connect to the specific process and then run the environment check. It rarely makes any sense unless its the user themselves doing the check. I assume there is a greater requirement at the bavk of this? What exactly is it you are trying to find out? There may be a better way. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From delegbede at dudupay.com Thu Feb 24 10:03:33 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Thu, 24 Feb 2011 10:03:33 +0100 Subject: [Tutor] help In-Reply-To: References: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> Message-ID: That line only expects int and say numbers generally. If you want to print strings, use, raw_input in place of input. Try that out and then let's have a feedback. Sent from my BlackBerry wireless device from MTN On Thu, Feb 24, 2011 at 9:53 AM, Nitin Pawar wrote: > instead of input ... use raw_input() > > On Thu, Feb 24, 2011 at 9:45 AM, Chris Schiro wrote: > >> Hi, >> >> I am completely new to programming aside from working with basic many >> years ago. I purchased a Python book for beginners so I could start from >> scratch which has been walking me through just fine until: writing a program >> to interact with user for feedback: >> >> >> >> name=input(?What is your name? ?) >> >> >> >> I have found that this line will return an error every time while running >> the completed program, unless I enter a number. If I enter a numeric value >> the program will continue on as written. >> >> >> >> I have followed the code exactly per the book. What is the proper coding >> in this scenario? >> >> >> >> Thank you, >> >> >> >> Chris >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Nitin Pawar > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinf > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 24 10:04:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 24 Feb 2011 09:04:26 -0000 Subject: [Tutor] help References: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> Message-ID: "Chris Schiro" wrote > I am completely new to programming aside from working with basic > many years > ago. I purchased a Python book for beginners so I could start from > scratch > which has been walking me through just fine until: writing a program > to > interact with user for feedback: > > name=input("What is your name? ") > > I have found that this line will return an error every time while > running > the completed program, unless I enter a number. It sounds like you are using a Python v3 book but running Python v2. Python v3 was a major change and not backward compatible with Python 2. As a beginner your best bet is probably to upgrade your copy of Python to v3. The snag with that is that some 3rd party modules are not yet ported to v3, but hopefully, by the time you need to use them, if ever, they will be! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From delegbede at dudupay.com Thu Feb 24 10:08:00 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Thu, 24 Feb 2011 10:08:00 +0100 Subject: [Tutor] help In-Reply-To: References: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> Message-ID: i can mail free books on python 2.XXXX if you want. starting out with python 3.XXX restricts the amount of help you can get and also free resources. most resources i have come across are python 2.XXX. cheers. On Thu, Feb 24, 2011 at 9:58 AM, Andre Engels wrote: > On Thu, Feb 24, 2011 at 5:15 AM, Chris Schiro > wrote: > > Hi, > > > > I am completely new to programming aside from working with basic many > years > > ago. I purchased a Python book for beginners so I could start from > scratch > > which has been walking me through just fine until: writing a program to > > interact with user for feedback: > > > > > > > > name=input(?What is your name? ?) > > > > > > > > I have found that this line will return an error every time while running > > the completed program, unless I enter a number. If I enter a numeric > value > > the program will continue on as written. > > > > > > > > I have followed the code exactly per the book. What is the proper coding > in > > this scenario? > > What is going on is that you are presumably running some version of > Python 2, whereas the book you are using is intended for Python 3. In > Python 2, to get the same result as input() in Python 3, you have to > use raw_input instead. > > name=raw_input(?What is your name? ?) > > Alternatively, you could of course install Python 3.1 instead of > Python 2.7 (or whatever version you are running). > > -- > Andr? Engels, andreengels at gmail.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development -------------- next part -------------- An HTML attachment was scrubbed... URL: From nitinchandra1 at gmail.com Thu Feb 24 10:54:36 2011 From: nitinchandra1 at gmail.com (nitin chandra) Date: Thu, 24 Feb 2011 15:24:36 +0530 Subject: [Tutor] merging 2 files. Message-ID: Hello Every One, I have A problem :) I have a file with data collected in with 5 colums in a CSV format. eg. test.csv (below) format ------------------------------------------------------- 26290,75.3186699999993,28.3905499998328,"WELL 3","WELL 3 MENCHOKE FUNCTIOANL" 26290,75.3161800000604,28.3970899999997,"WT 1","WT 1 BHIEND SCHOOL FUNCTIONAL" 26290,75.3162700000357,28.3971299997539,"HP1","HP1 PRIMERY SCHOOL SHYOPURA NOFUNCTIONAL" 26290,75.3184299998057,28.3902899999283,"GLR 1","GLR1 MENCHOKE FUNCTIONAL" 26290,75.3197099998803,28.3895599995882,"WELL 1","WELL1 BUS STAND NONFUNCTIONAL" 26290,75.3169699997421,28.3956699999652,"TW 1","WELL 2 FRONT OF SCHOOL NONFUNCTIONAL" 40988,75.269703,28.369377,"HPG1","HPG1 WARD NO. 7" 40988,75.270543,28.368524,"GLR1","GLR1 IN SCHOOL" 40988,75.270429,28.368761,"WT1","WT1 IN SCHOOL" 40988,75.2711484196972,28.3689626934834,"OW1+TW1","OW1+TW1 W. N. 7" 40988,75.271347,28.369323,"GLR1","GLR1 WARD NO. 7" 41458,75.2825099999856,28.4071500000085,"GLR1","GLR1 PO KE PASS" 41458,75.2824,28.40718,"GLR2","GLR2 P.O. KE PASS" ---------------------------------------------- The other file is Jhun.csv **************************** id,loc_id,habitation_name,source_type,type_habit,location,longitude,latitude,functional_status,operational_status,quality_status,village_quality_status,yield,seasonal_fluctuation,water_fluctuation_min,water_fluctuation_max,avg_depth,para_ph,para_tds,para_cl,para_f,para_no3,bact,rep_status,remark 88075,60942,Raghunathpura,TW3,MH,Madhaya Mein,,,F,In-Use,Potable,Good,Good,No-Change,0,0,140,8,680,300,1,100,,,remarks4 88074,60942,Raghunathpura,TW2,MH,School Ke pas,,,F,In-Use,Potable,Good,Good,No-Change,0,0,150,8,620,320,0.5,45,,,remarks3 88073,60942,Raghunathpura,TW1,MH,Harizen basti ,,,F,In-Use,Potable,Good,Good,No-Change,0,0,120,8,810,380,1,45,,,remarks2 88072,60942,Raghunathpura,HpGovt1,MH,Raste Per,,,NF,,,,,,,,,,,,,,,Rep,remarks1 83613,59500,Dhani Hukma,TW3,MH,rasta per,,,NF,,,,,,,,,,,,,,,Non Rep,remarks8 83612,59500,Dhani Hukma,TW2,MH,rasta per,,,F,In-Use,Potable,Good,Good,No-Change,0,0,140,7.5,660,220,0.5,45,,,remarks7 83611,59500,Dhani Hukma,TW1,MH,rasta per,,,F,In-Use,Potable,Good,Good,No-Change,0,0,135,7.5,740,180,1,45,,,remarks6 83610,59500,Dhani Hukma,HpGovt5,MH,chowk mai,,,NF,,,,,,,,,,,,,,,Non Rep,remarks5 83609,59500,Dhani Hukma,HpGovt4,MH,chowk mai,,,NF,,,,,,,,,,,,,,,Non Rep,remarks4 83608,59500,Dhani Hukma,HpGovt3,MH,rasta per,,,NF,,,,,,,,,,,,,,,Non Rep,remarks3 83607,59500,Dhani Hukma,HpGovt2,MH,rasta per,,,F,In-Use,Potable,Good,Good,No-Change,0,0,80,7.5,690,200,0.5,45,,,remarks2 83606,59500,Dhani Hukma,HpGovt1,MH,near ragu home,,,NF,,,,,,,,,,,,,,,Non Rep,remarks1 1085,11284,Ashok Nagar,HpGovt1,MH,IN SCHOOL,,,NF,,,,,,,,,,,,,,,Rep, ********************************** PROBLEM : I need to pick the "first coloum" from test.csv AND SEARCH in jhun.csv "second coloum" , IF matches read that row from jhun.csv, break it into individual values , concat with the first file, test.csv, individual values and write to a third file, eg. merged2.csv currently the data in both the file is 6 - 10,000 rows max. I am in need of the solution as client breathing down my neck. this is my 5th attempt. Thank you VERY much Nitin ///////////////////////////////////////// import os, sys, re f = open ('Jhun_Water_source_details_hab.csv', 'r') f2 = open ('test.csv', 'r') fw = f.readline() # read from Jhun Water csv file f11 = f.read() print "This is from Jhun_Water_source_details_hab.csv file" #print col11 + col12 + col13 + col14 print f11 # read from test csv file f21 = f2.readline() ln3 = f21.rstrip('\r\n') ln4 = ln3.strip('""') row2 = ln4.split(',') #print row2 col21 = row2[:1] col22 = row2[1:2] col23 = row2[2:3] print "This is from test.csv file" #print col21 + col22 + col23 print f21 for line in f11: match = None if line.find(col21) == 0: pass if line.find(col21) == f11: print line1 break //////////////////// From steve at pearwood.info Thu Feb 24 11:34:29 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 Feb 2011 21:34:29 +1100 Subject: [Tutor] licensing python work? In-Reply-To: References: Message-ID: <4D663435.9060009@pearwood.info> Wayne Werner wrote: > If you don't care how people use it at all, just release your code into the > public domain, then it doesn't matter how they use it. That's actually not as easy as it sounds. It depends where you are. In some jurisdictions, such as the USA, it's hard to put work into the public domain in such a way as it sticks. Just look at the effort the Creative Commons people going to in order to make their "public domain" licence bulletproof. http://creativecommons.org/choose/zero/ You might say, "What difference does it make, I'm not going to sue you". Sure, but what if you get hit by a bus, and your heirs come after me with a fully-loaded lawyer for "stealing" your valuable intellectual "property"? If your release isn't bulletproof, I'm not going to touch it. Personally I recommend two free/open source licences: the MIT licence and the GPL. If you want people to use your work, and you don't care how, use the MIT licence: http://www.opensource.org/licenses/mit-license.php The only restriction is that if they re-distribute your software, they have to include the copyright notice. If you want your uses to "share and share alike", use the GPL: http://www.opensource.org/licenses/gpl-license But if you're serious about having others use your software, you *must* be GPL-compatible: http://www.dwheeler.com/essays/gpl-compatible.html Whatever you do, don't make up your own licence unless you are a lawyer specializing in *international* copyright law and software licences! Every time an amateur makes up a new open source licence, God buys a retail version of Windows. -- Steven From martin at linux-ip.net Thu Feb 24 11:41:50 2011 From: martin at linux-ip.net (Martin A. Brown) Date: Thu, 24 Feb 2011 11:41:50 +0100 Subject: [Tutor] merging 2 files. In-Reply-To: References: Message-ID: Hi Nitin, : currently the data in both the file is 6 - 10,000 rows max. Many ways to skin this cat. You say that the files are 6-10,000 lines. These are small files. Load them into memory. Learn how to use csv.reader. : PROBLEM : I need to pick the "first coloum" from test.csv AND : SEARCH in jhun.csv "second coloum" , IF matches read that row : from jhun.csv, break it into individual values , concat with the : first file, test.csv, individual values and write to a third : file, eg. merged2.csv Always break your problem into its parts and examine your data. There's probably a data structure that suits your needs. You have a lookup table, 'jhun.csv' (your second file). Given your problem description, it seems like the first column in 'jhun.csv' has your unique identifiers. If that's accurate, then read that second file into some sort of in-memory lookup table. A key, perhaps in a dictionary, would you say? Then, you can simply read your other file (test.csv) and print to output. This is one quick and dirty solution: import csv # -- build the lookup table # lookup = dict() file0 = csv.reader(open('jhun.csv','r')) for row in file0: lookup[ row[0] ] = row # -- now, read through the # file1 = csv.reader(open('test.csv','r')) for row in file1: exists = lookup.get( row[0], None ) if exists: print row, exists # -- print out only what you want else: pass # -- do you need to do something if no lookup entry? At 10^4 lines in the lookup file, you could easily do this in memory. There are many tools for dealing with structured data, even loosely structured data such as csv. When faced with a problem like this in the future, ask yourself not only about what tools like csv.reader you may have at your disposal, but also what data structures are suited to your questions of your data. : I am in need of the solution as client breathing down my neck. They always do. Wear a scarf. -Martin -- Martin A. Brown http://linux-ip.net/ From davea at ieee.org Thu Feb 24 11:56:21 2011 From: davea at ieee.org (Dave Angel) Date: Thu, 24 Feb 2011 05:56:21 -0500 Subject: [Tutor] comparing strings In-Reply-To: <4D65D671.1010808@aol.com> References: <4D65CEDA.1020707@aol.com> <4D65D0B6.2090400@aim.com> <4D65D671.1010808@aol.com> Message-ID: <4D663955.8030408@ieee.org> On 01/-10/-28163 02:59 PM, Edward Martinez wrote: > On 02/23/11 19:29, Corey Richardson wrote: >> On 02/23/2011 10:22 PM, Edward Martinez wrote: >>> Hi, >>> >>> I'm new to the list and programming. >>> i have a question, why when i evaluate strings ie 'a'> '3' it reports >>> true, how does python come up with that? >> Welcome! As far as I know, it compares the value of the ord()'s. >> >>>>> ord('a') >> 97 >>>>> ord('3') >> 51 >> >> This is their number in the ASCII system. You can also do this: >> >>>>> chr(97) >> 'a' >>>>> chr(51) >> '3' >> A string is effectively an array of characters. Each one may be ASCII or Unicode or other, depending partly on your Python version. Each character has an ord() between 0 and 255, or between 0 and 65535. Except for some values below 0x20 (eg. tab, newline), these are printable. So you can make a chart for your own system with a fairly simple loop. Comparison is done left to right on the two strings, comparing one character at a time. If there are no control characters, this approximates what a dictionary order would do. But notice that all the capital letters appear before any of the lowercase characters. And that if you have accented characters, they're generally nowhere near the unaccented versions. One other point: if one string begins with all the characters in the other (eg. 'cat' and 'catatonic'), the longer string is then considered "greater". DaveA From steve at pearwood.info Thu Feb 24 11:59:30 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 Feb 2011 21:59:30 +1100 Subject: [Tutor] Convert string to long In-Reply-To: References: Message-ID: <4D663A12.8000802@pearwood.info> tee chwee liong wrote: > hi, > > is there a way to convert from string to long? my_string = "1234" my_long = long(my_string) We're happy to help you, but you should make some effort to help yourself. Have you worked through the Python tutorial? Don't just *read* it, actually follow the instructions and *do* it. From Python 2.5 on, the function int() will do the same thing and there's never any reason to use long(). From Python 3, long() is removed. int() (and long) also take an optional second argument, the base to use: >>> int("11") # decimal by default 11 >>> int("11", 2) # binary 3 -- Steven From ranjand2005 at gmail.com Thu Feb 24 12:29:27 2011 From: ranjand2005 at gmail.com (ranjan das) Date: Thu, 24 Feb 2011 16:59:27 +0530 Subject: [Tutor] Clubbing simillar elements together in a list with repeating elements Message-ID: I have a list a=[1,2,3,4,2,5,5,4,6,7,8] I want to club the repeating elements together and my output should be something like a_new=[ [1], [2,2], [3], [4,4] , [5,5,5],[6], [7], [8]] How do I do this? I tried the following but it is not giving me the desired result a=[1,2,3,2,3,4,5,4,5,5,6] Output=[] Unique=[] Duplicate=[] FinList=[] for element in a: if element not in Unique: Unique.append(element) else: Duplicate.append(element) for element in Unique: if element in Duplicate: count=0 for i in Duplicate: if i==element: count=count+1 for j in range(count+1): FinList.append(element) else: FinList.append([element]) print Unique print Duplicate print FinList *result:* Unique=[1, 2, 3, 4, 5, 6] Duplicate=[2, 3, 4, 5, 5] FinList=[[1], 2, 2, 3, 3, 4, 4, 5, 5, 5, [6]] I want the FinList as [ [1], [2,2], [3,3], [4,4] , [5,5,5],[6]] -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Thu Feb 24 12:50:10 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Thu, 24 Feb 2011 11:50:10 +0000 Subject: [Tutor] Convert string to long In-Reply-To: References: , Message-ID: > int(s,16) for a hex string > great but the leading zeroes are being truncated. i want it to be: 0x0000001800000400000000000000000000000000000000000000000000000000L >>> array0='00000018000004000000000000000000' >>> array1='00000000000000000000000000000000' >>> array=array0+array1 >>> a=int(array,16) >>> print a 647038726439367532107969464256319505531941876229785714677657987186688 >>> print hex(a) 0x1800000400000000000000000000000000000000000000000000000000L >>> pls advise. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Thu Feb 24 13:03:26 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 24 Feb 2011 13:03:26 +0100 Subject: [Tutor] Clubbing simillar elements together in a list with repeating elements In-Reply-To: References: Message-ID: Won't give you all the ansers, but here's a few tips. On Thu, Feb 24, 2011 at 12:29 PM, ranjan das wrote: > > I have a list > > a=[1,2,3,4,2,5,5,4,6,7,8] > > I want to club the repeating elements together and my output should be > something like > > a_new=[ [1], [2,2], [3], [4,4] , [5,5,5],[6], [7], [8]] > In you original list a, there's only 2 fives. Please make sure that you type everything in accurately, and use the same example throughout, or we get confused far more easily. > How do I do this? > > I tried the following but it is not giving me the desired result > > > for element in Unique: > ??? if element in Duplicate: > ??????? count=0 > ??????? for i in Duplicate: > ??????????? if i==element: > ??????????????? count=count+1 > > ??????? for j in range(count+1): > ??????????? FinList.append(element) > ??? else: > ??????? FinList.append([element]) > The mistake is in that piece. Note that if the element is not in duplicate, you append it *inside* a separate list. But if it *is* in duplicate, you append all the elements to FinList directly, *without* creating a separate list for them. Note that you don't have to use the range() function. Try this in the interpreter: >>> [5] * 3 [5, 5, 5] Can you use that neat little multiply trick to avoid having to loop over a range? This problem has come up before, and you can do it much, much quicker. You can create the Unique list much easier by simply using the set() function. Then, the count() method counts how often an item appears in a list. Finally, we can make it even shorter with the groupby function from the itertools package, which was pretty much made for this: HTH, Hugo From wprins at gmail.com Thu Feb 24 14:08:37 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 24 Feb 2011 13:08:37 +0000 Subject: [Tutor] Convert string to long In-Reply-To: References: Message-ID: On 24 February 2011 11:50, tee chwee liong wrote: > > int(s,16) for a hex string > > > > great but the leading zeroes are being truncated. > You need to seperate the concept of display/formatting of some thing from the actual thing/value being displayed. Normally when we humans communicate numbers and or work with them, leaading zero's are not used, so normally most computer systems and languages will not display numbers with leading zeros by default. It is therefore up to you to *tell* the computer you want leading zeros in order for it to produce them from the actual value being represented. Furthermore you need to distinguish (as does the computer) between different object types (namely strings and numbers) as they are different animals which are handled differently by the computer. A number, as already mentioned, will be by default not displayed with leading zeros as that's normally how humans are used to seeing numbers. A string however is a data structure that can contain arbitrary characters. The computer therefore will generally just display a string with whatever is in it (some exceptions apply for escape characters etc depending on context etc. but ignore that for the moment.) Now, a string may contain characters that happens to be the character representation of number (with or without leading zeros) but yet to the computer this remains a string and only a string, until you *explicitly* tell it otherwise and explicitly convert it into an actual number object. After you've done this of course, the computer will know that the thing now being dealt with is in fact a number, and will therefore display/format the number as it usually does (e.g. without leading zeros), again, unless you tell it to display/format it otherwise. So at the risk of belaboring the points: 1) Get a handle on the fact that numbers and strings are different things, and that on the one hand you're converting between them. 2) Get a handle on the fact that different things can furthermore be displayed/formatted in a variety of different ways, and there may be many ways to display or represent a given thing, which again is up to *you* to control/specify. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Feb 24 14:28:14 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 24 Feb 2011 08:28:14 -0500 Subject: [Tutor] help In-Reply-To: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> References: <4d65db6d.2b35ec0a.599e.ffffa120@mx.google.com> Message-ID: <4D665CEE.8000902@gmail.com> Request: When posting a question use a meaningful subject line, as some of us track email by subject. -- Bob Gailer 919-636-4239 Chapel Hill NC From joel.goldstick at gmail.com Thu Feb 24 14:32:37 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 24 Feb 2011 08:32:37 -0500 Subject: [Tutor] Convert string to long In-Reply-To: References: Message-ID: On Thu, Feb 24, 2011 at 8:08 AM, Walter Prins wrote: > > > On 24 February 2011 11:50, tee chwee liong wrote: > >> > int(s,16) for a hex string >> > >> >> great but the leading zeroes are being truncated. >> > > You need to seperate the concept of display/formatting of some thing from > the actual thing/value being displayed. > > Normally when we humans communicate numbers and or work with them, leaading > zero's are not used, so normally most computer systems and languages will > not display numbers with leading zeros by default. It is therefore up to > you to *tell* the computer you want leading zeros in order for it to produce > them from the actual value being represented. > > Furthermore you need to distinguish (as does the computer) between > different object types (namely strings and numbers) as they are different > animals which are handled differently by the computer. > > A number, as already mentioned, will be by default not displayed with > leading zeros as that's normally how humans are used to seeing numbers. > > A string however is a data structure that can contain arbitrary > characters. The computer therefore will generally just display a string > with whatever is in it (some exceptions apply for escape characters etc > depending on context etc. but ignore that for the moment.) > > Now, a string may contain characters that happens to be the character > representation of number (with or without leading zeros) but yet to the > computer this remains a string and only a string, until you *explicitly* > tell it otherwise and explicitly convert it into an actual number object. > After you've done this of course, the computer will know that the thing now > being dealt with is in fact a number, and will therefore display/format the > number as it usually does (e.g. without leading zeros), again, unless you > tell it to display/format it otherwise. > > So at the risk of belaboring the points: 1) Get a handle on the fact that > numbers and strings are different things, and that on the one hand you're > converting between them. 2) Get a handle on the fact that different things > can furthermore be displayed/formatted in a variety of different ways, and > there may be many ways to display or represent a given thing, which again is > up to *you* to control/specify. > > Walter > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Take a look at this code. You get your hex number as a string. It has 0x on the left which shows its hexidecimal. Get rid of it with the slice (h[2:] in my example) Now, use the zfill method on the string to pad the result to 5 characters. You can pad to any size you want. Then add back the 0x prefix q.e.d. >>> h = hex(546) >>> h '0x222' >>> n = h[2:] >>> n '222' >>> n.zfill(5) '00222' >>> '0x' + n.zfill(5) '0x00222' >>> This can all be simplified (well .. shortened!) to >>> '0x' + hex(543)[2:].zfill(5) '0x0021f' -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Thu Feb 24 15:03:32 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Thu, 24 Feb 2011 14:03:32 +0000 Subject: [Tutor] Convert string to long In-Reply-To: References: , , , , Message-ID: >>> '0x' + hex(543)[2:].zfill(5) '0x0021f' this is a good way but it's still in string format. but if i convert it to long, then the leading 0s will be truncated. i guess can't have it both way. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Feb 24 15:20:46 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 24 Feb 2011 15:20:46 +0100 Subject: [Tutor] Convert string to long In-Reply-To: References: Message-ID: On Thu, Feb 24, 2011 at 3:03 PM, tee chwee liong wrote: >>>> '0x' + hex(543)[2:].zfill(5) > '0x0021f' > > this is a good way but it's still in string format. but if i convert it to > long, then the leading 0s will be truncated. i guess can't have it both way. A long is just a number. You cannot say that a number has or does not have leading zeroes. Only _a representation of_ that number has. The numbers 3, 1+2 and 0000000000003 are all the same number, so you cannot say that the first does not have leading zeroes whereas the last one has. To make the concept of 'leading zeroes' a meaningful one, you _first_ have to re-convert the number to a string. Whether or not there are leading zeroes depends on how that conversion is done. If you use Python's standard conversion method, the result will be a string representation without leading zeroes, but there are other conversion methods that do give leading zeroes. -- Andr? Engels, andreengels at gmail.com From joel.goldstick at gmail.com Thu Feb 24 15:27:25 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 24 Feb 2011 09:27:25 -0500 Subject: [Tutor] Convert string to long In-Reply-To: References: Message-ID: On Thu, Feb 24, 2011 at 9:03 AM, tee chwee liong wrote: > >>> '0x' + hex(543)[2:].zfill(5) > '0x0021f' > > this is a good way but it's still in string format. but if i convert it to > long, then the leading 0s will be truncated. i guess can't have it both way. > > > > > > > > > > _______________________________________________ Tutor maillist - > Tutor at python.org To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > As was explained by another poster earlier, the idea of leading zeros in the internal representation of a number is meaningless. If I have 05 of something, or I have 5 of something I have the same number of things. So, when the python shell prints out a number, it has no reason to print leading zeros. How would it know you want them? If you do want leading zeros because it makes your display look more proper, then you do the string formatting to get what you need. Go back and read some tutorials or the python manual to understand data types. -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From pyhx0r at gmail.com Thu Feb 24 15:52:12 2011 From: pyhx0r at gmail.com (pyhx0r) Date: Thu, 24 Feb 2011 21:52:12 +0700 Subject: [Tutor] Help on Python Looping Please Message-ID: Dear All, I?m new in programming and I?m studying Python now. I use Python 3.1.2 and learn from Dive Into Python 3 book (Mark Pilgrim, Thank you very much for him). I?ve learned list, tuple, set, dictionary and little bit about looping. I?m so confused about looping in first Python Program in that book (humanize.py), it?s the code: SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], 1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']} def approximate_size(size, a_kilobyte_is_1024_bytes=True): '''Convert a file size to human-readable form. Keyword arguments: size -- file size in bytes a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024 if False, use multiples of 1000 Returns: string ''' if size < 0: raise ValueError('number must be non-negative') multiple = 1024 if a_kilobyte_is_1024_bytes else 1000 for suffix in SUFFIXES[multiple]: size /= multiple if size < multiple: return '{0:.1f} {1}'.format(size, suffix) raise ValueError('number too large') if __name__ == '__main__': print(approximate_size(1000000000000, False)) print(approximate_size(1000000000000)) Result: 1.0 TB 931.3 GiB I?ve shorted the code be: >>> SUFFIXES = {1000: ['KB','MB','GB'], 1024: ['KiB','MiB','GiB']} >>> multiple = 1000 >>> size = 2300 >>> for suffix in SUFFIXES[multiple]: size /= multiple if size < multiple: '{0:.1f} {1}'.format(size, suffix) '2.3 KB' '0.0 MB' '0.0 GB' >>> *Why do in my code, it loops to all values and not in Mark Pilgrim?s code?* Best Regards, [ pyhx0r - hx0r-labs.org ] -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu Feb 24 16:08:05 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 24 Feb 2011 15:08:05 +0000 Subject: [Tutor] Help on Python Looping Please In-Reply-To: References: Message-ID: On 24 February 2011 14:52, pyhx0r wrote: > *Why do in my code, it loops to all values and not in Mark Pilgrim?s code? > * > > Because in Mark's code the loop is terminated by the return statement (contained in the utility function approximate_size().) In your code you've removed the entire function including the return statement, consequently the loop runs to completion. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.klaitos at gmail.com Thu Feb 24 16:48:20 2011 From: chris.klaitos at gmail.com (Christopher Brookes) Date: Thu, 24 Feb 2011 16:48:20 +0100 Subject: [Tutor] Python object Message-ID: Hi, i'm new in python. I'm trying to create a small fight program in object. I've created __init__ (its works) but when i'm trying to display init param i'm getting param and "None" every time. Why ? def GetAllAtrib(self): print '-----------------------------------------------' print self.name print self.description print self.type print '-----------------------------------------------' give ->> ----------------------------------------------- Klaitos Soldier very strong Soldier ----------------------------------------------- *None *<<<<<<<<-- WHY ARE U HERE ?? Yours, -- Brookes Christopher. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu Feb 24 17:13:47 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 24 Feb 2011 11:13:47 -0500 Subject: [Tutor] Python object In-Reply-To: References: Message-ID: I don't understand what you are trying to do? I'm assuming def GetAllAtrib is a method within a class; perhaps you could copy more the code base? It seems to be locating the three elements you have in that method just fine, but I'm guessing you have another print statement somewhere that is causing it to print None. On Thu, Feb 24, 2011 at 10:48 AM, Christopher Brookes < chris.klaitos at gmail.com> wrote: > Hi, i'm new in python. > I'm trying to create a small fight program in object. > > I've created __init__ (its works) but when i'm trying to display init param > i'm getting param and "None" every time. Why ? > > def GetAllAtrib(self): > print '-----------------------------------------------' > print self.name > print self.description > print self.type > print '-----------------------------------------------' > > give ->> > > ----------------------------------------------- > Klaitos > Soldier very strong > Soldier > ----------------------------------------------- > *None *<<<<<<<<-- WHY ARE U HERE > ?? > > Yours, > > > > -- > Brookes Christopher. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Feb 24 17:22:10 2011 From: davea at ieee.org (Dave Angel) Date: Thu, 24 Feb 2011 11:22:10 -0500 Subject: [Tutor] Help on Python Looping Please In-Reply-To: References: Message-ID: <4D6685B2.5090208@ieee.org> On 01/-10/-28163 02:59 PM, pyhx0r wrote: > Dear All, > > > > multiple = 1024 if a_kilobyte_is_1024_bytes else 1000 > for suffix in SUFFIXES[multiple]: > size /= multiple > if size< multiple: > return '{0:.1f} {1}'.format(size, suffix) > > > I?ve shorted the code be: > > >>>> SUFFIXES = {1000: ['KB','MB','GB'], > > 1024: ['KiB','MiB','GiB']} >>>> multiple = 1000 >>>> size = 2300 >>>> for suffix in SUFFIXES[multiple]: > size /= multiple > if size< multiple: > '{0:.1f} {1}'.format(size, suffix) > > > > > *Why do in my code, it loops to all values and not in Mark Pilgrim?s code?* > (Is there a reason you double-spaced all that code? It makes it very hard to read, and quite difficult to quote, since I had to delete every other line.) You wrote your code inline, and not as a function. And you omitted the return statement. So the loop won't return, it'll run to completion. Another way to exit a loop early is to use the break statement. DaveA From __peter__ at web.de Thu Feb 24 17:26:20 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Feb 2011 17:26:20 +0100 Subject: [Tutor] Python object References: Message-ID: Christopher Brookes wrote: > Hi, i'm new in python. > I'm trying to create a small fight program in object. > > I've created __init__ (its works) but when i'm trying to display init > param i'm getting param and "None" every time. Why ? > > def GetAllAtrib(self): > print '-----------------------------------------------' > print self.name > print self.description > print self.type > print '-----------------------------------------------' > > give ->> > > ----------------------------------------------- > Klaitos > Soldier very strong > Soldier > ----------------------------------------------- > *None *<<<<<<<<-- WHY ARE U HERE My crystall ball says: because you invoke the above method with something like print soldier.GetAllAttrib() instead of just soldier.GetAllAttrib() If I'm guessing wrong please provide the relevant source code. By the way, show_all_attributes() would be a better name for your method as it would make the problem in your code obvious. From pyhx0r at gmail.com Thu Feb 24 17:36:09 2011 From: pyhx0r at gmail.com (pyhx0r) Date: Thu, 24 Feb 2011 23:36:09 +0700 Subject: [Tutor] Help on Python Looping Please In-Reply-To: <4D6685B2.5090208@ieee.org> References: <4D6685B2.5090208@ieee.org> Message-ID: Dear All, Thank you for your advise, it's helpful for me. NB: To DaveA, It was copy-paste from my notepad so the indentation went wrong :( +---+------+---+ | py | h | x0r | +---+------+---+ ? 1 3 0 E2 C 9 ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From eyeye689 at gmail.com Thu Feb 24 16:56:44 2011 From: eyeye689 at gmail.com (Neven Dragojlovic) Date: Thu, 24 Feb 2011 15:56:44 +0000 Subject: [Tutor] having difficulty installing python Message-ID: Please can someone help me? I am trying to install python 2.5.4 on MacBookPro running on OS10.6.6, but when I try to set it up on Terminal by running "python setup.py install" I get the following: IDLE Subprocess: Connection to IDLE GUI failed, exiting. Tk_MacOSXSetupTkNotifier: first [load] of TkAqua has to occur in the main thread! with an extra pop-up saying it can not access port 8833. When I try to install that port with "sudo port install `8833'" it again says it can not find that port. What is going on? The trouble started when I installed X11 and fink 0.29.16, with all those files coming in and I allowed them. What do I do now? Thank you ahead of time, Neven From nitinchandra1 at gmail.com Thu Feb 24 17:43:16 2011 From: nitinchandra1 at gmail.com (nitin chandra) Date: Thu, 24 Feb 2011 22:13:16 +0530 Subject: [Tutor] merging 2 files. In-Reply-To: References: Message-ID: On Thu, Feb 24, 2011 at 9:18 PM, nitin chandra wrote: > Hi Martin, > > Thanks a lot. It did work, but I am trying to break it down and ?understand > >> ?import csv >> >> ?# -- build the lookup table >> ?# >> ?lookup = dict() >> ?file0 = csv.reader(open('jhun.csv','r')) >> ?for row in file0: >> ? ? ?lookup[ row[0] ] = row >> >> ?# -- now, read through the >> ?# >> ?file1 = csv.reader(open('test.csv','r')) >> ?for row in file1: > > modified it to > > for row1 in file1: > >> ? ? ?exists = lookup.get( row[0], None ) > > ? ? exists = lookup.get(row1[0], None) > >> ? ? ?if exists: >> ? ? ? ? ?print row, exists ?# -- print out only what you want >> ? ? ?else: >> ? ? ? ? ?pass ?# -- do you need to do something if no lookup entry? >> > > but some how It is reading "test.csv" from row 8000+ onwards not from > 1st row. Dunno if it doing the same thing with jhun.csv. screen > scrolls by. > >> >> ?: I am in need of the solution as client breathing down my neck. >> >> They always do. ?Wear a scarf. >> >> -Martin >> > I shall try a fire proof scarf ... thanks :) > > Nitin > From steve at alchemy.com Thu Feb 24 17:25:32 2011 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 24 Feb 2011 08:25:32 -0800 Subject: [Tutor] Python object In-Reply-To: References: Message-ID: <4D66867C.4040300@alchemy.com> On 24-Feb-11 08:13, James Reynolds wrote: > I don't understand what you are trying to do? > > I'm assuming def GetAllAtrib is a method within a class; perhaps you > could copy more the code base? > > It seems to be locating the three elements you have in that method just > fine, but I'm guessing you have another print statement somewhere that > is causing it to print None. Or perhaps calling the method from an IDE or interactive prompt, where the print statements in the method are printing as intended, but the interactive environment itself is printing the return value from the method? This could happen if you did this at the prompt: >>> print object.GetAllAtrib() This is a case where giving us more information about what you're doing helps us answer your question better. --steve > > > On Thu, Feb 24, 2011 at 10:48 AM, Christopher Brookes > > wrote: > > Hi, i'm new in python. > I'm trying to create a small fight program in object. > > I've created __init__ (its works) but when i'm trying to display > init param i'm getting param and "None" every time. Why ? > > def GetAllAtrib(self): > print '-----------------------------------------------' > print self.name > print self.description > print self.type > print '-----------------------------------------------' > > give ->> > > ----------------------------------------------- > Klaitos > Soldier very strong > Soldier > ----------------------------------------------- > *None *<<<<<<<<-- WHY ARE U HERE ?? > > Yours, > > > > -- > Brookes Christopher. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From mehgcap at gmail.com Thu Feb 24 17:48:05 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 24 Feb 2011 11:48:05 -0500 Subject: [Tutor] relative imports Message-ID: Hi all, I am trying to place some common files into a folder so that all files in other folders can access the common files. That is, the file for a card class, a deck class, and so on are all in a "common" folder. At this folder's level are also all folders for games so that all games' files can simply say from .common import cards However, it is not working out that way. Attached is a simple example. Try running a\common\vars.py and you will get an error, even though the "a" folder has a __init__.py file in it. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap -------------- next part -------------- A non-text attachment was scrubbed... Name: a.zip Type: application/zip Size: 569 bytes Desc: not available URL: From mehgcap at gmail.com Thu Feb 24 17:49:46 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 24 Feb 2011 11:49:46 -0500 Subject: [Tutor] relative imports In-Reply-To: References: Message-ID: Sorry, I forgot to say that the error is: ValueError: attempted relative import in non-package. On 2/24/11, Alex Hall wrote: > Hi all, > I am trying to place some common files into a folder so that all files > in other folders can access the common files. That is, the file for a > card class, a deck class, and so on are all in a "common" folder. At > this folder's level are also all folders for games so that all games' > files can simply say > from .common import cards > However, it is not working out that way. Attached is a simple example. > Try running a\common\vars.py and you will get an error, even though > the "a" folder has a __init__.py file in it. > > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com; http://www.facebook.com/mehgcap > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From wprins at gmail.com Thu Feb 24 17:55:46 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 24 Feb 2011 16:55:46 +0000 Subject: [Tutor] Help on Python Looping Please In-Reply-To: <4D6685B2.5090208@ieee.org> References: <4D6685B2.5090208@ieee.org> Message-ID: On 24 February 2011 16:22, Dave Angel wrote: > > (Is there a reason you double-spaced all that code? It makes it very hard > to read, and quite difficult to quote, since I had to delete every other > line.) > For what it's worth the code came out perfectly fine on my email reader (GMail). (No double spacing, courier formatted, all in all pretty easy to read. What email client are you using?) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.klaitos at gmail.com Thu Feb 24 19:58:00 2011 From: chris.klaitos at gmail.com (Christopher Brookes) Date: Thu, 24 Feb 2011 19:58:00 +0100 Subject: [Tutor] Dictionnaries in object Message-ID: Hi, I want to create some powers in my fight program. I want to know if dictionnaries is the best solution to do it. For now its look like this : //French name and description, don't care about it ;) power1= {} power1['Name'] = 'Flammes infernales' power1['Description'] = 'Embrase lenemi et le feu bruler' power2= {} power2['Name'] = 'Froid devorant' power2['Description'] = 'Gele lenemi sur place' powerAll= [power1,power2] but if i want to create like 20 powers, it will be long no ? is there any solution shorter (and better ?) Thank you for reading, -- Brookes Christopher. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Thu Feb 24 20:04:15 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Thu, 24 Feb 2011 14:04:15 -0500 Subject: [Tutor] Dictionnaries in object In-Reply-To: References: Message-ID: <4D66ABAF.9040703@aim.com> On 02/24/2011 01:58 PM, Christopher Brookes wrote: > Hi, > > I want to create some powers in my fight program. > I want to know if dictionnaries is the best solution to do it. > > For now its look like this : > > > //French name and description, don't care about it ;) > > power1= {} > power1['Name'] = 'Flammes infernales' > power1['Description'] = 'Embrase lenemi et le feu bruler' > > power2= {} > power2['Name'] = 'Froid devorant' > power2['Description'] = 'Gele lenemi sur place' > > powerAll= [power1,power2] > > but if i want to create like 20 powers, it will be long no ? is there any > solution shorter (and better ?) > > Thank you for reading, powerAll = {"Flammes infernales": "Embrase lenemi et le feu bruler", "Froid devorant": "Gele lenemi sur place"} Have it implicit that the key is the name and the value is the description. That's how I would do it, at least. -- Corey Richardson From bgailer at gmail.com Thu Feb 24 20:17:05 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 24 Feb 2011 14:17:05 -0500 Subject: [Tutor] Dictionnaries in object In-Reply-To: References: Message-ID: <4D66AEB1.8090000@gmail.com> On 2/24/2011 1:58 PM, Christopher Brookes wrote: > Hi, > > I want to create some powers in my fight program. > I want to know if dictionnaries is the best solution to do it. > > For now its look like this : > > > //French name and description, don't care about it ;) > > power1= {} > power1['Name'] = 'Flammes infernales' > power1['Description'] = 'Embrase lenemi et le feu bruler' > > power2= {} > power2['Name'] = 'Froid devorant' > power2['Description'] = 'Gele lenemi sur place' > > powerAll= [power1,power2] > > but if i want to create like 20 powers, it will be long no ? is there > any solution shorter (and better ?) > 1 - define a Power class and create instances class Power: def __init__(self, name, desc): self.name = name self.desc = desc powerAll = [ Power('Flammes infernales' , 'Embrase lenemi et le feu bruler'), Power('Froid devorant', 'Gele lenemi sur place')] -- Bob Gailer 919-636-4239 Chapel Hill NC From chris.klaitos at gmail.com Thu Feb 24 22:54:10 2011 From: chris.klaitos at gmail.com (Christopher Brookes) Date: Thu, 24 Feb 2011 22:54:10 +0100 Subject: [Tutor] Display all field of a listuples Message-ID: Hi i would like to display all the field of my powerAll like this : Choose a power : Froid devorant : Embrase lenemi et le feu bruler Flammes infernales : 'Gele lenemi sur place ----------------------------- class Character(): def ChoosePouvoirUnique(self): print ("Choose a power") for Power in powerAll: print (Power) class Power: def __init__(self, name, desc): self.name = name self.desc = desc powerAll = [ Power('Flammes infernales' , 'Embrase lenemi et le feu bruler'), Power('Froid devorant', 'Gele lenemi sur place')] But he won't display it :( i've try For PowerName,PowerDesc in powerAll: print (PowerName, PowerDesc) but it doesn't work ! Thank you again.. -- Brookes Christopher. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Feb 24 22:59:08 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 24 Feb 2011 16:59:08 -0500 Subject: [Tutor] Dictionnaries in object In-Reply-To: References: <4D66AEB1.8090000@gmail.com> Message-ID: <4D66D4AC.5020100@gmail.com> Always reply-all so a copy goes to the list. On 2/24/2011 2:20 PM, Christopher Brookes wrote: > Oh yes, did'nt think about it. I love this solution Ty :) ! > > BTW i add Character class, how can i add to it ONE power ? Sorry I don't understand. > > class Character(): > """ Classe du personnage, ses movements, attaques, geston de > l'exp?rience et du niveau""" > def > __init__(self,name,description,type,strenght,intelligence,agility,health,level): > self.name = name > self.description = description > self.type = type > self.strenght = strenght > self.intelligence = intelligence > self.agility = agility > self.health = health > self.level = level > > def hit(self,target): > """ Calcule la puissance du coup et r?duit la vie de la cible""" > target.health -=self.strenght // care about it is - = > print (self.name , "hit",target.name > , "for", self.strenght, "damage") > > > > > Sorry, object is very new for me... > > > 2011/2/24 bob gailer > > > On 2/24/2011 1:58 PM, Christopher Brookes wrote: > > Hi, > > I want to create some powers in my fight program. > I want to know if dictionnaries is the best solution to do it. > > For now its look like this : > > > //French name and description, don't care about it ;) > > power1= {} > power1['Name'] = 'Flammes infernales' > power1['Description'] = 'Embrase lenemi et le feu bruler' > > power2= {} > power2['Name'] = 'Froid devorant' > power2['Description'] = 'Gele lenemi sur place' > > powerAll= [power1,power2] > > but if i want to create like 20 powers, it will be long no ? > is there any solution shorter (and better ?) > > 1 - define a Power class and create instances > > class Power: > def __init__(self, name, desc): > self.name = name > self.desc = desc > > powerAll = [ > Power('Flammes infernales' , 'Embrase lenemi et le feu bruler'), > Power('Froid devorant', 'Gele lenemi sur place')] > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > > > > -- > Brookes Christopher. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Thu Feb 24 23:09:26 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 24 Feb 2011 17:09:26 -0500 Subject: [Tutor] Display all field of a listuples In-Reply-To: References: Message-ID: On 2/24/11, Christopher Brookes wrote: > Hi i would like to display all the field of my powerAll like this : > > Choose a power : > Froid devorant : Embrase lenemi et le feu bruler > Flammes infernales : 'Gele lenemi sur place > > ----------------------------- > class Character(): > def ChoosePouvoirUnique(self): > print ("Choose a power") > for Power in powerAll: > print (Power) You need a __init__() function in this class, as with any class. > > class Power: > def __init__(self, name, desc): > self.name = name > self.desc = desc > > > > > powerAll = [ > Power('Flammes infernales' , 'Embrase lenemi et le feu bruler'), > Power('Froid devorant', 'Gele lenemi sur place')] > > > But he won't display it :( How are you calling it? That is, what code are you using to try to display the contents of the list? Is powerAll supposed to be a variable in a class? If so, it should be self.powerAll. > > i've try For PowerName,PowerDesc in powerAll: > print (PowerName, PowerDesc) > > but it doesn't work ! What does that mean? It prints something strange, or you get an error? What error is it? Also, "for" should be lowercase, though I am honestly not sure that this is a requirement(though I believe it is). > > Thank you again.. > > -- > Brookes Christopher. > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Thu Feb 24 23:29:14 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Feb 2011 09:29:14 +1100 Subject: [Tutor] having difficulty installing python In-Reply-To: References: Message-ID: <4D66DBBA.2020806@pearwood.info> Neven Dragojlovic wrote: > Please can someone help me? I am trying to install python 2.5.4 on > MacBookPro running on OS10.6.6, This is a mailing list for beginners to programming Python, not a general Python mailing list. It's quite likely that nobody here knows enough about installing software on OS X to help you. I suggest you take this question to either a dedicated Mac forum, or to the main Python help list python-list at python.org, which is also available as a newsgroup comp.lang.python. A couple of further comments: Unless you really have need for Python 2.5, I don't think it's worth wasting your time on such an old version. The current versions of Python are 2.7 and 3.2, so you are missing out on probably 3-5 years of bug fixes and new features. I recommend you go straight to 2.7 and 3.2. If you only want to install one version, just use 2.7. If 2.7 and 3.2 aren't yet available for Mac, go for 2.6 and 3.1. Don't under any circumstances use 3.0, it was rubbish :) > but when I try to set it up on > Terminal by running "python setup.py install" I get the following: > IDLE Subprocess: Connection to IDLE GUI failed, exiting. > Tk_MacOSXSetupTkNotifier: first [load] of TkAqua has to occur in the > main thread! > with an extra pop-up saying it can not access port 8833. When I try to > install that port with "sudo port install `8833'" it again says it can > not find that port. I don't know what the "port" command might do on OS X (possibly it means MacPorts, see below), but I think you are misunderstanding the error message. Normally port refers to a networking port, and if IDLE is complaining about not accessing port 8833, that means your firewall is blocking access to it. You don't install port 8833, because it is automatically there, but you need to tell your firewall to trust connections to it from localhost. You might also like to use the MacPorts program for managing Unix software on your Mac. I haven't used it myself, I don't have a Mac, but I have heard good things about it. -- Steven From steve at pearwood.info Thu Feb 24 23:46:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Feb 2011 09:46:50 +1100 Subject: [Tutor] Display all field of a listuples In-Reply-To: References: Message-ID: <4D66DFDA.5010500@pearwood.info> Alex Hall wrote: > On 2/24/11, Christopher Brookes wrote: >> Hi i would like to display all the field of my powerAll like this : >> >> Choose a power : >> Froid devorant : Embrase lenemi et le feu bruler >> Flammes infernales : 'Gele lenemi sur place >> >> ----------------------------- >> class Character(): >> def ChoosePouvoirUnique(self): >> print ("Choose a power") >> for Power in powerAll: >> print (Power) > You need a __init__() function in this class, as with any class. That's not strictly correct. You don't *need* an __init__ method, unless your class needs to be initialised. Most classes will, but some do not. [...] > Also, "for" should be lowercase, though I am > honestly not sure that this is a requirement(though I believe it is). It certainly is. Python is case sensitive, so "for" and "FOR" and "For" are different. "for" is a Python keyword with special meaning. The others are just words with no special meaning. -- Steven From chris.klaitos at gmail.com Fri Feb 25 00:02:06 2011 From: chris.klaitos at gmail.com (Christopher Brookes) Date: Fri, 25 Feb 2011 00:02:06 +0100 Subject: [Tutor] Display all field of a listuples In-Reply-To: <4D66DFDA.5010500@pearwood.info> References: <4D66DFDA.5010500@pearwood.info> Message-ID: class Character: def __init__(self, name): self.name = name def ChoosePouvoirUnique(self): """ Permet de choisir le pouvoir unique du personnage """ print ("Veuillez choisir votre pouvoir unique dans la liste") for PowerNom,PowerDesc in powerAll: print (PowerNom, PowerDesc) class Power: def __init__(self, name, desc): self.name = name self.desc = desc powerAll = [ Power('Flammes infernales' , 'Embrase lenemi et le feu bruler'), Power('Froid devorant', 'Gele lenemi sur place')] hero1 = Character("Klaitos") hero1.ChoosePouvoirUnique() im *WANT to display this* : Froid devorant : Gele lenemi sur place Flammes infernales : Embrase lenemi et le feu bruler I don't know how to get this ? :( 2011/2/24 Steven D'Aprano > Alex Hall wrote: > >> On 2/24/11, Christopher Brookes wrote: >> >>> Hi i would like to display all the field of my powerAll like this : >>> >>> Choose a power : >>> Froid devorant : Embrase lenemi et le feu bruler >>> Flammes infernales : 'Gele lenemi sur place >>> >>> ----------------------------- >>> class Character(): >>> def ChoosePouvoirUnique(self): >>> print ("Choose a power") >>> for Power in powerAll: >>> print (Power) >>> >> > You need a __init__() function in this class, as with any class. >> > > That's not strictly correct. You don't *need* an __init__ method, unless > your class needs to be initialised. Most classes will, but some do not. > > > [...] > > Also, "for" should be lowercase, though I am >> honestly not sure that this is a requirement(though I believe it is). >> > > It certainly is. Python is case sensitive, so "for" and "FOR" and "For" are > different. "for" is a Python keyword with special meaning. The others are > just words with no special meaning. > > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Brookes Christopher. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mark at martialfit.net Fri Feb 25 00:26:37 2011 From: mark at martialfit.net (Mark Weil) Date: Thu, 24 Feb 2011 15:26:37 -0800 Subject: [Tutor] having difficulty installing python In-Reply-To: <4D66DBBA.2020806@pearwood.info> References: <4D66DBBA.2020806@pearwood.info> Message-ID: Is there a reason you don't want to use the newer, already pre-installed version? http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/python.1.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Fri Feb 25 00:33:05 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 24 Feb 2011 18:33:05 -0500 Subject: [Tutor] Display all field of a listuples In-Reply-To: References: <4D66DFDA.5010500@pearwood.info> Message-ID: On 2/24/11, Christopher Brookes wrote: > class Character: > def __init__(self, name): > self.name = name > > def ChoosePouvoirUnique(self): > """ Permet de choisir le pouvoir unique du personnage """ > print ("Veuillez choisir votre pouvoir unique dans la liste") > > > for PowerNom,PowerDesc in powerAll: > print (PowerNom, PowerDesc) > > > class Power: > def __init__(self, name, desc): > self.name = name > self.desc = desc > > powerAll = [ > Power('Flammes infernales' , 'Embrase lenemi et le feu bruler'), > Power('Froid devorant', 'Gele lenemi sur place')] > > hero1 = Character("Klaitos") > hero1.ChoosePouvoirUnique() > > im *WANT to display this* : > > Froid devorant : Gele lenemi sur place > Flammes infernales : Embrase lenemi et le feu bruler > > I don't know how to get this ? :( Again, what is the error (traceback) you get when you try to run the code? > > 2011/2/24 Steven D'Aprano > >> Alex Hall wrote: >> >>> On 2/24/11, Christopher Brookes wrote: >>> >>>> Hi i would like to display all the field of my powerAll like this : >>>> >>>> Choose a power : >>>> Froid devorant : Embrase lenemi et le feu bruler >>>> Flammes infernales : 'Gele lenemi sur place >>>> >>>> ----------------------------- >>>> class Character(): >>>> def ChoosePouvoirUnique(self): >>>> print ("Choose a power") >>>> for Power in powerAll: >>>> print (Power) >>>> >>> >> You need a __init__() function in this class, as with any class. >>> >> >> That's not strictly correct. You don't *need* an __init__ method, unless >> your class needs to be initialised. Most classes will, but some do not. >> >> >> [...] >> >> Also, "for" should be lowercase, though I am >>> honestly not sure that this is a requirement(though I believe it is). >>> >> >> It certainly is. Python is case sensitive, so "for" and "FOR" and "For" >> are >> different. "for" is a Python keyword with special meaning. The others are >> just words with no special meaning. >> >> >> >> >> -- >> Steven >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Brookes Christopher. > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From mehgcap at gmail.com Fri Feb 25 00:34:46 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 24 Feb 2011 18:34:46 -0500 Subject: [Tutor] Display all field of a listuples In-Reply-To: References: <4D66DFDA.5010500@pearwood.info> Message-ID: On 2/24/11, Christopher Brookes wrote: > class Character: > def __init__(self, name): > self.name = name > > def ChoosePouvoirUnique(self): > """ Permet de choisir le pouvoir unique du personnage """ > print ("Veuillez choisir votre pouvoir unique dans la liste") > > > for PowerNom,PowerDesc in powerAll: > print (PowerNom, PowerDesc) > > > class Power: > def __init__(self, name, desc): > self.name = name > self.desc = desc > > powerAll = [ > Power('Flammes infernales' , 'Embrase lenemi et le feu bruler'), > Power('Froid devorant', 'Gele lenemi sur place')] > > hero1 = Character("Klaitos") > hero1.ChoosePouvoirUnique() > > im *WANT to display this* : > > Froid devorant : Gele lenemi sur place > Flammes infernales : Embrase lenemi et le feu bruler > > I don't know how to get this ? :( Again, what is the error (traceback) you get when you try to run the code? > > 2011/2/24 Steven D'Aprano > >> Alex Hall wrote: >> >>> On 2/24/11, Christopher Brookes wrote: >>> >>>> Hi i would like to display all the field of my powerAll like this : >>>> >>>> Choose a power : >>>> Froid devorant : Embrase lenemi et le feu bruler >>>> Flammes infernales : 'Gele lenemi sur place >>>> >>>> ----------------------------- >>>> class Character(): >>>> def ChoosePouvoirUnique(self): >>>> print ("Choose a power") >>>> for Power in powerAll: >>>> print (Power) >>>> >>> >> You need a __init__() function in this class, as with any class. >>> >> >> That's not strictly correct. You don't *need* an __init__ method, unless >> your class needs to be initialised. Most classes will, but some do not. >> >> >> [...] >> >> Also, "for" should be lowercase, though I am >>> honestly not sure that this is a requirement(though I believe it is). >>> >> >> It certainly is. Python is case sensitive, so "for" and "FOR" and "For" >> are >> different. "for" is a Python keyword with special meaning. The others are >> just words with no special meaning. >> >> >> >> >> -- >> Steven >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Brookes Christopher. > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From davea at ieee.org Fri Feb 25 00:37:10 2011 From: davea at ieee.org (Dave Angel) Date: Thu, 24 Feb 2011 18:37:10 -0500 Subject: [Tutor] Help on Python Looping Please In-Reply-To: References: <4D6685B2.5090208@ieee.org> Message-ID: <4D66EBA6.9020703@ieee.org> On 02/24/2011 11:55 AM, Walter Prins wrote: > On 24 February 2011 16:22, Dave Angel wrote: > >> >> (Is there a reason you double-spaced all that code? It makes it very hard >> to read, and quite difficult to quote, since I had to delete every other >> line.) >> > > For what it's worth the code came out perfectly fine on my email reader > (GMail). (No double spacing, courier formatted, all in all pretty easy to > read. What email client are you using?) > > Walter > I use Thunderbird 3.1.7 on Linux 10.04. In text mode, naturally, but I get the same result in html mode. The prose was properly spaced, and everyone else's messagesare properly spaced. But the code in that particular message was double-spaced. DaveA From alan.gauld at btinternet.com Fri Feb 25 01:42:16 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Feb 2011 00:42:16 -0000 Subject: [Tutor] Display all field of a listuples References: <4D66DFDA.5010500@pearwood.info> Message-ID: "Christopher Brookes" wrote > class Character: > def __init__(self, name): > self.name = name > > def ChoosePouvoirUnique(self): > """ Permet de choisir le pouvoir unique du personnage """ > print ("Veuillez choisir votre pouvoir unique dans la liste") > for PowerNom,PowerDesc in powerAll: > print (PowerNom, PowerDesc) powerAll is a list of Power objects. So you need to get each object then access the attributes inside the object using dot notation: for powerObject in powerAll: print "%s : %s" % (powerObject.name, powerObject.desc) > class Power: > def __init__(self, name, desc): > self.name = name > self.desc = desc > > powerAll = [ > Power('Flammes infernales' , 'Embrase lenemi et le feu bruler'), > Power('Froid devorant', 'Gele lenemi sur place')] > > hero1 = Character("Klaitos") > hero1.ChoosePouvoirUnique() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Feb 25 01:43:25 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Feb 2011 11:43:25 +1100 Subject: [Tutor] Display all field of a listuples In-Reply-To: References: <4D66DFDA.5010500@pearwood.info> Message-ID: <4D66FB2D.80906@pearwood.info> Christopher Brookes wrote: > class Power: > def __init__(self, name, desc): > self.name = name > self.desc = desc > > powerAll = [ > Power('Flammes infernales' , 'Embrase lenemi et le feu bruler'), > Power('Froid devorant', 'Gele lenemi sur place')] > im *WANT to display this* : > > Froid devorant : Gele lenemi sur place > Flammes infernales : Embrase lenemi et le feu bruler > > I don't know how to get this ? :( for pwr in powerAll: print pwr.name, pwr.desc If the order really matters to you, you need to sort powerAll into whatever order you prefer. -- Steven From wallenpb at gmail.com Fri Feb 25 04:30:05 2011 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 24 Feb 2011 21:30:05 -0600 Subject: [Tutor] accessing another system's environment In-Reply-To: References: Message-ID: I have times when it is useful for me to check the environment of a user system on our lan remotely while trouble shooting and issue with them. Now, this is quite easy to do while I am using a windows system via the computer management console. However, I am trying to do this via a linux workstation (which is joined to the domain, etc.). I cannot find a native facility to duplicate the computer management functions, so I thought I would write a program to fill the need. Not to mention, I thought it might be a good learning opportunity. --Bill On Thu, Feb 24, 2011 at 03:00, Alan Gauld wrote: > "Bill Allen" wrote > > > I know that I can use the following to get a listing of the environment of >> my own system. How can I do similar for another system on my network. >> This is for administrative purposes. >> > > Environments are user and process specific so you would need to > access the remote machine, access the user account, connect > to the specific process and then run the environment check. > > It rarely makes any sense unless its the user themselves > doing the check. > > I assume there is a greater requirement at the bavk of this? > What exactly is it you are trying to find out? There may be a better > way. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Fri Feb 25 04:46:17 2011 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 24 Feb 2011 19:46:17 -0800 Subject: [Tutor] accessing another system's environment In-Reply-To: References: Message-ID: <4D672609.2070204@alchemy.com> On 24-Feb-11 19:30, Bill Allen wrote: > I have times when it is useful for me to check the environment of a user > system on our lan remotely while trouble shooting and issue with them. > Now, this is quite easy to do while I am using a windows system via the Are you sure you're talking about the same thing we are when you say "environment"? There is no "the" environment on Unix-like systems. Every single process has its own environment. Each user's login session loads their personal set of environment variables, which is inherited by the processes they launch, but can be modified from process to process. Meanwhile, other users have their own environment, and system services have their own, etc. I thought Windows was similar in this respect, isn't it? > computer management console. However, I am trying to do this via a > linux workstation (which is joined to the domain, etc.). I cannot find > a native facility to duplicate the computer management functions, so I > thought I would write a program to fill the need. Not to mention, I > thought it might be a good learning opportunity. Getting environment variables is easy if you can get your script to be executed in that environment. Finding the environment of a running process can be done easily, too. Look at the output of "ps" with certain options set, or the contents of files in /proc. However, remember that there are as many environments are there are processes. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From bgailer at gmail.com Fri Feb 25 05:23:54 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 24 Feb 2011 23:23:54 -0500 Subject: [Tutor] Display all field of a listuples In-Reply-To: References: Message-ID: <4D672EDA.4040602@gmail.com> On 2/24/2011 4:54 PM, Christopher Brookes wrote: > Hi i would like to display all the field of my powerAll like this : > > Choose a power : > Froid devorant : Embrase lenemi et le feu bruler > Flammes infernales : 'Gele lenemi sur place > > ----------------------------- > class Character(): > def ChoosePouvoirUnique(self): > print ("Choose a power") > for Power in powerAll: > print (Power) > > class Power: > def __init__(self, name, desc): > self.name = name > self.desc = desc > > > > > powerAll = [ > Power('Flammes infernales' , 'Embrase lenemi et le feu bruler'), > Power('Froid devorant', 'Gele lenemi sur place')] > > > But he won't display it :( > > i've try For PowerName,PowerDesc in powerAll: > print (PowerName, PowerDesc) > > but it doesn't work ! When something "does not work" always show us what results you got as well as what you wanted. Also get in the habit of using Capitalized names for classes and unCapitalized names for variables and functions. powerAll is a list of class instaces. You must (in some way) identify the attributes of those instances. One way: for power in powerAll: print (power.name, power.desc) -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From sunil.techspk at gmail.com Fri Feb 25 06:35:35 2011 From: sunil.techspk at gmail.com (sunil tech) Date: Fri, 25 Feb 2011 11:05:35 +0530 Subject: [Tutor] list of dictionary Message-ID: Hi all... i have d=[{'qty':0.0},{'qty':0.0}] when all the qty is 0.0, i want to perform some print operation (only at once, after it checks everything in the list of dictionary 'd')... if its not 0.0, print some message... Thank you in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From pacificmorrowind at gmail.com Fri Feb 25 07:21:43 2011 From: pacificmorrowind at gmail.com (Pacific Morrowind) Date: Thu, 24 Feb 2011 22:21:43 -0800 Subject: [Tutor] list of dictionary In-Reply-To: References: Message-ID: <4D674A77.9010000@gmail.com> Hi; On 24/02/2011 9:35 PM, sunil tech wrote: > Hi all... > > i have d=[{'qty':0.0},{'qty':0.0}] > If there isn't some pressing reason to dictionaries as the list items (but since I'm not sure how you're generating the list/what you are later using the list I can't tell ofc but if applicable to your situation I'd suggest just doing for creation of the list d = [] (logic for whatever gives your values) d.append(value) etc.) > when all the qty is 0.0, > i want to perform some print operation > (only at once, after it checks everything in the list of dictionary > 'd')... > > if its not 0.0, > print some message... > > Thank you in advance Presuming you do have to use the dictionaries: qty = 0.0 for item in d: for subitem in d: if item[subitem] != 0.0: qty = item[subitem] break if qty != 0.0: print "some message - for example a non zero qty = %f" % qty (presuming you are using Python 2x - if using python 3x the syntax will be slightly different) Hopefully that will serve your purpose if not just post again and I or one of the more frequently posting helpful users here will answer soon. Nick -------------- next part -------------- An HTML attachment was scrubbed... URL: From edwardcru1 at aol.com Fri Feb 25 08:53:49 2011 From: edwardcru1 at aol.com (Edward Martinez) Date: Thu, 24 Feb 2011 23:53:49 -0800 Subject: [Tutor] comparing strings In-Reply-To: <4D663955.8030408@ieee.org> References: <4D65CEDA.1020707@aol.com> <4D65D0B6.2090400@aim.com> <4D65D671.1010808@aol.com> <4D663955.8030408@ieee.org> Message-ID: <4D67600D.8040601@aol.com> On 02/24/11 02:56, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, Edward Martinez wrote: >> On 02/23/11 19:29, Corey Richardson wrote: >>> On 02/23/2011 10:22 PM, Edward Martinez wrote: >>>> Hi, >>>> >>>> I'm new to the list and programming. >>>> i have a question, why when i evaluate strings ie 'a'> '3' it reports >>>> true, how does python come up with that? >>> Welcome! As far as I know, it compares the value of the ord()'s. >>> >>>>>> ord('a') >>> 97 >>>>>> ord('3') >>> 51 >>> >>> This is their number in the ASCII system. You can also do this: >>> >>>>>> chr(97) >>> 'a' >>>>>> chr(51) >>> '3' >>> > > A string is effectively an array of characters. Each one may be ASCII > or Unicode or other, depending partly on your Python version. > > Each character has an ord() between 0 and 255, or between 0 and 65535. > Except for some values below 0x20 (eg. tab, newline), these are > printable. So you can make a chart for your own system with a fairly > simple loop. > > Comparison is done left to right on the two strings, comparing one > character at a time. If there are no control characters, this > approximates what a dictionary order would do. But notice that all > the capital letters appear before any of the lowercase characters. And > that if you have accented characters, they're generally nowhere near > the unaccented versions. > > One other point: if one string begins with all the characters in the > other (eg. 'cat' and 'catatonic'), the longer string is then > considered "greater". > > DaveA > > Thanks for the reply. i now understand that python uses either ASCll or Unicode to compare and to do other things Regards, Edward From chris.klaitos at gmail.com Fri Feb 25 09:18:23 2011 From: chris.klaitos at gmail.com (Christopher Brookes) Date: Fri, 25 Feb 2011 09:18:23 +0100 Subject: [Tutor] Display all field of a listuples In-Reply-To: <4D672EDA.4040602@gmail.com> References: <4D672EDA.4040602@gmail.com> Message-ID: It's works. Thank you all. 2011/2/25 bob gailer > On 2/24/2011 4:54 PM, Christopher Brookes wrote: > > Hi i would like to display all the field of my powerAll like this : > > Choose a power : > Froid devorant : Embrase lenemi et le feu bruler > Flammes infernales : 'Gele lenemi sur place > > ----------------------------- > class Character(): > def ChoosePouvoirUnique(self): > print ("Choose a power") > for Power in powerAll: > print (Power) > > class Power: > def __init__(self, name, desc): > self.name = name > self.desc = desc > > > > > powerAll = [ > Power('Flammes infernales' , 'Embrase lenemi et le feu bruler'), > Power('Froid devorant', 'Gele lenemi sur place')] > > > But he won't display it :( > > i've try For PowerName,PowerDesc in powerAll: > print (PowerName, PowerDesc) > > but it doesn't work ! > > > When something "does not work" always show us what results you got as well > as what you wanted. > > Also get in the habit of using Capitalized names for classes and > unCapitalized names for variables and functions. > > powerAll is a list of class instaces. You must (in some way) identify the > attributes of those instances. One way: > > for power in powerAll: > print (power.name, power.desc) > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -- Brookes Christopher. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Fri Feb 25 09:23:05 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 25 Feb 2011 03:23:05 -0500 Subject: [Tutor] comparing strings In-Reply-To: <4D67600D.8040601@aol.com> References: <4D65CEDA.1020707@aol.com> <4D65D0B6.2090400@aim.com> <4D65D671.1010808@aol.com> <4D663955.8030408@ieee.org> <4D67600D.8040601@aol.com> Message-ID: <4D6766E9.6060400@aim.com> On 02/25/2011 02:53 AM, Edward Martinez wrote: > Thanks for the reply. i now understand that python uses either > ASCll or Unicode to compare and to do other things 1. Those are i's, not l's. 2. The first 128 characters of Unicode are the same as the only 128 characters of unicode. Check out http://qcpages.qc.cuny.edu/~nixon/links/asciiUnicode.html -- Corey Richardson From bgailer at gmail.com Fri Feb 25 09:59:54 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 25 Feb 2011 03:59:54 -0500 Subject: [Tutor] comparing strings In-Reply-To: <4D6766E9.6060400@aim.com> References: <4D65CEDA.1020707@aol.com> <4D65D0B6.2090400@aim.com> <4D65D671.1010808@aol.com> <4D663955.8030408@ieee.org> <4D67600D.8040601@aol.com> <4D6766E9.6060400@aim.com> Message-ID: <4D676F8A.4010708@gmail.com> On 2/25/2011 3:23 AM, Corey Richardson wrote: > On 02/25/2011 02:53 AM, Edward Martinez wrote: >> Thanks for the reply. i now understand that python uses either >> ASCll or Unicode to compare and to do other things When comparing string (not unicode) Python uses the underlying hardware character representation. This is not always ASCII. On IBM Mainframes it is EBCDIC. The ord values are different, and the order is different. See http://www.dynamoo.com/technical/ascii-ebcdic.htm -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Fri Feb 25 10:07:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Feb 2011 09:07:22 -0000 Subject: [Tutor] list of dictionary References: Message-ID: "sunil tech" wrote > > i have d=[{'qty':0.0},{'qty':0.0}] > > when all the qty is 0.0, > i want to perform some print operation > (only at once, after it checks everything in the list of dictionary > 'd')... > > if its not 0.0, > print some message... Just so I'm clear on the requirement you want something like: isZero = True for each dictionary in d if dictionary[qty] is not 0.0 print some message isZero = False if isZero: some print operation If so that should be easily translated into Python? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Feb 25 10:11:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Feb 2011 09:11:26 -0000 Subject: [Tutor] accessing another system's environment References: Message-ID: "Bill Allen" wrote >I have times when it is useful for me to check the environment of a >user > system on our lan remotely while trouble shooting and issue with > them. Now, > this is quite easy to do while I am using a windows system via the > computer > management console. I think we are meaning different things by "environment"? Can you give a specific example? > However, I am trying to do this via a linux workstation > (which is joined to the domain, etc.). I cannot find a native > facility to duplicate the computer management functions, so I > thought I > would write a program to fill the need. Anything you can do locally you can do on the remote machine with a combination of ssh, rsh, rlogin, telnet etc. ssh is the safest but requires a bit more admin to set it up properly for maximum convenience. Having got remote access its just a case of figuring out which of the 500 or so Unix commands you need to use to do the job... :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Feb 25 10:49:57 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Feb 2011 20:49:57 +1100 Subject: [Tutor] accessing another system's environment In-Reply-To: References: Message-ID: <4D677B45.5050506@pearwood.info> Alan Gauld wrote: > Anything you can do locally you can do on the remote > machine with a combination of ssh, rsh, rlogin, telnet etc. I'd like to remove a CD from the CD drive, and replace it with a different disk. Being difficult just for the sake of it-ly y'rs, -- Steven From kb1pkl at aim.com Fri Feb 25 11:05:16 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 25 Feb 2011 05:05:16 -0500 Subject: [Tutor] accessing another system's environment In-Reply-To: <4D677B45.5050506@pearwood.info> References: <4D677B45.5050506@pearwood.info> Message-ID: <4D677EDC.5080708@aim.com> On 02/25/2011 04:49 AM, Steven D'Aprano wrote: > Alan Gauld wrote: > >> Anything you can do locally you can do on the remote >> machine with a combination of ssh, rsh, rlogin, telnet etc. > > I'd like to remove a CD from the CD drive, and replace it with a > different disk. > > > Being difficult just for the sake of it-ly y'rs, And at that point, the all-encompassing "etc." steps in ;-) -- Corey Richardson From cfuller084 at thinkingplanet.net Fri Feb 25 11:23:54 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 25 Feb 2011 04:23:54 -0600 Subject: [Tutor] accessing another system's environment In-Reply-To: <4D677EDC.5080708@aim.com> References: <4D677B45.5050506@pearwood.info> <4D677EDC.5080708@aim.com> Message-ID: <201102250424.00781.cfuller084@thinkingplanet.net> My "etc" would be the loopback device and an iso image, optionally accompanied by wget and cdrecord (or whatever the kids are using these days). I was also reminded of this story: http://thedailywtf.com/Articles/ITAPPMONROBOT.aspx Cheers On Friday 25 February 2011, Corey Richardson wrote: > On 02/25/2011 04:49 AM, Steven D'Aprano wrote: > > Alan Gauld wrote: > >> Anything you can do locally you can do on the remote > >> machine with a combination of ssh, rsh, rlogin, telnet etc. > > > > I'd like to remove a CD from the CD drive, and replace it with a > > different disk. > > > > > > Being difficult just for the sake of it-ly y'rs, > > And at that point, the all-encompassing "etc." steps in ;-) From gavroche at gavroche.pl Fri Feb 25 13:34:43 2011 From: gavroche at gavroche.pl (Dominik Zyla) Date: Fri, 25 Feb 2011 13:34:43 +0100 Subject: [Tutor] having difficulty installing python In-Reply-To: References: Message-ID: <20110225123443.GA18837@mail.mercom.pl> On Thu, Feb 24, 2011 at 03:56:44PM +0000, Neven Dragojlovic wrote: > Please can someone help me? I am trying to install python 2.5.4 on > MacBookPro running on OS10.6.6, but when I try to set it up on > Terminal by running "python setup.py install" I get the following: > IDLE Subprocess: Connection to IDLE GUI failed, exiting. > Tk_MacOSXSetupTkNotifier: first [load] of TkAqua has to occur in the > main thread! > with an extra pop-up saying it can not access port 8833. When I try to > install that port with "sudo port install `8833'" it again says it can > not find that port. > What is going on? > The trouble started when I installed X11 and fink 0.29.16, with all > those files coming in and I allowed them. What do I do now? > > Thank you ahead of time, > Neven Why don't you try to download `.dmg' image from http://www.python.org/download/releases/? It can be installed easyly. Only think you would have to do is to add `/Library/Frameworks/Python.framework/Versions/$VERSION/bin' at the begining of your PATH shell variable to use exactly this version, you would install. -- Dominik Zyla -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 195 bytes Desc: not available URL: From chris.klaitos at gmail.com Fri Feb 25 15:11:01 2011 From: chris.klaitos at gmail.com (Christopher Brookes) Date: Fri, 25 Feb 2011 15:11:01 +0100 Subject: [Tutor] Search function in a list-tuples Message-ID: Hi, is there a better way to do this ? (*heros are Character*) herosAll = [ Character(0,"Chris","Soldat fort",type[0],15,5,8,50,1), Character(1,"Antaa","Soldat moins fort",type[0],15,5,8,50,1)] def HeroExist(HerosName): herosId = -1 for heros in herosAll: if HerosName in heros.name: herosId = heros.id if herosId != -1: return herosId else: return -1 I find this solution myself and I think a better one exist.. HerosName=input("Enter heros name : ") if Character.HeroExist(HerosName) != -1: herosAll[Character.HeroExist(HerosName)].DisplayCharacterInfos() else : print ('This heros does\'nt exist') Display_menu() Ty :) -- Brookes Christopher. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ranjand2005 at gmail.com Fri Feb 25 15:49:48 2011 From: ranjand2005 at gmail.com (ranjan das) Date: Fri, 25 Feb 2011 20:19:48 +0530 Subject: [Tutor] Unintentionally manipulating a list Message-ID: I am facing the following problem I have a list of the form INPUT= [ [ ['A1-N','A2-Y','A3-N' ],['B1-Y','B2-N','B3-N' ] ], [.........] ] and I want an output of the form (selecting only those elements which have a Y associated with them) OUTPUT=[ ['A2-Y', 'B1-Y'],[....] ] I wrote the following code. Although it gives me the desired output, it CHANGES the list INPUT now after i run the code I get INPUT as the same as OUTPUT (which i dont want to happen). I have used the copy function but it still is not working. Any help or pointers is appreciated *CODE* from copy import copy temp=copy( INPUT ) OUTPUT=temp for i in range(len(temp)): for j in range(len(temp[i])): for k in range(len(temp[i][j])): if temp[i][j][k][-1]=='Y': OUTPUT[i][j]=temp[i][j][k] -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Fri Feb 25 15:52:56 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 25 Feb 2011 09:52:56 -0500 Subject: [Tutor] Unintentionally manipulating a list In-Reply-To: References: Message-ID: You may want to deepcopy instead of just copy? On 2/25/11, ranjan das wrote: > I am facing the following problem > > > I have a list of the form > > INPUT= [ [ ['A1-N','A2-Y','A3-N' ],['B1-Y','B2-N','B3-N' ] ], [.........] ] > > > and I want an output of the form (selecting only those elements which have a > Y associated with them) > > OUTPUT=[ ['A2-Y', 'B1-Y'],[....] ] > > > I wrote the following code. Although it gives me the desired output, it > CHANGES the list INPUT > > now after i run the code I get INPUT as the same as OUTPUT (which i dont > want to happen). I have used the copy function but it still is not working. > Any help or pointers is appreciated > > *CODE* > > from copy import copy > > temp=copy( INPUT ) > OUTPUT=temp > > > > for i in range(len(temp)): > > for j in range(len(temp[i])): > > for k in range(len(temp[i][j])): > > if temp[i][j][k][-1]=='Y': > > OUTPUT[i][j]=temp[i][j][k] > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From knacktus at googlemail.com Fri Feb 25 16:21:49 2011 From: knacktus at googlemail.com (Knacktus) Date: Fri, 25 Feb 2011 16:21:49 +0100 Subject: [Tutor] Unintentionally manipulating a list In-Reply-To: References: Message-ID: <4D67C90D.2040206@googlemail.com> Am 25.02.2011 15:49, schrieb ranjan das: > > I am facing the following problem > > > I have a list of the form > > INPUT= [ [ ['A1-N','A2-Y','A3-N' ],['B1-Y','B2-N','B3-N' ] ], [.........] ] > > > and I want an output of the form (selecting only those elements which > have a Y associated with them) > > OUTPUT=[ ['A2-Y', 'B1-Y'],[....] ] > > > I wrote the following code. Although it gives me the desired output, it > CHANGES the list INPUT > > now after i run the code I get INPUT as the same as OUTPUT (which i dont > want to happen). I have used the copy function but it still is not > working. Any help or pointers is appreciated > > _CODE_ > > from copy import copy > > temp=copy( INPUT ) > OUTPUT=temp > > > > for i in range(len(temp)): > > for j in range(len(temp[i])): > > for k in range(len(temp[i][j])): > > if temp[i][j][k][-1]=='Y': > > OUTPUT[i][j]=temp[i][j][k] > > There's no need for an index. You can iterate over the elements directly and create the result on the fly: results = [] for sub_list in INPUT: sub_results = [] for sub_sub_list in sub_list: sub_sub_results = [] for entry in sub_sub_list: if entry.endswith("Y"): sub_sub_results.append(entry) if sub_sub_results: sub_results.append(sub_sub_results) if sub_results: results.append(sub_results) Uuppsy daisy, not really readable code ;-). Your solution looks cleaner. I bet, some of the gurus can come up with a real pythonic solution. Cheers, Jan > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Fri Feb 25 16:35:20 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Feb 2011 02:35:20 +1100 Subject: [Tutor] Unintentionally manipulating a list In-Reply-To: References: Message-ID: <4D67CC38.7010508@pearwood.info> ranjan das wrote: > I am facing the following problem > > > I have a list of the form > > INPUT= [ [ ['A1-N','A2-Y','A3-N' ],['B1-Y','B2-N','B3-N' ] ], [.........] ] > and I want an output of the form (selecting only those elements which have a > Y associated with them) > > OUTPUT=[ ['A2-Y', 'B1-Y'],[....] ] Can the Y be anywhere, or must it be at the end of the string? Should 'Y2-N' be included or excluded? I will assume excluded. What about lowercase 'y'? Should 'A3-y' be included? I assume it should be. > I wrote the following code. Although it gives me the desired output, it > CHANGES the list INPUT Start with a simple function that extracts the strings you want from the inner-most list, Here's the hard way: def select(items, suffix): suffix = suffix.upper() result = [] for s in items: if s.upper().endswith(suffix): result.append(s) return result This can be simplified to: def select(items, suffix): suffix = suffix.upper() return [s for s in items if s.upper().endswith(suffix)] Now you can use it: OUTPUT = [] # INPUT looks like: # [ [a1_list, b1_list, ...], [a2_list, b2_list, ...], ... ] for middle in INPUT: # middle looks like [a99_list, b99_list, c99_list, ...] temp = [] for inner in middle: # inner looks like [astr-N, bstr-Y, cstr-Y, ...] temp.extend(select(inner, '-Y')) OUTPUT.append(temp) There is no need to make a copy of the input list. -- Steven From ramjaju.mail at gmail.com Fri Feb 25 16:47:03 2011 From: ramjaju.mail at gmail.com (Sriram Jaju) Date: Fri, 25 Feb 2011 21:17:03 +0530 Subject: [Tutor] Python in MATLAB Message-ID: can i embed python code in MATLAB program? -- Xcited 2 be Alive....Sriram -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramjaju.mail at gmail.com Fri Feb 25 16:49:50 2011 From: ramjaju.mail at gmail.com (Sriram Jaju) Date: Fri, 25 Feb 2011 21:19:50 +0530 Subject: [Tutor] Python in MATLAB Message-ID: can i embed python code in MATLAB program? -- Xcited 2 be Alive....Sriram -------------- next part -------------- An HTML attachment was scrubbed... URL: From ljmamoreira at gmail.com Fri Feb 25 16:51:04 2011 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Fri, 25 Feb 2011 15:51:04 +0000 Subject: [Tutor] How to vectorize a constant function? Message-ID: <201102251551.04996.ljmamoreira@gmail.com> Hello! In "A Primer on Scientific Programming with Python", they define a vectorized function as a scalar function that, when called with a vector argument, returns a vector with the values of the function for each of the values stored in the argument vector. I am trying to define a constant vectorized function, that is, one that returns 1. (for instance) when called with a scalar argument x and that returns array([1.,1.,1.]) when the argument is a three-element array, etc. Here are a few snippets of an interactive session displaying my failed attempts: --------------------------- In [1]: from numpy import * In [2]: def f(x): ...: return 1. In [3]: x=linspace(0,1,5) In [4]: print f(x) ------> print(f(x)) 1.0 ------------------------- That's not what I want, that's a scalar, not a five element array. Next option: ------------------------- In [13]: def g(x): ....: return where(True,1.,0.) In [14]: print g(x) -------> print(g(x)) 1.0 --------------------------- Still not right. But here is something strange. The values in x are non- negative, therefore the test x>=0 yelds True for each element in x. One might then think that g(x) as defined above would, in this case, be equivalent to h(x) defined below: -------------------------- In [16]: def h(x): ....: return where(x>=0,1.,0) --------------------------- However, --------------------------- In [18]: print h(x) -------> print(h(x)) [ 1. 1. 1. 1. 1.] --------------------------- So my questions are: 1. What's the proper way to vectorize a constant function (I know that we really don't have to, but I'd like to do it in a first step towards a more sophisticated calculation)? 2. Why do g(x) and h(x) return different results? 3. Why doesn't f(x) work? Thanks Jose From alan.gauld at btinternet.com Fri Feb 25 17:15:29 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Feb 2011 16:15:29 -0000 Subject: [Tutor] Search function in a list-tuples References: Message-ID: "Christopher Brookes" wrote > Hi, is there a better way to do this ? (*heros are Character*) There are several better ways but mainly they involve techniques that may be too advanced for you at present, so we'll keep it simple for now :-) > herosAll = [ > Character(0,"Chris","Soldat fort",type[0],15,5,8,50,1), > Character(1,"Antaa","Soldat moins fort",type[0],15,5,8,50,1)] > > def HeroExist(HerosName): > herosId = -1 > for heros in herosAll: > if HerosName in heros.name: > herosId = heros.id > if herosId != -1: > return herosId > else: > return -1 replace from the for loop down with: for heros in herosAll: if HerosName in heros.name: herosId = heros.id return herosId return None # This allows more convenient testing, see below Which has the advantage of being slightly faster too. > HerosName=input("Enter heros name : ") > if Character.HeroExist(HerosName) != -1: HeroExist is not a method of Character ( although you could make it so - one of the better solutions I alluded to above! ) So you don't need to prefix it with Character. And you can assign the return value to a variable so you avoid calling it twice: HerosName=input("Enter heros name : ") ch = HeroExist(HerosName): if ch: # because None is treated as False ch.DisplayCharacterInfos() else : print ('This heros does\'nt exist') HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Fri Feb 25 17:48:36 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 Feb 2011 17:48:36 +0100 Subject: [Tutor] How to vectorize a constant function? References: <201102251551.04996.ljmamoreira@gmail.com> Message-ID: Jose Amoreira wrote: > I am trying to define a constant vectorized function, that is, one that > returns 1. (for instance) when called with a scalar argument x and that > returns array([1.,1.,1.]) when the argument is a three-element array, etc. With the help of google I found http://docs.scipy.org/doc/numpy/reference/generated/numpy.frompyfunc.html >>> import numpy >>> def f(x): return 42 ... >>> f = numpy.frompyfunc(f, 1, 1) >>> f(1) 42 >>> f(numpy.zeros(7)) array([42, 42, 42, 42, 42, 42, 42], dtype=object) From patty at cruzio.com Fri Feb 25 18:44:39 2011 From: patty at cruzio.com (Patty) Date: Fri, 25 Feb 2011 09:44:39 -0800 Subject: [Tutor] list of dictionary References: <4D674A77.9010000@gmail.com> Message-ID: ----- Original Message ----- From: Pacific Morrowind To: tutor at python.org Sent: Thursday, February 24, 2011 10:21 PM Subject: Re: [Tutor] list of dictionary Hi; On 24/02/2011 9:35 PM, sunil tech wrote: Hi all... i have d=[{'qty':0.0},{'qty':0.0} If there isn't some pressing reason to dictionaries as the list items (but since I'm not sure how you're generating the list/what you are later using the list I can't tell ofc but Hi - I had just a couple comments plus clarification about lists and iterating: if applicable to your situation I'd suggest just doing for creation of the list d = [] I like creating the empty variable structure, makes the code really clear. (logic for whatever gives your values) d.append(value) etc.) when all the qty is 0.0, i want to perform some print operation (only at once, after it checks everything in the list of dictionary 'd')... if its not 0.0, print some message... Thank you in advance Presuming you do have to use the dictionaries: qty = 0.0 for item in d: Right here - is the variable 'item' created right on the spot to iterate over this list? And I think you are doing the same thing when you create the variable 'subitem' in the line below, right? I am trying to get myself to recognize an iterator variable as opposed to a counter variable I create myself to keep track of these things (used in other programming languages) - and realizing the difference between counter/iterator variables and variables that I really care about like 'd = []' . Thanks! Patty for subitem in d: if item[subitem] != 0.0: qty = item[subitem] break if qty != 0.0: print "some message - for example a non zero qty = %f" % qty (presuming you are using Python 2x - if using python 3x the syntax will be slightly different) Hopefully that will serve your purpose if not just post again and I or one of the more frequently posting helpful users here will answer soon. Nick ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Fri Feb 25 19:18:15 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 25 Feb 2011 12:18:15 -0600 Subject: [Tutor] Python in MATLAB In-Reply-To: References: Message-ID: <201102251218.21338.cfuller084@thinkingplanet.net> Absolutely. You can use mex files to interface with the Python API (this requires considerable C proficiency), or you can use something like pymex or pymat. Did you google "matlab python"? http://vader.cse.lehigh.edu/~perkins/pymex.html http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html Cheers On Friday 25 February 2011, Sriram Jaju wrote: > can i embed python code in MATLAB program? From chris.klaitos at gmail.com Fri Feb 25 19:51:52 2011 From: chris.klaitos at gmail.com (Christopher Brookes) Date: Fri, 25 Feb 2011 19:51:52 +0100 Subject: [Tutor] Search function in a list-tuples In-Reply-To: <306861.96028.qm@web86705.mail.ird.yahoo.com> References: <306861.96028.qm@web86705.mail.ird.yahoo.com> Message-ID: Hi, I found the solution :) Special thanks to Alan G. Solution : def FindByName(HerosName): for heros in herosAll: if HerosName == heros.name: return heros return None HerosName = 'notfound' while FindByName(HerosName) == None: HerosName=input("Enter heros name (type exit for close): ") if HerosName.lower() == 'exit': Display_menu() else: ch = FindByName(HerosName) if ch: ch.DisplayCharacterInfos() newSearch=input('New search ? (Y/N)') else : print ('This heros does\'nt exist') 2011/2/25 ALAN GAULD > CCing group. Please use ReplyAll in replies to the list. > > > > Hi, thank your for your answer. i wrote this now : > > > def HeroExist(HerosName): > for heros in herosAll: > if HerosName in heros.name: > herosId = heros.id > return herosId > return None > > HerosName=input("Enter heros name : ") > ch = HeroExist(HerosName) > if ch: > ch.DisplayCharacterInfos() > else : > print ('This heros does\'nt exist') > > But whatever i type, he says : heros doesn't exist :/ > > That suggets a problem with how the name is being stored. > Can you send the code for the Character class, esp[ecially the init method. > Plus a cut n paste of the output of a ruin of the programme so that > we can see exactly what you are inputting and what the > results are? > > BTW you don't need the \ in the last print. You are using double quotes > around the string so you can just type the single quote directly > > print ( "This hero doesn't exist') > > Alan G. > > 2011/2/25 Alan Gauld > >> "Christopher Brookes" wrote >> >> Hi, is there a better way to do this ? (*heros are Character*) >>> >> >> There are several better ways but mainly they involve >> techniques that may be too advanced for you at present, >> so we'll keep it simple for now :-) >> >> >> herosAll = [ >>> Character(0,"Chris","Soldat fort",type[0],15,5,8,50,1), >>> Character(1,"Antaa","Soldat moins fort",type[0],15,5,8,50,1)] >>> >>> def HeroExist(HerosName): >>> herosId = -1 >>> for heros in herosAll: >>> if HerosName in heros.name: >>> herosId = heros.id >>> if herosId != -1: >>> return herosId >>> else: >>> return -1 >>> >> >> replace from the for loop down with: >> >> >> for heros in herosAll: >> if HerosName in heros.name: >> herosId = heros.id >> return herosId >> return None # This allows more convenient testing, see below >> >> Which has the advantage of being slightly faster too. >> >> >> HerosName=input("Enter heros name : ") >>> if Character.HeroExist(HerosName) != -1: >>> >> >> HeroExist is not a method of Character ( although you could >> make it so - one of the better solutions I alluded to above! ) >> So you don't need to prefix it with Character. >> >> And you can assign the return value to a variable so >> you avoid calling it twice: >> >> >> HerosName=input("Enter heros name : ") >> ch = HeroExist(HerosName): >> if ch: # because None is treated as False >> ch.DisplayCharacterInfos() >> >> else : >> print ('This heros does\'nt exist') >> >> HTH, >> >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Brookes Christopher. > > -- Brookes Christopher. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramjaju.mail at gmail.com Fri Feb 25 20:30:48 2011 From: ramjaju.mail at gmail.com (Sriram Jaju) Date: Sat, 26 Feb 2011 01:00:48 +0530 Subject: [Tutor] Python in MATLAB In-Reply-To: <201102251218.21338.cfuller084@thinkingplanet.net> References: <201102251218.21338.cfuller084@thinkingplanet.net> Message-ID: I googled but i didn't get considerable results. I am doing a project on optical character recognition, i tried a code on matlab, but it was not efficient. I tried it on python it worked. Now i want to embed python code in matlab code with other matlab function such as image acquisition etc. so how it can be done? On Fri, Feb 25, 2011 at 11:48 PM, Chris Fuller < cfuller084 at thinkingplanet.net> wrote: > > Absolutely. You can use mex files to interface with the Python API (this > requires considerable C proficiency), or you can use something like pymex > or pymat. Did you google "matlab python"? > > http://vader.cse.lehigh.edu/~perkins/pymex.html > http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html > > Cheers > > On Friday 25 February 2011, Sriram Jaju wrote: > > can i embed python code in MATLAB program? > > -- Xcited 2 be Alive....Sriram -------------- next part -------------- An HTML attachment was scrubbed... URL: From jwbonnell5 at gmail.com Sat Feb 26 00:42:00 2011 From: jwbonnell5 at gmail.com (Justin Bonnell) Date: Fri, 25 Feb 2011 17:42:00 -0600 Subject: [Tutor] Running Existing Python Message-ID: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> I downloaded Python 2.7.1. I think this is a pretty basic question. When I try to run the existing python files on the computer (hello.py), I receive a syntax error. Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "copyright", "credits" or "license()" for more information. >>> python hello.py SyntaxError: invalid syntax I am running Mac OS X version 10.6.6. Shouldn't I be able to run hello.py from the IDLE interpreter? From kb1pkl at aim.com Sat Feb 26 00:51:08 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 25 Feb 2011 18:51:08 -0500 Subject: [Tutor] Running Existing Python In-Reply-To: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> Message-ID: <4D68406C.4040503@aim.com> On 02/25/2011 06:42 PM, Justin Bonnell wrote: > I downloaded Python 2.7.1. I think this is a pretty basic question. > When I try to run the existing python files on the computer (hello.py), I receive a syntax error. > > Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) > [GCC 4.2.1 (Apple Inc. build 5664)] on darwin > Type "copyright", "credits" or "license()" for more information. >>>> python hello.py > SyntaxError: invalid syntax > > I am running Mac OS X version 10.6.6. > Shouldn't I be able to run hello.py from the IDLE interpreter? You need to run "python hello.py" in a terminal window, not from the Python interpreter. If you are using IDLE, you can File > Open hello.py and hit F5 to run it... I don't know if that advice applies to Mac, might be different key strokes. -- Corey Richardson From alan.gauld at btinternet.com Fri Feb 25 19:44:43 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 25 Feb 2011 18:44:43 +0000 (GMT) Subject: [Tutor] Search function in a list-tuples In-Reply-To: References: Message-ID: <306861.96028.qm@web86705.mail.ird.yahoo.com> CCing group. Please use ReplyAll in replies to the list. > Hi, thank your for your answer. i wrote this now : >def HeroExist(HerosName): > for heros in herosAll: > if HerosName in heros.name: > herosId = heros.id > return herosId > return None > >HerosName=input("Enter heros name : ") >ch = HeroExist(HerosName) >if ch: > ch.DisplayCharacterInfos() >else : > print ('This heros does\'nt exist') > >But whatever i type, he says : heros doesn't exist :/ > >That suggets a problem with how the name is being stored. Can you send the code for the Character class, esp[ecially the init method. Plus a cut n paste of the output of a ruin of the programme so that we can see exactly what you are inputting and what the results are? BTW you don't need the \ in the last print. You are using double quotes around the string so you can just type the single quote directly print ( "This hero doesn't exist') Alan G. 2011/2/25 Alan Gauld > >"Christopher Brookes" wrote >> >> >>Hi, is there a better way to do this ? (*heros are Character*) >>> >There are several better ways but mainly they involve >techniques that may be too advanced for you at present, >so we'll keep it simple for now :-) > > > >herosAll = [ >>Character(0,"Chris","Soldat fort",type[0],15,5,8,50,1), >>Character(1,"Antaa","Soldat moins fort",type[0],15,5,8,50,1)] >> >>def HeroExist(HerosName): >> herosId = -1 >> for heros in herosAll: >> if HerosName in heros.name: >> herosId = heros.id >> if herosId != -1: >> return herosId >> else: >> return -1 >> replace from the for loop down with: > > > for heros in herosAll: > if HerosName in heros.name: > herosId = heros.id > return herosId > return None # This allows more convenient testing, see below > >Which has the advantage of being slightly faster too. > > > > HerosName=input("Enter heros name : ") >> if Character.HeroExist(HerosName) != -1: >> HeroExist is not a method of Character ( although you could >make it so - one of the better solutions I alluded to above! ) >So you don't need to prefix it with Character. > >And you can assign the return value to a variable so >you avoid calling it twice: > > > HerosName=input("Enter heros name : ") > ch = HeroExist(HerosName): > if ch: # because None is treated as False > ch.DisplayCharacterInfos() > > else : > print ('This heros does\'nt exist') > > HTH, > > >-- >Alan Gauld >Author of the Learn to Program web site >http://www.alan-g.me.uk/ > > > >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > >-- >Brookes Christopher. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vic_prof at hotmail.com Fri Feb 25 21:20:45 2011 From: vic_prof at hotmail.com (Victor Binns) Date: Fri, 25 Feb 2011 15:20:45 -0500 Subject: [Tutor] scripts search Message-ID: Hello I am fairly new to python. I have a small business and I wanted to use python in my business. I have a need for an Employee Time and Attendance software. Is there any python scripts out there that can do the trick? Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Sat Feb 26 01:08:48 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 25 Feb 2011 19:08:48 -0500 Subject: [Tutor] scripts search In-Reply-To: References: Message-ID: <4D684490.1040302@aim.com> On 02/25/2011 03:20 PM, Victor Binns wrote: > > Hello I am fairly new to python. > > I have a small business and I wanted to use python in my business. I have a need for an > Employee Time and Attendance software. > > Is there any python scripts out there that can do the trick? > I don't know of any and a google didn't return favorable results. You'll have to write it yourself. Luckily, Python is one of the more simple languages and you should have a fairly easy time writing it. Check out http://www.alan-g.me.uk/tutor/index.htm if you haven't programmed before, and if you have, try this: http://docs.python.org/tutorial/ -- Corey Richardson From alan.gauld at btinternet.com Sat Feb 26 01:46:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Feb 2011 00:46:44 -0000 Subject: [Tutor] Running Existing Python References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> Message-ID: "Justin Bonnell" wrote > Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) > [GCC 4.2.1 (Apple Inc. build 5664)] on darwin > Type "copyright", "credits" or "license()" for more information. >>>> The >>> prompt means you are already inside Python. You can type Python commands at the >>> prompt, things like >>> print "Hello" But you cannot ruin a program from inside the >>> prompt (well, you can, but its more complicated than sane people want to bother with! :-) You run a Python script from the OS Terminal prompt: $ python hello.py > Shouldn't I be able to run hello.py from the IDLE interpreter? You can't run it from the >>> prompt in IDLE but.... What you can do is open the file for editing and then run that file using the menu commands, then the output will show up in the interpreter window. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Feb 26 01:49:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Feb 2011 00:49:11 -0000 Subject: [Tutor] scripts search References: Message-ID: "Victor Binns" wrote > I have a small business and I wanted to use python > in my business. I have a need for an > Employee Time and Attendance software. > Is there any python scripts out there that can do the trick? I'm not aware of any but a Google or Sourceforge search might throw up something. However depending how small your business is you might find spreadsheets are sufficient for your needs and much easier to set up than trying to write something from scratch in Python... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From pacificmorrowind at gmail.com Sat Feb 26 02:38:51 2011 From: pacificmorrowind at gmail.com (Pacific Morrowind) Date: Fri, 25 Feb 2011 17:38:51 -0800 Subject: [Tutor] list of dictionary In-Reply-To: References: <4D674A77.9010000@gmail.com> Message-ID: <4D6859AB.1010808@gmail.com> On 25/02/2011 9:44 AM, Patty wrote: > > ----- Original Message ----- > *From:* Pacific Morrowind > *To:* tutor at python.org > *Sent:* Thursday, February 24, 2011 10:21 PM > *Subject:* Re: [Tutor] list of dictionary > > Presuming you do have to use the dictionaries: > qty = 0.0 > for item in d: > > Right here - is the variable 'item' created right on the spot to > iterate over this list? And I think you are doing the same thing > when you create the variable 'subitem' in the line below, right? > I am trying to get myself to recognize an iterator variable as > opposed to a counter variable I create myself to keep track of > these things (used in other programming languages) - and realizing > the difference between counter/iterator variables and variables > that I really care about like > 'd = []' . > Thanks! > Patty > yes and yes. both item and subitem are created on the spot; anychunk of python code like: for x in y: will create x as a variable and with each iteration x refers to the next item in y; Of course if I knew the function of the list/dictionary I'd name them something more informative than item and subitem - like f.e. for lap in d and for time in d if it was refering to races. Nick -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Sat Feb 26 03:50:39 2011 From: wallenpb at gmail.com (Bill Allen) Date: Fri, 25 Feb 2011 20:50:39 -0600 Subject: [Tutor] accessing another system's environment In-Reply-To: References: Message-ID: I apologize for not have been clear previously. What I am trying to access are the Windows system environment variables. The same ones that are listed out if you type the set command at a command prompt in Windows. --Bill On Fri, Feb 25, 2011 at 03:11, Alan Gauld wrote: > > "Bill Allen" wrote > > I have times when it is useful for me to check the environment of a user >> system on our lan remotely while trouble shooting and issue with them. >> Now, >> this is quite easy to do while I am using a windows system via the >> computer >> management console. >> > > I think we are meaning different things by "environment"? > Can you give a specific example? > > > However, I am trying to do this via a linux workstation >> (which is joined to the domain, etc.). I cannot find a native >> facility to duplicate the computer management functions, so I thought I >> would write a program to fill the need. >> > > Anything you can do locally you can do on the remote > machine with a combination of ssh, rsh, rlogin, telnet etc. > ssh is the safest but requires a bit more admin to set it > up properly for maximum convenience. > > Having got remote access its just a case of figuring out > which of the 500 or so Unix commands you need to > use to do the job... :-) > > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Sat Feb 26 04:27:43 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 25 Feb 2011 19:27:43 -0800 Subject: [Tutor] accessing another system's environment In-Reply-To: References: Message-ID: <4D68732F.2090801@alchemy.com> On 25-Feb-11 18:50, Bill Allen wrote: > I apologize for not have been clear previously. What I am trying to > access are the Windows system environment variables. The same ones > that are listed out if you type the set command at a command prompt in > Windows. There isn't a "system" set of environment variables on Unix-like systems--there is a default "starting" set per user (although they are configurable per-process as has already been stated). Perhaps you want to see the set of variables for the "root" account? But again, I have to ask what you're really trying to accomplish. Environment variables are only such a small part of a system's configuration, on Windows or Unix/Linux. On a Windows box, I would probably be more interested in what's in the system registry, for example, and on a Unix system I'd want to see what's in various configuration files in /etc to know what's configured on that system. Environment variables, from the point of view of a random process running on the system, are pretty much the same on both Windows and Unix. Where they come from, and which are "system" or "user" variables, is quite different, and I suspect you're reaching for environment variables out of habit but that may not ultimately be what you're really looking for here. Or maybe it is. If it is, step back and consider WHOSE set of variables you really want? The root account? the account of a service that you're interested in? The default skeleton configuration files for new users? The environment of something you know to be running already? All of those things are possible to look at, if you know what you're really after and why it will help you accomplish what you need to do. --steve > > > --Bill > > > > > > On Fri, Feb 25, 2011 at 03:11, Alan Gauld > wrote: > > > "Bill Allen" > wrote > > I have times when it is useful for me to check the environment > of a user > system on our lan remotely while trouble shooting and issue with > them. Now, > this is quite easy to do while I am using a windows system via > the computer > management console. > > > I think we are meaning different things by "environment"? > Can you give a specific example? > > > However, I am trying to do this via a linux workstation > (which is joined to the domain, etc.). I cannot find a native > facility to duplicate the computer management functions, so I > thought I > would write a program to fill the need. > > > Anything you can do locally you can do on the remote > machine with a combination of ssh, rsh, rlogin, telnet etc. > ssh is the safest but requires a bit more admin to set it > up properly for maximum convenience. > > Having got remote access its just a case of figuring out > which of the 500 or so Unix commands you need to > use to do the job... :-) > > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From steve at alchemy.com Sat Feb 26 04:33:04 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 25 Feb 2011 19:33:04 -0800 Subject: [Tutor] accessing another system's environment In-Reply-To: <4D68732F.2090801@alchemy.com> References: <4D68732F.2090801@alchemy.com> Message-ID: <4D687470.6020807@alchemy.com> On 25-Feb-11 19:27, Steve Willoughby wrote: Wait. Are you trying to figure out how, on a Unix system, to read Unix system environment variables as you're accustomed to doing on Windows? Or are you saying you want to, from a remote Unix system, reach out to a Windows system and see that Windows system's system environment variables? > On 25-Feb-11 18:50, Bill Allen wrote: >> I apologize for not have been clear previously. What I am trying to >> access are the Windows system environment variables. The same ones >> that are listed out if you type the set command at a command prompt in >> Windows. > > There isn't a "system" set of environment variables on Unix-like > systems--there is a default "starting" set per user (although they are > configurable per-process as has already been stated). > > Perhaps you want to see the set of variables for the "root" account? But > again, I have to ask what you're really trying to accomplish. > Environment variables are only such a small part of a system's > configuration, on Windows or Unix/Linux. On a Windows box, I would > probably be more interested in what's in the system registry, for > example, and on a Unix system I'd want to see what's in various > configuration files in /etc to know what's configured on that system. > > Environment variables, from the point of view of a random process > running on the system, are pretty much the same on both Windows and > Unix. Where they come from, and which are "system" or "user" variables, > is quite different, and I suspect you're reaching for environment > variables out of habit but that may not ultimately be what you're really > looking for here. > > Or maybe it is. If it is, step back and consider WHOSE set of variables > you really want? The root account? the account of a service that you're > interested in? The default skeleton configuration files for new users? > The environment of something you know to be running already? > > All of those things are possible to look at, if you know what you're > really after and why it will help you accomplish what you need to do. > > --steve > >> >> >> --Bill >> >> >> >> >> >> On Fri, Feb 25, 2011 at 03:11, Alan Gauld > > wrote: >> >> >> "Bill Allen" > wrote >> >> I have times when it is useful for me to check the environment >> of a user >> system on our lan remotely while trouble shooting and issue with >> them. Now, >> this is quite easy to do while I am using a windows system via >> the computer >> management console. >> >> >> I think we are meaning different things by "environment"? >> Can you give a specific example? >> >> >> However, I am trying to do this via a linux workstation >> (which is joined to the domain, etc.). I cannot find a native >> facility to duplicate the computer management functions, so I >> thought I >> would write a program to fill the need. >> >> >> Anything you can do locally you can do on the remote >> machine with a combination of ssh, rsh, rlogin, telnet etc. >> ssh is the safest but requires a bit more admin to set it >> up properly for maximum convenience. >> >> Having got remote access its just a case of figuring out >> which of the 500 or so Unix commands you need to >> use to do the job... :-) >> >> >> HTH, >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From wallenpb at gmail.com Sat Feb 26 05:26:15 2011 From: wallenpb at gmail.com (Bill Allen) Date: Fri, 25 Feb 2011 22:26:15 -0600 Subject: [Tutor] accessing another system's environment In-Reply-To: <4D687470.6020807@alchemy.com> References: <4D68732F.2090801@alchemy.com> <4D687470.6020807@alchemy.com> Message-ID: On Fri, Feb 25, 2011 at 21:33, Steve Willoughby wrote: > On 25-Feb-11 19:27, Steve Willoughby wrote: > > > Or are you saying you want to, from a remote Unix system, reach out to a > Windows system and see that Windows system's system environment variables? Yes, that's it exactly. :-) I administrate the workstations in our engineering environment and some of the major pieces of software we use are configured via the Windows system environment variables. Being able to reach out to a PC and check or change those is handy, even important, in my situation. I am trying to explore the possibility of managing these from a system I am using in a platform independent way and figure that I ought to be able to do this with Python. Perhaps there are third party Python modules I need to help accomplish this? --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Sat Feb 26 05:35:46 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 25 Feb 2011 23:35:46 -0500 Subject: [Tutor] Cross-Module Interaction Message-ID: <4D688322.6090607@aim.com> Greetings, Tutors (Sorry for the poor subject name, couldn't think of anything better) I'm writing a MUD server as part of a school project. Yes this is homework, but I'm not taking a traditional programming class (going through the OCW for CS50 at Harvard and getting credit). I'm in the design phase and am testing out a few things. One thing I will definitely need is a global players_online collection which will act much like the name implies. My first thought was to have a module specifically for holding things like that, global objects that all the interacting modules need access to. I did a simple test with a lib module, and then a few modules that simply added things to a list called g in that lib module, but the changes did not persist (tested with another module that printed the contents of lib.g) I'm probably thinking about this from the wrong direction. Is there something about this approach that I'm missing, or is there a different way I should be using? (If you're curious about the telephone data-transfer I was working on, I ran into too much trouble with the various sound libraries that exist to wrap over Alsa or JACK, so I put it off for the future after I'm more comfortable with C/C++) -- Corey Richardson From steve at alchemy.com Sat Feb 26 05:39:41 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 25 Feb 2011 20:39:41 -0800 Subject: [Tutor] accessing another system's environment In-Reply-To: References: <4D68732F.2090801@alchemy.com> <4D687470.6020807@alchemy.com> Message-ID: <4D68840D.2040508@alchemy.com> On 25-Feb-11 20:26, Bill Allen wrote: > > > On Fri, Feb 25, 2011 at 21:33, Steve Willoughby > wrote: > > On 25-Feb-11 19:27, Steve Willoughby wrote: > > > Or are you saying you want to, from a remote Unix system, reach out > to a Windows system and see that Windows system's system environment > variables? > > > Yes, that's it exactly. :-) Ok... this is starting to make more sense then. So you have two problems, really. One is to get the linux box to invoke a command remotely on the windows box, and the other is what command to run on the windows side. Either *could* be a Python script, in theory, but those are two separate problems. There are lots of ways to go about this. You could write some kind of service in Python (CPython, or IronPython/.net or even C# or whatever) which manages the settings on your windows system. A Python script could then be written to interact with that service. Or, you could use a linux RDP-compatible tool to interactively run commands on the windows box for you. One question you need to figure out is how interactive you want this to be, or how automated. That will drive the implementation of what comes after. As will the list of available options at your site for securely allowing a remote host to run administrative tools on your windows systems. > I administrate the workstations in our engineering environment and some > of the major pieces of software we use are configured via the Windows > system environment variables. Being able to reach out to a PC and check > or change those is handy, even important, in my situation. I am trying > to explore the possibility of managing these from a system I am using in > a platform independent way and figure that I ought to be able to do this > with Python. Perhaps there are third party Python modules I need to > help accomplish this? > > --Bill > -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From steve at pearwood.info Sat Feb 26 06:11:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Feb 2011 16:11:40 +1100 Subject: [Tutor] Cross-Module Interaction In-Reply-To: <4D688322.6090607@aim.com> References: <4D688322.6090607@aim.com> Message-ID: <4D688B8C.2050604@pearwood.info> Corey Richardson wrote: > My first thought was to have a module specifically for holding things > like that, global objects that all the interacting modules need access > to. I did a simple test with a lib module, and then a few modules that > simply added things to a list called g in that lib module, but the > changes did not persist (tested with another module that printed the > contents of lib.g) Perhaps you should give a *simple* example, but what you describe should work. Let's start with a very simple library module: # lib.py g = [] Now let's import it and use it from another module: # a.py import lib def do_stuff(): lib.g.append(42) Save those two files as named, and then import them into the interactive interpreter: [steve at sylar ~]$ python Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import lib >>> import a >>> lib.g [] >>> a.do_stuff() >>> lib.g [42] Of course, when your application exists (or in this case, the interactive session), the changes to lib.g will be lost because they only exist in memory. If you want data to persist across application runs, you need to arrange for the application to save the data to disk, and then read it again when it starts up. Python has many tools for working with persistent data: Windows-style ini files (module config parser), XML, JSON, Mac-style plists, YAML (third-party module only), and pickles, to name only a few. -- Steven From kb1pkl at aim.com Sat Feb 26 06:33:18 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 26 Feb 2011 00:33:18 -0500 Subject: [Tutor] Cross-Module Interaction In-Reply-To: <4D688B8C.2050604@pearwood.info> References: <4D688322.6090607@aim.com> <4D688B8C.2050604@pearwood.info> Message-ID: <4D68909E.2010808@aim.com> On 02/26/2011 12:11 AM, Steven D'Aprano wrote: > [steve at sylar ~]$ python > Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import lib > >>> import a > >>> lib.g > [] > >>> a.do_stuff() > >>> lib.g > [42] > > > Of course, when your application exists (or in this case, the > interactive session), the changes to lib.g will be lost because they > only exist in memory. If you want data to persist across application > runs, you need to arrange for the application to save the data to disk, > and then read it again when it starts up. Aha, that explains why I didn't get any results. Each file got its own interpreter instance. > > Python has many tools for working with persistent data: Windows-style > ini files (module config parser), XML, JSON, Mac-style plists, YAML > (third-party module only), and pickles, to name only a few. In any case everything would be called in one interpreter, which I didn't know worked because I didn't test it like you showed it, but to be safe I definitely need to persist that data every once in a while. I'm slightly concerned about performance when it comes to reading/writing to disk a lot when doing things like that, since if this thing ever needs to scale I want it to be able to do that. Thank you, Steven -- Corey Richardson From wallenpb at gmail.com Sat Feb 26 07:26:17 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 26 Feb 2011 00:26:17 -0600 Subject: [Tutor] accessing another system's environment In-Reply-To: <4D68840D.2040508@alchemy.com> References: <4D68732F.2090801@alchemy.com> <4D687470.6020807@alchemy.com> <4D68840D.2040508@alchemy.com> Message-ID: On Fri, Feb 25, 2011 at 22:39, Steve Willoughby wrote: > > One question you need to figure out is how interactive you want this to be, > or how automated. That will drive the implementation of what comes after. > As will the list of available options at your site for securely allowing a > remote host to run administrative tools on your windows systems. > > > I am pretty basic and no-frills about programs, particularly ones that are utilities for my own use. I am one of those admins that has full administrator privs on the site workstations, so I am able to run anything I like on or against these systems. I am envisioning a little command line program that would work like this: $python get_set_env.py -c some_computer_name This would then just dump the system environment variables of some_computer_name $python get_set_env.py -c some_computer_name -e UG_SHOW_MOD True On the system some_computer_name, this would edit the system environment variable UG_SHOW_MOD to a value of True. $python get_set_env.py -c some_computer_name -s UG_RUN_DIR C:\UGII On the system some_computer_name, this would create the system environment variable UG_RUN_DIR and set it to the value C:\UGII --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Feb 26 10:19:36 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 26 Feb 2011 09:19:36 +0000 (GMT) Subject: [Tutor] accessing another system's environment In-Reply-To: References: Message-ID: <994737.99124.qm@web86705.mail.ird.yahoo.com> Bill, That's the same thing we are talking about. The problem is those environment variables are highly variable so you can't talk about a machine's environment. Two users on the same machine (at the same time) may have very different environments. And a batch file or program can add or remove variables too. So when I run python2 I may have the PYTHONPATH seet to one thing, but if I run python3 I have it set to something different. And I could be running both at the same time. And another user (or service) logged into the same machine might be running a Django web server with yet another setting. So what is PYTHONPATH for that "machine"? The USER and HOME Values are set by the OS to different values depending on who is logged in, but the user can then change these later, etc... Even with no users logged in you might have different services running each with their own environment set up. It is very difficult for an admin to do anything reliably based on environment variable settings. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ > >From: Bill Allen >To: Alan Gauld >Cc: tutor at python.org >Sent: Saturday, 26 February, 2011 2:50:39 >Subject: Re: [Tutor] accessing another system's environment > >I apologize for not have been clear previously. What I am trying to access are >the Windows system environment variables. The same ones that are listed out if >you type the set command at a command prompt in Windows. > > > >--Bill > > > > > > >On Fri, Feb 25, 2011 at 03:11, Alan Gauld wrote: > > >>"Bill Allen" wrote >> >> >>I have times when it is useful for me to check the environment of a user >>>system on our lan remotely while trouble shooting and issue with them. Now, >>>this is quite easy to do while I am using a windows system via the computer >>>management console. >>> > I think we are meaning different things by "environment"? >>Can you give a specific example? >> >> >> >>However, I am trying to do this via a linux workstation >>>(which is joined to the domain, etc.). I cannot find a native >>>facility to duplicate the computer management functions, so I thought I >>>would write a program to fill the need. >>> > Anything you can do locally you can do on the remote >>machine with a combination of ssh, rsh, rlogin, telnet etc. >>ssh is the safest but requires a bit more admin to set it >>up properly for maximum convenience. >> >>Having got remote access its just a case of figuring out >>which of the 500 or so Unix commands you need to >>use to do the job... :-) >> >> >>HTH, >> >>-- >>Alan Gauld >>Author of the Learn to Program web site >>http://www.alan-g.me.uk/ >> >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>To unsubscribe or change subscription options: >>http://mail.python.org/mailman/listinfo/tutor >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Feb 26 10:29:26 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 26 Feb 2011 09:29:26 +0000 (GMT) Subject: [Tutor] Running Existing Python In-Reply-To: References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> Message-ID: <621483.98875.qm@web86705.mail.ird.yahoo.com> The error says it can't find the file hello.py. That means its probably in some other folder or you need to specify the full or relative path to the file This is a MacOS issue not Python, its how your MacOS shell is searching for the file. If it is in the same folder try explicitly telling MacOS: $ python ./hello.py Or if it is somewhere else either cd to that folder or type the path: $ python /the/full/path/to/the/dfile/hello.py There are some environment variables you can set in your login script which will help MacOS find the files but they depend on which shell Terminal is running, tcsh or bash are the usual options. Finally there is a trick you can use on the hello.py file that means you can launch the .py file directly from Finder. It's called the shebang trick by Unix folks. Basically you add a line like #! /usr/env/python To the very top of the file. MacOS will then use that command to execute the script. If usr/env doesn't work type $ which python and copy the output instead of /usr/env Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Original Message ---- > From: Justin Bonnell > To: Alan Gauld > Cc: tutor at python.org > Sent: Saturday, 26 February, 2011 6:49:37 > Subject: Re: [Tutor] Running Existing Python > > Okay. When I try to run the script from the terminal, it still doesn't work. >Here is a screenshot. > > > What am I doing wrong? > > > On Feb 25, 2011, at 6:46 PM, Alan Gauld wrote: > > > > > "Justin Bonnell" wrote > > > >> Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) [GCC 4.2.1 (Apple Inc. >build 5664)] on darwin > >> Type "copyright", "credits" or "license()" for more information. > > > > The >>> prompt means you are already inside Python. > > You can type Python commands at the >>> prompt, things like > > > >>>> print "Hello" > > > > But you cannot ruin a program from inside the >>> prompt (well, you can, but >its more complicated than sane people want to bother with! :-) > > > > You run a Python script from the OS Terminal prompt: > > > > $ python hello.py > > > >> Shouldn't I be able to run hello.py from the IDLE interpreter? > > > > You can't run it from the >>> prompt in IDLE but.... > > What you can do is open the file for editing and then run that file using >the menu commands, then the output will show up in the interpreter window. > > > I get how to do this now^^ > > HTH, > > > > -- > > Alan Gauld > > Author of the Learn to Program web site > > http://www.alan-g.me.uk/ > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > From jwbonnell5 at gmail.com Sat Feb 26 07:49:37 2011 From: jwbonnell5 at gmail.com (Justin Bonnell) Date: Sat, 26 Feb 2011 00:49:37 -0600 Subject: [Tutor] Running Existing Python In-Reply-To: References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> Message-ID: Okay. When I try to run the script from the terminal, it still doesn't work. Here is a screenshot. -------------- next part -------------- A non-text attachment was scrubbed... Name: Screen shot 2011-02-26 at 12.47.02 AM.png Type: image/png Size: 30616 bytes Desc: not available URL: -------------- next part -------------- What am I doing wrong? On Feb 25, 2011, at 6:46 PM, Alan Gauld wrote: > > "Justin Bonnell" wrote > >> Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin >> Type "copyright", "credits" or "license()" for more information. > > The >>> prompt means you are already inside Python. > You can type Python commands at the >>> prompt, things like > >>>> print "Hello" > > But you cannot ruin a program from inside the >>> prompt (well, you can, but its more complicated than sane people want to bother with! :-) > > You run a Python script from the OS Terminal prompt: > > $ python hello.py > >> Shouldn't I be able to run hello.py from the IDLE interpreter? > > You can't run it from the >>> prompt in IDLE but.... > What you can do is open the file for editing and then run that file using the menu commands, then the output will show up in the interpreter window. > I get how to do this now^^ > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at alchemy.com Sat Feb 26 10:40:12 2011 From: steve at alchemy.com (Steve Willoughby) Date: Sat, 26 Feb 2011 01:40:12 -0800 Subject: [Tutor] accessing another system's environment In-Reply-To: <994737.99124.qm@web86705.mail.ird.yahoo.com> References: <994737.99124.qm@web86705.mail.ird.yahoo.com> Message-ID: <4D68CA7C.3050202@alchemy.com> On 26-Feb-11 01:19, ALAN GAULD wrote: > Bill, > > That's the same thing we are talking about. > The problem is those environment variables are > highly variable so you can't talk about a machine's environment. > Two users on the same machine (at the same time) may have > very different environments. And a batch file or program can I'm a Unix hacker, so forgive me if my understanding of Windows is a bit naive. I think, though, that Windows has a set of environment variables which are system-wide, added automatically to the user set of variables when a new process is launched. Yes, they can be changed or deleted but there is a standard set applied to all users. If that's a correct assumption on my part, there must be somewhere that can be read from, probably (I would guess) in the registry. So a script which could read/write those registry keys may do what is required here. The issue of exposing that to remote machines remains a dangling issue, though. Of course, it's not entirely clear we're solving a Python question, although this discussion may well go more solidly into that space. > add or remove variables too. So when I run python2 I may have > the PYTHONPATH seet to one thing, but if I run python3 I > have it set to something different. And I could be running > both at the same time. And another user (or service) logged > into the same machine might be running a Django web server with > yet another setting. So what is PYTHONPATH for that "machine"? > > The USER and HOME Values are set by the OS to different > values depending on who is logged in, but the user can > then change these later, etc... > > Even with no users logged in you might have different services > running each with their own environment set up. > > It is very difficult for an admin to do anything reliably > based on environment variable settings. > > Alan Gauld > Author of the Learn To Program website > http://www.alan-g.me.uk/ > > > > *From:* Bill Allen > *To:* Alan Gauld > *Cc:* tutor at python.org > *Sent:* Saturday, 26 February, 2011 2:50:39 > *Subject:* Re: [Tutor] accessing another system's environment > > I apologize for not have been clear previously. What I am trying to > access are the Windows system environment variables. The same ones > that are listed out if you type the set command at a command prompt > in Windows. > > > --Bill > > > > > > On Fri, Feb 25, 2011 at 03:11, Alan Gauld > wrote: > > > "Bill Allen" > wrote > > I have times when it is useful for me to check the > environment of a user > system on our lan remotely while trouble shooting and issue > with them. Now, > this is quite easy to do while I am using a windows system > via the computer > management console. > > > I think we are meaning different things by "environment"? > Can you give a specific example? > > > However, I am trying to do this via a linux workstation > (which is joined to the domain, etc.). I cannot find a native > facility to duplicate the computer management functions, so > I thought I > would write a program to fill the need. > > > Anything you can do locally you can do on the remote > machine with a combination of ssh, rsh, rlogin, telnet etc. > ssh is the safest but requires a bit more admin to set it > up properly for maximum convenience. > > Having got remote access its just a case of figuring out > which of the 500 or so Unix commands you need to > use to do the job... :-) > > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From alan.gauld at btinternet.com Sat Feb 26 10:41:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Feb 2011 09:41:31 -0000 Subject: [Tutor] Cross-Module Interaction References: <4D688322.6090607@aim.com> <4D688B8C.2050604@pearwood.info> <4D68909E.2010808@aim.com> Message-ID: "Corey Richardson" wrote > I'm slightly concerned about performance when it comes to > reading/writing to disk a lot when doing things like that, since if > this > thing ever needs to scale I want it to be able to do that. There is always an overhead but it depends what you mean by "a lot". You might choose to only write on updates, only write when users leave the system, only write when the system closes down or write periodically (either a timed period or when certain resource levels get above/below critical levels) Lots of options. You need to choose a strategy that works for your situation. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Sat Feb 26 11:49:08 2011 From: davea at ieee.org (Dave Angel) Date: Sat, 26 Feb 2011 05:49:08 -0500 Subject: [Tutor] Running Existing Python In-Reply-To: References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> Message-ID: <4D68DAA4.4000308@ieee.org> On 01/-10/-28163 02:59 PM, Justin Bonnell wrote: > Okay. When I try to run the script from the terminal, it still doesn't work. Here is a screenshot. > > > > > > What am I doing wrong? > 1) You're top-posting. Put your responses after the quote you're responding to. 2) You're trying to include graphical images in a text-based newsgroup. Just use copy/paste, and include it in your message. 3) You don't tell us where the hello.py file actually is. Presumably it's not in the current directory when you run that. Two cures for that: either specify its real location, python ~/mysources/hello.py or cd to the proper directory. The latter is usually easier, but it depends where other files your script are located. DaveA From bouncingcats at gmail.com Sat Feb 26 11:54:47 2011 From: bouncingcats at gmail.com (David) Date: Sat, 26 Feb 2011 21:54:47 +1100 Subject: [Tutor] accessing another system's environment In-Reply-To: References: Message-ID: On 25 February 2011 14:30, Bill Allen wrote: > > I have times when it is useful for me to check the environment of a user > system on our lan remotely while trouble shooting and issue with them.? Now, > this is quite easy to do while I am using a windows system via the computer > management console.?? However, I am trying to do this via a linux > workstation (which is joined to the domain, etc.).?? I cannot find a native > facility to duplicate the computer management functions, so I thought I > would write a program to fill the need.?? Not to mention, I thought it might > be a good learning opportunity. If I understand correctly, you want to view/change the environment variables of some user running under some version of Windows while you are sitting at a remote Linux workstation. I have just done a test here which might help answer your query. I have "ssh" running on this linux box. I have "openssh" [1] running on a Windows 2000 sp4 box on my LAN. I can open a terminal on the linux box and run "ssh" to remote login to the windows box which then displays a windows "command prompt" shell in the terminal where I can use the dos "set" command to remotely view/change the windows environment variables. I expect that once you have this working interactively, it could be scripted using python, but I have not tested that. [1] http://sshwindows.webheat.co.uk Disclaimer: I personally have zero information about this software provider. So do not use it without conducting your own investigation into any security risks that might affect your situation. David From wprins at gmail.com Sat Feb 26 12:02:16 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 26 Feb 2011 11:02:16 +0000 Subject: [Tutor] Cross-Module Interaction In-Reply-To: <4D68909E.2010808@aim.com> References: <4D688322.6090607@aim.com> <4D688B8C.2050604@pearwood.info> <4D68909E.2010808@aim.com> Message-ID: On 26 February 2011 05:33, Corey Richardson wrote: > Aha, that explains why I didn't get any results. Each file got its own > interpreter instance. > Not wanting to nit pick, but no: It's not that each *file* does has its own interpreter instance, it's that every python instance that you start does not automatically persist anything that gets created while it lives. In other words, you can import many modules (files) into any given interpreter instance, but whether or not the stuff gets persisted anywhere is a seperate matter. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Sat Feb 26 12:05:57 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 26 Feb 2011 11:05:57 +0000 Subject: [Tutor] Cross-Module Interaction In-Reply-To: <4D68909E.2010808@aim.com> References: <4D688322.6090607@aim.com> <4D688B8C.2050604@pearwood.info> <4D68909E.2010808@aim.com> Message-ID: On 26 February 2011 05:33, Corey Richardson wrote: > > I'm slightly concerned about performance when it comes to > reading/writing to disk a lot when doing things like that, since if this > thing ever needs to scale I want it to be able to do that. > I'd be tempted to say you should not be worrying about such performance issues at this stage. Remember what Knuth said, "... premature optimization is the root of all evil" Suffice it to say you can push rather large amounts of disk I/O with Python, and you can always come up with creative caching systems or whatever once you get that far along and it proves to be a problem. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Sat Feb 26 12:06:06 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 26 Feb 2011 06:06:06 -0500 Subject: [Tutor] Cross-Module Interaction In-Reply-To: References: <4D688322.6090607@aim.com> <4D688B8C.2050604@pearwood.info> <4D68909E.2010808@aim.com> Message-ID: <4D68DE9E.3070107@aim.com> On 02/26/2011 06:02 AM, Walter Prins wrote: > On 26 February 2011 05:33, Corey Richardson wrote: > >> Aha, that explains why I didn't get any results. Each file got its own >> interpreter instance. >> > > Not wanting to nit pick, but no: It's not that each *file* does has its own > interpreter instance, it's that every python instance that you start does > not automatically persist anything that gets created while it lives. In > other words, you can import many modules (files) into any given interpreter > instance, but whether or not the stuff gets persisted anywhere is a seperate > matter. > > Walter > I ran them like this: python use1.py python use2.py python plib.py Each file got its own instance of the interpreter. -- Corey Richardson From kb1pkl at aim.com Sat Feb 26 12:10:46 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 26 Feb 2011 06:10:46 -0500 Subject: [Tutor] Cross-Module Interaction In-Reply-To: References: <4D688322.6090607@aim.com> <4D688B8C.2050604@pearwood.info> <4D68909E.2010808@aim.com> Message-ID: <4D68DFB6.2050302@aim.com> On 02/26/2011 06:05 AM, Walter Prins wrote: > I'd be tempted to say you should not be worrying about such performance > issues at this stage. Indeed, but I can't have every piece of variable information being saved to disk and then read back again every time a player leaves or enters a room, that'd just be silly! Playing MUD's for a bit it gets annoying on a medium-size server when you have to wait more than 3 seconds just to get how much health you have after attacking some baddie. I won't be trying to pull every microsecond of efficiency out of this, but I would like it to be sensible and now waste time dawdling. (And the full quote is "We should forget about *small* efficiencies, say about 97% of the time: premature optimization is the root of all evil." (emphasis added)) -- Corey Richardson From wprins at gmail.com Sat Feb 26 12:11:29 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 26 Feb 2011 11:11:29 +0000 Subject: [Tutor] Cross-Module Interaction In-Reply-To: <4D68DE9E.3070107@aim.com> References: <4D688322.6090607@aim.com> <4D688B8C.2050604@pearwood.info> <4D68909E.2010808@aim.com> <4D68DE9E.3070107@aim.com> Message-ID: On 26 February 2011 11:06, Corey Richardson wrote: > I ran them like this: > python use1.py > python use2.py > python plib.py > > Each file got its own instance of the interpreter. > Yes, but not because instances are intrinsically linked to seperate python modules, which is what it sounds like you're saying. In the above case you *explicitly* started the 3 python instances seperately yourself from the command line, giving each instance a file to run, which is why you got 3 seperate instances. It's nothing to do with the fact that you have 3 files as such. (You'd have had 3 instances even if you ran the same file 3 times.) If you e.g. ran "use1.py" which then imported or ran use2.py and use3.py they'd all have used the same instance. Similarly, if you'd opened all 3 files in IDLE, and ran them with F5 in turn, they'd all have run in the *same* interpreter instance. Perhaps you do understand and you've expressed yourself poorly or I've just miinterpreted what you meant, I just wanted to make sure you don't think that seperate files (modules) will by some magic always have their own instances (which is not the case in general.) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Sat Feb 26 12:17:39 2011 From: python at bdurham.com (python at bdurham.com) Date: Sat, 26 Feb 2011 06:17:39 -0500 Subject: [Tutor] accessing another system's environment In-Reply-To: <4D68CA7C.3050202@alchemy.com> References: <994737.99124.qm@web86705.mail.ird.yahoo.com> <4D68CA7C.3050202@alchemy.com> Message-ID: <1298719059.12300.1423996501@webmail.messagingengine.com> Bill, Coming into this thread late: If you are working with Windows workstations, try posting your question on the Python Windows API mailing list. http://mail.python.org/mailman/listinfo/python-win32 You may be able to use WMI (via Python) to accomplish what you're trying to do. Malcolm From wprins at gmail.com Sat Feb 26 12:19:48 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 26 Feb 2011 11:19:48 +0000 Subject: [Tutor] Cross-Module Interaction In-Reply-To: <4D68DFB6.2050302@aim.com> References: <4D688322.6090607@aim.com> <4D688B8C.2050604@pearwood.info> <4D68909E.2010808@aim.com> <4D68DFB6.2050302@aim.com> Message-ID: On 26 February 2011 11:10, Corey Richardson wrote: > On 02/26/2011 06:05 AM, Walter Prins wrote: > > I'd be tempted to say you should not be worrying about such performance > > issues at this stage. > > Indeed, but I can't have every piece of variable information being saved > to disk and then read back again every time a player leaves or enters a > room, that'd just be silly! > Sure. I still think however that at this stage it's a much of a muchness. Modern PC's and disk caching subsystems being what they are, you likely won't really notice it either way until you're quite far along with this project. ;) (I'm not suggesting you should be willfully stupid of course, and the mere fact that you write the above indicates you're not, so there's no problem!) > Playing MUD's for a bit it gets annoying on a medium-size server when > you have to wait more than 3 seconds just to get how much health you > have after attacking some baddie. I won't be trying to pull every > microsecond of efficiency out of this, but I would like it to be > sensible and now waste time dawdling. > Sure. It's of course an assumption that the delay you see is due to disk I/O... (it may well be, but then again there's lots of possible reasons for things being slow...) > > (And the full quote is "We should forget about *small* efficiencies, say > about 97% of the time: premature optimization is the root of all evil." > (emphasis added)) > I know what the full quote is, I continue to be of the opinion that the point it makes is relevant, it's not worth worrying too much about. Pick a strategy that works sufficiently, you can always refactor and improve when needed. Good luck, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Feb 26 12:39:11 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Feb 2011 22:39:11 +1100 Subject: [Tutor] Running Existing Python In-Reply-To: References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> Message-ID: <4D68E65F.7070002@pearwood.info> Justin Bonnell wrote: > Okay. When I try to run the script from the terminal, it still doesn't work. Here is a screenshot. Please don't send screenshots except as a last resort. Just copy and paste the error message -- it is ordinary text in a terminal window. The error seems pretty straight-forward: it says no such file or directory. You're telling Python to run the file "hello.py" in the current directory. There obviously is no such file -- either you got the name wrong (perhaps it is "Hello.py"?) or it is in another directory. -- Steven From wprins at gmail.com Sat Feb 26 12:42:12 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 26 Feb 2011 11:42:12 +0000 Subject: [Tutor] accessing another system's environment In-Reply-To: References: <4D68732F.2090801@alchemy.com> <4D687470.6020807@alchemy.com> Message-ID: On 26 February 2011 04:26, Bill Allen wrote: > Yes, that's it exactly. :-) > > I administrate the workstations in our engineering environment and some of > the major pieces of software we use are configured via the Windows system > environment variables. Being able to reach out to a PC and check or change > those is handy, even important, in my situation. I am trying to explore > the possibility of managing these from a system I am using in a platform > independent way and figure that I ought to be able to do this with Python. > Perhaps there are third party Python modules I need to help accomplish this? > Are you intending changing *running processes* environment variables, or merely update a given PC's configuration so that next time an app starts they'll see the new settings? (I'd guess the latter as even Windows itself won't e.g. update running instances of cmd.exe's environment when you change them after an instance of cmd.exe has started.) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sat Feb 26 12:52:18 2011 From: davea at ieee.org (Dave Angel) Date: Sat, 26 Feb 2011 06:52:18 -0500 Subject: [Tutor] accessing another system's environment In-Reply-To: <4D68CA7C.3050202@alchemy.com> References: <994737.99124.qm@web86705.mail.ird.yahoo.com> <4D68CA7C.3050202@alchemy.com> Message-ID: <4D68E972.4020406@ieee.org> On 01/-10/-28163 02:59 PM, Steve Willoughby wrote: > On 26-Feb-11 01:19, ALAN GAULD wrote: >> Bill, >> >> That's the same thing we are talking about. >> The problem is those environment variables are >> highly variable so you can't talk about a machine's environment. >> Two users on the same machine (at the same time) may have >> very different environments. And a batch file or program can > > I'm a Unix hacker, so forgive me if my understanding of Windows is a bit > naive. I think, though, that Windows has a set of environment variables > which are system-wide, added automatically to the user set of variables > when a new process is launched. Yes, they can be changed or deleted but > there is a standard set applied to all users. > > If that's a correct assumption on my part, there must be somewhere that > can be read from, probably (I would guess) in the registry. So a script > which could read/write those registry keys may do what is required here. > > The issue of exposing that to remote machines remains a dangling issue, > though. > > Of course, it's not entirely clear we're solving a Python question, > although this discussion may well go more solidly into that space. > Indeed. in Windows, there are two sets of registry keys for environment variables, one is system wide, and one is per user. When Explorer launches a console or an application for a particular user, it combines those two sets of keys to come up with an initial set of environment variables. I tried to launch a VirtualBox XP machine, but it failed for some reason. Probably I have too much else running. So I can't tell you the key names. I'd suggest asking about remotely accessing the registry on the python-win32 forum. I'm sure the win32 extension have a way, I just don't know if it'll work from a Linux client. DaveA From bouncingcats at gmail.com Sat Feb 26 12:59:27 2011 From: bouncingcats at gmail.com (David) Date: Sat, 26 Feb 2011 22:59:27 +1100 Subject: [Tutor] accessing another system's environment In-Reply-To: References: <4D68732F.2090801@alchemy.com> <4D687470.6020807@alchemy.com> Message-ID: On 26 February 2011 22:42, Walter Prins wrote: > > On 26 February 2011 04:26, Bill Allen wrote: >> >> I administrate the workstations in our engineering environment and some of >> the major pieces of software we use are configured via the Windows system >> environment variables. Being able to reach out to a PC and check or change >> those is handy, even important, in my situation. I am trying to explore >> the possibility of managing these from a system I am using in a platform >> independent way and figure that I ought to be able to do this with Python. >> Perhaps there are third party Python modules I need to help accomplish this? > > Are you intending changing *running processes* environment variables, or > merely update a given PC's configuration so that next time an app starts > they'll see the new settings? (I'd guess the latter as even Windows itself > won't e.g. update running instances of cmd.exe's environment when you change > them after an instance of cmd.exe has started.) Indeed. "check" is easy by my method. "change" is harder. I can only guess this would involve somehow editing the windows registry. I have nothing to offer on that topic. From modulok at gmail.com Sat Feb 26 13:16:17 2011 From: modulok at gmail.com (Modulok) Date: Sat, 26 Feb 2011 05:16:17 -0700 Subject: [Tutor] accessing another system's environment In-Reply-To: <4D68E972.4020406@ieee.org> References: <994737.99124.qm@web86705.mail.ird.yahoo.com> <4D68CA7C.3050202@alchemy.com> <4D68E972.4020406@ieee.org> Message-ID: I'm coming into this thread late so I might be off the mark here, but it seems like you're going about it backwards: Instead of trying to reach in and modify a user's environment, which is highly variable and process dependent, why not just wrap the software they're running? Have a python script wrap all of the programs you're trying to configure on the client's machine. (No matter how you do it, you'd have to install a client program of some kind anyway.) When they launch the 'program' in question, they're really launching a python script. The script checks in with a remote server that holds the config files or environment data. (Or whatever else you need.) The client script says some thing like "I'm john, running program version x.x. Give me my env variables".) The server then replies with any variables that the client needs to set and their values. You could do this with a python script running on a server sending ajax responses. (There's an ajax module in the standard library.) The wrapper, running on the client gets the response and set any environment variables for the process it's about to launch. It then starts the real program, passing the properly configured environment on to it. You have to write two programs. 1. A client wrapper that asks the server for its data and 2. A simple server that passes any data back to the client. In effect, you'll be able to change the clients configuration, environment variables or *anything else* that needs done before your script launches the the real client program. You don't have to deal with screwing around with the client's environment or the complexities that brings up either. On 2/26/11, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, Steve Willoughby wrote: >> On 26-Feb-11 01:19, ALAN GAULD wrote: >>> Bill, >>> >>> That's the same thing we are talking about. >>> The problem is those environment variables are >>> highly variable so you can't talk about a machine's environment. >>> Two users on the same machine (at the same time) may have >>> very different environments. And a batch file or program can >> >> I'm a Unix hacker, so forgive me if my understanding of Windows is a bit >> naive. I think, though, that Windows has a set of environment variables >> which are system-wide, added automatically to the user set of variables >> when a new process is launched. Yes, they can be changed or deleted but >> there is a standard set applied to all users. >> >> If that's a correct assumption on my part, there must be somewhere that >> can be read from, probably (I would guess) in the registry. So a script >> which could read/write those registry keys may do what is required here. >> >> The issue of exposing that to remote machines remains a dangling issue, >> though. >> >> Of course, it's not entirely clear we're solving a Python question, >> although this discussion may well go more solidly into that space. >> > > Indeed. in Windows, there are two sets of registry keys for environment > variables, one is system wide, and one is per user. When Explorer > launches a console or an application for a particular user, it combines > those two sets of keys to come up with an initial set of environment > variables. > > I tried to launch a VirtualBox XP machine, but it failed for some > reason. Probably I have too much else running. So I can't tell you the > key names. > > I'd suggest asking about remotely accessing the registry on the > python-win32 forum. I'm sure the win32 extension have a way, I just > don't know if it'll work from a Linux client. > > DaveA > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From modulok at gmail.com Sat Feb 26 13:28:15 2011 From: modulok at gmail.com (Modulok) Date: Sat, 26 Feb 2011 05:28:15 -0700 Subject: [Tutor] accessing another system's environment In-Reply-To: References: <994737.99124.qm@web86705.mail.ird.yahoo.com> <4D68CA7C.3050202@alchemy.com> <4D68E972.4020406@ieee.org> Message-ID: On 2/26/11, Modulok wrote: ... > The server then replies with any variables that the client needs to > set and their values. You could do this with a python script running > on a server sending ajax responses. (There's an ajax module in the > standard library.) ... Sorry, I meant a 'json' module, not 'ajax'. I've been doing too much web programming recently :p. You could probably even get away with not having to write a server, just set up a web server to handle it, sending a well-formed response. -Modulok- From wallenpb at gmail.com Sat Feb 26 16:54:51 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 26 Feb 2011 09:54:51 -0600 Subject: [Tutor] accessing another system's environment In-Reply-To: References: Message-ID: Wow! What an overwhelming response to my inquiry. All the post have been very informative and have given me plenty to consider. I can see now this is a win32 api question, not really Python. There has been more than enough here to point to some resources for win32 api and I have found library resources for that for Python, so I think I am on my way. It is just a matter of finding the right win32 api calls to do what I am wanting to do. Thanks again everyone, this was a great help to me. -Bill On Wed, Feb 23, 2011 at 21:53, Bill Allen wrote: > > I know that I can use the following to get a listing of the environment of > my own system. How can I do similar for another system on my network. > This is for administrative purposes. > > >>> import os > >>> for param in os.environ.keys(): > print(param, os.environ[param]) > > --Bill > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.klaitos at gmail.com Sat Feb 26 18:49:51 2011 From: chris.klaitos at gmail.com (Christopher Brookes) Date: Sat, 26 Feb 2011 18:49:51 +0100 Subject: [Tutor] Object, methods, class Message-ID: Hi, Is there in Python private/protected attributes in class like in other langage ? -- Brookes Christopher. -------------- next part -------------- An HTML attachment was scrubbed... URL: From knacktus at googlemail.com Sat Feb 26 19:17:03 2011 From: knacktus at googlemail.com (Knacktus) Date: Sat, 26 Feb 2011 19:17:03 +0100 Subject: [Tutor] Object, methods, class In-Reply-To: References: Message-ID: <4D69439F.5030404@googlemail.com> Am 26.02.2011 18:49, schrieb Christopher Brookes: > Hi, > Is there in Python private/protected attributes in class like in other > langage ? Yes, there is. But it's protected by convention not compiler ;-). Check out this: http://docs.python.org/tutorial/classes.html#private-variables > > -- > Brookes Christopher. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From jwbonnell5 at gmail.com Sat Feb 26 22:10:15 2011 From: jwbonnell5 at gmail.com (Justin Bonnell) Date: Sat, 26 Feb 2011 15:10:15 -0600 Subject: [Tutor] Running Existing Python In-Reply-To: <4D68DAA4.4000308@ieee.org> References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <4D68DAA4.4000308@ieee.org> Message-ID: On Feb 26, 2011, at 4:49 AM, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, Justin Bonnell wrote: >> Okay. When I try to run the script from the terminal, it still doesn't work. Here is a screenshot. >> >> >> >> >> >> What am I doing wrong? >> > 1) You're top-posting. Put your responses after the quote you're responding to. --Okay. I'm pretty new to this so most of my responses were just general questions rather than specific responses. > > 2) You're trying to include graphical images in a text-based newsgroup. Just use copy/paste, and include it in your message. --Got it. I will do that from now on. > > 3) You don't tell us where the hello.py file actually is. Presumably it's not in the current directory when you run that. Two cures for that: either specify its real location, > python ~/mysources/hello.py --This is the location of the file: /jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py but it still says it cannot find the directory when I try to run it or cd to it. Is there any way that I can tell which directory the shell is currently working from? > or cd to the proper directory. The latter is usually easier, but it depends where other files your script are located. > > DaveA -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Sat Feb 26 22:18:00 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 26 Feb 2011 16:18:00 -0500 Subject: [Tutor] Running Existing Python In-Reply-To: References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <4D68DAA4.4000308@ieee.org> Message-ID: <4D696E08.8040407@aim.com> On 02/26/2011 04:10 PM, Justin Bonnell wrote: > --This is the location of the file: > > /jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py > > but it still says it cannot find the directory when I try to run it or cd to it. Is there any way that I can tell which directory the shell is currently working from? At the terminal, the command "pwd" , print working directory, should do the trick. If you cannot cd to the directory, that's generally a pretty big hint that the directory doesn't exist ;-) But yet you can see it in your file browser? That's most curious. -- Corey Richardson From jwbonnell5 at gmail.com Sat Feb 26 22:18:15 2011 From: jwbonnell5 at gmail.com (Justin Bonnell) Date: Sat, 26 Feb 2011 15:18:15 -0600 Subject: [Tutor] Running Existing Python In-Reply-To: <621483.98875.qm@web86705.mail.ird.yahoo.com> References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <621483.98875.qm@web86705.mail.ird.yahoo.com> Message-ID: <11FD2C7C-5448-44E5-8DD9-688721A3D903@gmail.com> On Feb 26, 2011, at 3:29 AM, Alan Gauld wrote: This is really helpful directions and I am trying to follow what you're saying. I think you are getting my response to another person helping me so this will basically repeat what I was saying there. I am really new to this and am trying to learn on my own so thanks for your help and patience. > The error says it can't find the file hello.py. > That means its probably in some other folder > or you need to specify the full or relative path to the file > This is a MacOS issue not Python, its how your MacOS > shell is searching for the file. > > If it is in the same folder try explicitly telling MacOS: > > $ python ./hello.py > > Or if it is somewhere else either cd to that folder > or type the path: > > $ python /the/full/path/to/the/dfile/hello.py --I tried to follow this using: /jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py which is the correct location of the hello.py file. > > There are some environment variables you can > set in your login script which will help MacOS > find the files but they depend on which shell > Terminal is running, tcsh or bash are the usual > options. --My Terminal is running bash. > > Finally there is a trick you can use on the hello.py > file that means you can launch the .py file directly > from Finder. It's called the shebang trick by Unix > folks. > > Basically you add a line like > > #! /usr/env/python > > To the very top of the file. MacOS will then use that > command to execute the script. If usr/env doesn't > work type --So if I add that line to the file, then I use $ python /usr/env/python ? > > $ which python --This is the correct for my computer: /Library/Frameworks/Python.framework/Versions/2.7/bin/python > > and copy the output instead of /usr/env > > > Alan Gauld > Author of the Learn To Program website > http://www.alan-g.me.uk/ > > > > > ----- Original Message ---- >> From: Justin Bonnell >> To: Alan Gauld >> Cc: tutor at python.org >> Sent: Saturday, 26 February, 2011 6:49:37 >> Subject: Re: [Tutor] Running Existing Python >> >> Okay. When I try to run the script from the terminal, it still doesn't work. >> Here is a screenshot. >> >> >> What am I doing wrong? >> >> >> On Feb 25, 2011, at 6:46 PM, Alan Gauld wrote: >> >>> >>> "Justin Bonnell" wrote >>> >>>> Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) [GCC 4.2.1 (Apple Inc. >> build 5664)] on darwin >>>> Type "copyright", "credits" or "license()" for more information. >>> >>> The >>> prompt means you are already inside Python. >>> You can type Python commands at the >>> prompt, things like >>> >>>>>> print "Hello" >>> >>> But you cannot ruin a program from inside the >>> prompt (well, you can, but >> its more complicated than sane people want to bother with! :-) >>> >>> You run a Python script from the OS Terminal prompt: >>> >>> $ python hello.py >>> >>>> Shouldn't I be able to run hello.py from the IDLE interpreter? >>> >>> You can't run it from the >>> prompt in IDLE but.... >>> What you can do is open the file for editing and then run that file using >> the menu commands, then the output will show up in the interpreter window. >>> >> I get how to do this now^^ >>> HTH, >>> >>> -- >>> Alan Gauld >>> Author of the Learn to Program web site >>> http://www.alan-g.me.uk/ >>> >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >> >> From shantanoo at gmail.com Sat Feb 26 22:20:05 2011 From: shantanoo at gmail.com (=?utf-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Sun, 27 Feb 2011 02:50:05 +0530 Subject: [Tutor] Running Existing Python In-Reply-To: References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <4D68DAA4.4000308@ieee.org> Message-ID: On 27-Feb-2011, at 2:40 AM, Justin Bonnell wrote: > On Feb 26, 2011, at 4:49 AM, Dave Angel wrote: >> 3) You don't tell us where the hello.py file actually is. Presumably it's not in the current directory when you run that. Two cures for that: either specify its real location, >> python ~/mysources/hello.py > > --This is the location of the file: > > /jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py You need to escape space. Try /jwbonnell/bin/Python\ 2.7/Extras/Demo/tkinter/guido/hello.py There is '\' before space. From davea at ieee.org Sat Feb 26 23:05:07 2011 From: davea at ieee.org (Dave Angel) Date: Sat, 26 Feb 2011 17:05:07 -0500 Subject: [Tutor] Running Existing Python In-Reply-To: References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <4D68DAA4.4000308@ieee.org> Message-ID: <4D697913.8050400@ieee.org> On 02/26/2011 04:10 PM, Justin Bonnell wrote: > > On Feb 26, 2011, at 4:49 AM, Dave Angel wrote: > >> On 01/-10/-28163 02:59 PM, Justin Bonnell wrote: >>> Okay. When I try to run the script from the terminal, it still doesn't work. Here is a screenshot. >>> >>> >>> >>> >>> >>> What am I doing wrong? >>> >> 1) You're top-posting. Put your responses after the quote you're responding to. > --Okay. I'm pretty new to this so most of my responses were just general questions rather than specific responses. >> >> 2) You're trying to include graphical images in a text-based newsgroup. Just use copy/paste, and include it in your message. > --Got it. I will do that from now on. > >> >> 3) You don't tell us where the hello.py file actually is. Presumably it's not in the current directory when you run that. Two cures for that: either specify its real location, >> python ~/mysources/hello.py > > --This is the location of the file: > > /jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py > > but it still says it cannot find the directory when I try to run it or cd to it. Is there any way that I can tell which directory the shell is currently working from? > pwd will show your current directory on Linux. And it's usually showing in your prompt. As for cd not working, someone else has pointed out that in the shell, you need to escape certain characters, the space being one. I try to avoid ever having spaces in directory or file names. >> or cd to the proper directory. The latter is usually easier, but it depends where other files your script are located. >> >> DaveA > > From wprins at gmail.com Sat Feb 26 23:18:18 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 26 Feb 2011 22:18:18 +0000 Subject: [Tutor] Running Existing Python In-Reply-To: <11FD2C7C-5448-44E5-8DD9-688721A3D903@gmail.com> References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <621483.98875.qm@web86705.mail.ird.yahoo.com> <11FD2C7C-5448-44E5-8DD9-688721A3D903@gmail.com> Message-ID: On 26 February 2011 21:18, Justin Bonnell wrote: > --I tried to follow this using: > /jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py > which is the correct location of the hello.py file. > Try putting quotes around the full path. The problem is that the space between "Python" and "2.7" makes the line look like 2 arguments, e.g. /jwbonnell/bin/Python ... and ... 2.7/Extras/Demo/tkinter/guido/hello.py If you double quote the entire string like so: "/jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py" By quoting the line you're telling the system not to interpret that space and make it part of the argument to the Python interpreter. (Aside: You would need to quote the path also when using it with the "cd" command, as the same problem will happen unless you quote it.) The other thing I'd suggest is to just use IDLE which may be slightly easier at this point. In the main IDLE shell, click "File"->"Open", open the file (it opens in its own window) then run it from there using e.g. F5. The output appears in the IDLE shell then. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Feb 26 23:26:12 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Feb 2011 09:26:12 +1100 Subject: [Tutor] Running Existing Python In-Reply-To: References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <4D68DAA4.4000308@ieee.org> Message-ID: <4D697E04.5010001@pearwood.info> Justin Bonnell wrote: > --This is the location of the file: > > /jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py I doubt that. Mac OS is a type of Unix, and it would shock me if it puts home directories (the jwbonnell/ part) directly under the file system root / My guess is that the correct path is probably /home/jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py but of course I could be wrong. Don't forget to quote the path, otherwise the spaces will mess things up for you: "/home/jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py" Try running this command from your command prompt: locate hello.py and see if it gives anything useful. (I don't know if OS X comes with locate as standard, so don't be surprised if you get an error.) Another alternative would be to refer to the file using: python ~/"bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py" Note that you don't quote the tilde ~ at the start. -- Steven From jwbonnell5 at gmail.com Sat Feb 26 22:32:45 2011 From: jwbonnell5 at gmail.com (Justin Bonnell) Date: Sat, 26 Feb 2011 15:32:45 -0600 Subject: [Tutor] Running Existing Python In-Reply-To: <4D696E08.8040407@aim.com> References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <4D68DAA4.4000308@ieee.org> <4D696E08.8040407@aim.com> Message-ID: <0A90776D-EEE0-42DC-8F14-847819AB7E04@gmail.com> On Feb 26, 2011, at 3:18 PM, Corey Richardson wrote: > On 02/26/2011 04:10 PM, Justin Bonnell wrote: > >> --This is the location of the file: >> >> /jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py >> >> but it still says it cannot find the directory when I try to run it or cd to it. Is there any way that I can tell which directory the shell is currently working from? > > At the terminal, the command "pwd" , print working directory, should do > the trick. > > If you cannot cd to the directory, that's generally a pretty big hint > that the directory doesn't exist ;-) > > But yet you can see it in your file browser? That's most curious. --My current working directory is not what I have been trying to cd to, so I'm assuming that I am using the cd command wrong. I have tried: $ cd /jwbonnell/bin/Python\2.7/Extras/Demo/tkinter/guido $ cd /jwbonnell/bin/Python\2.7/Extras/Demo/tkinter/guido/hello.py $ cd /jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py > > -- > Corey Richardson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kb1pkl at aim.com Sat Feb 26 23:47:13 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 26 Feb 2011 17:47:13 -0500 Subject: [Tutor] Running Existing Python In-Reply-To: <0A90776D-EEE0-42DC-8F14-847819AB7E04@gmail.com> References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <4D68DAA4.4000308@ieee.org> <4D696E08.8040407@aim.com> <0A90776D-EEE0-42DC-8F14-847819AB7E04@gmail.com> Message-ID: <4D6982F1.10303@aim.com> On 02/26/2011 04:32 PM, Justin Bonnell wrote: > --My current working directory is not what I have been trying to cd to, so I'm assuming that I am using the cd command wrong. > > I have tried: > > $ cd /jwbonnell/bin/Python\2.7/Extras/Demo/tkinter/guido > $ cd /jwbonnell/bin/Python\2.7/Extras/Demo/tkinter/guido/hello.py > $ cd /jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py > Alas, you still do it wrong. You don't just replace the space with a backslash, you put a slash _before_ the space. Or like Steven (I think it was) suggested, put it in quotes. -- Corey Richardson From steve at pearwood.info Sun Feb 27 00:31:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Feb 2011 10:31:58 +1100 Subject: [Tutor] Object, methods, class In-Reply-To: References: Message-ID: <4D698D6E.3020006@pearwood.info> Christopher Brookes wrote: > Hi, > Is there in Python private/protected attributes in class like in other > langage ? There's a short answer, a long answer, and an even longer answer. The short answer is No. The long answer is, not exactly. Python has private names, but they are not enforced by the compiler, but only by naming convention: use names starting with a single underscore to mean "private": _private_variable = 42 Anybody using such private names will know that they have nobody to blame but themselves if things break. Inside classes (but not outside), there is a second convention which is enforced by the compiler: name mangling. If you define this: class K: _a = 23 __b = 42 # TWO leading underscores the _a attribute is private by convention, but the __b attribute has its name mangled by the compiler to: _K__b This is to prevent *accidental* clashes when writing subclasses, but of course it can't prevent deliberate access. Since you know the name of the class, it's easy to do your own mangling and get access to the "private" attribute. (For extra bonus points, can you see which circumstances namespace mangling will fail to prevent accidental name clashes?) You might be thinking that double-underscore names are "stronger", and therefore safer, than single-underscore. No. In my opinion, don't waste your time and energy with double-underscore names. There's one further naming convention that is relevant: names with double leading and trailing underscores. These names are reserved for Python, and are used for special methods like __init__ __getitem__ __enter__ etc. The even longer answer is, no, and thank goodness for that, because having the compiler enforce private attributes is a real pain! It gets in the way of testing and debugging, and testing is MUCH more important than private or protected. It does very little good, and lots of harm, and gets in the way of things that you need. The internet is full of people asking "how do I access private members" and similar questions. They're not asking it to be difficult, but because they need to. It is a *good* thing that Python makes it a convention. In every language that I know of, it is possible to bypass the compiler's protection of private and protected attributes: E.g. in Ruby: http://blog.confabulus.com/2008/10/26/testing-protected-and-private-methods-in-ruby/ http://www.skorks.com/2010/04/ruby-access-control-are-private-and-protected-methods-only-a-guideline/ In C++: http://www.gotw.ca/gotw/076.htm http://stackoverflow.com/questions/729363/is-it-possible-to-access-private-members-of-a-class Java: http://stackoverflow.com/questions/1306166/how-can-i-access-private-class-members-in-java Python takes another approach. Instead of putting up barriers to the caller that must be overcome, barriers that just get in the way of debugging and testing, Python doesn't waste it's time trying to enforce something that people will find a way to break. Instead Python takes the attitude "we're all adults here". It trusts you not to access private attributes and methods unless you really need to, and to take the consequences if you do. (The only exception is that protection of objects written in C is treated more strongly, because that could cause a core dump and potential memory corruption, not just a safe Python exception. But even there, using the new ctypes module, you can do some pretty scary things.) -- Steven From steve at pearwood.info Sun Feb 27 00:37:38 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Feb 2011 10:37:38 +1100 Subject: [Tutor] Running Existing Python In-Reply-To: <0A90776D-EEE0-42DC-8F14-847819AB7E04@gmail.com> References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <4D68DAA4.4000308@ieee.org> <4D696E08.8040407@aim.com> <0A90776D-EEE0-42DC-8F14-847819AB7E04@gmail.com> Message-ID: <4D698EC2.4090405@pearwood.info> Justin Bonnell wrote: > --My current working directory is not what I have been trying to cd to, so I'm assuming that I am using the cd command wrong. You don't need to cd into the current working directory. You're already there. That's what "working directory" means -- the directory you just cd'ed into. But you can if you like. That's just: cd . Dot always means "this directory", no matter where you are. > I have tried: > > $ cd /jwbonnell/bin/Python\2.7/Extras/Demo/tkinter/guido And what happened? Please run these two lines and copy and paste the results back to us: ls -ld /jwbonnell ls -ld /home/jwbonnell > $ cd /jwbonnell/bin/Python\2.7/Extras/Demo/tkinter/guido/hello.py > $ cd /jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py cd stands for Change Directory. You can't cd into a file. -- Steven From alan.gauld at btinternet.com Sun Feb 27 01:55:51 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 27 Feb 2011 00:55:51 +0000 (GMT) Subject: [Tutor] Running Existing Python In-Reply-To: References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <4D68DAA4.4000308@ieee.org> Message-ID: <908521.41552.qm@web86705.mail.ird.yahoo.com> --This is the location of the file: > > >/jwbonnell/bin/Python 2.7/Extras/Demo/tkinter/guido/hello.py > > >but it still says it cannot find the directory when I try to run it or cd to it. > >As an obvious beginner with the shell the easiest way to change folder is MacOS is to use the Finder. type cd at the prrompt then locate the folder in Finder and drag it to the Terminal window. That should cause the Terminal to change to that folder The other thing to do is to let the shell copmplete the name for you, thus type cd /jwb and the shell will complete the first folder for you, then type bi to complete bin and so on. That will ensure the spaces are handled correctly. HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 27 02:18:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Feb 2011 01:18:22 -0000 Subject: [Tutor] Object, methods, class References: Message-ID: "Christopher Brookes" wrote > Is there in Python private/protected attributes in class like in > other > langage ? Steven has given you a comprehensive answer but as a bit of history none of the early OOP languages used public/protected/private etc. They either made all variables private (Smalltalk) or public (Object Pascal and Simula(I think) ). It was really C++ that started the vogue for mixing and matching the styles. Even it didn't introduce protected until version 1.2 of the language and Stroustrup admits to having concerns and doubts about the wisdom of the decision. But several other languages (Java, Object Pascal(aka Delphi) ) have followed C++ down that route. Python just asks users to be sensible, it doesn't attempt to protect(excuse the pun) them from themselves! Just musing.... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From vineethrakesh at gmail.com Sun Feb 27 04:11:15 2011 From: vineethrakesh at gmail.com (vineeth) Date: Sat, 26 Feb 2011 22:11:15 -0500 Subject: [Tutor] python module to search a website Message-ID: <4D69C0D3.5050801@gmail.com> Hello all, I am looking forward for a python module to search a website and extract the url. For example I found a module for Amazon with the name "amazonproduct", the api does the job of extracting the data based on the query it even parses the url data. I am looking some more similar query search python module for other websites like Amazon. Any help is appreciated. Thank You Vin From kb1pkl at aim.com Sun Feb 27 05:05:22 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 26 Feb 2011 23:05:22 -0500 Subject: [Tutor] python module to search a website In-Reply-To: <4D69C0D3.5050801@gmail.com> References: <4D69C0D3.5050801@gmail.com> Message-ID: <4D69CD82.30800@aim.com> On 02/26/2011 10:11 PM, vineeth wrote: > Hello all, > > I am looking forward for a python module to search a website and extract > the url. What website, what is it searching for, and what URL is it looking for? > > For example I found a module for Amazon with the name "amazonproduct", > the api does the job of extracting the data based on the query it even > parses the url data. I am looking some more similar query search python > module for other websites like Amazon. The only module I found for amazon-product was a python interface to Amazon's advertising API. What data does it extract, what query, and which URL does it parse? From what I found that module uses the API to search the website, a service provided by Amazon and not something Python is doing itself. You may want to look into urlparse and urllib2, for parsing URLs and opening websites respectively. http://docs.python.org/library/urlparse.html http://docs.python.org/library/urllib2.html If that isn't what you're looking for, you'll need to be a bit more descriptive. If you are going to be parsing the HTML and then searching for specific elements you might look into BeautifulSoup. -- Corey Richardson From wallenpb at gmail.com Sun Feb 27 06:04:27 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 26 Feb 2011 23:04:27 -0600 Subject: [Tutor] python module to search a website In-Reply-To: <4D69C0D3.5050801@gmail.com> References: <4D69C0D3.5050801@gmail.com> Message-ID: n Sat, Feb 26, 2011 at 21:11, vineeth wrote: > Hello all, > > I am looking forward for a python module to search a website and extract > the url. > > For example I found a module for Amazon with the name "amazonproduct", the > api does the job of extracting the data based on the query it even parses > the url data. I am looking some more similar query search python module for > other websites like Amazon. > > Any help is appreciated. > > Thank You > Vin > I am not sure what url you are trying to extract, or from where, but I can give you an example of basic web scraping if that is your aim. The following works for Python 2.x. #This one module that gives you the needed methods to read the html from a webpage import urllib #set a variable to the needed website mypath = "http://some_website.com" #read all the html data from the page into a variable and then parse through it looking for urls mylines = urllib.urlopen(mypath).readlines() for item in mylines: if "http://" in item: ...do something with the url that was found in the page html... ...etc... --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From knacktus at googlemail.com Sun Feb 27 07:35:46 2011 From: knacktus at googlemail.com (Knacktus) Date: Sun, 27 Feb 2011 07:35:46 +0100 Subject: [Tutor] Object, methods, class In-Reply-To: <4D698D6E.3020006@pearwood.info> References: <4D698D6E.3020006@pearwood.info> Message-ID: <4D69F0C2.5080702@googlemail.com> Once again a very insightfull answer. Much appreciated! Same to you, Alan. I paricularly like the "even longer answer". It remindes us of how lucky we are using Python and brings me light in dark times when I wish I had better code completion in my IDE for my own spaghetti-code ;-)) From vineethrakesh at gmail.com Sun Feb 27 08:46:32 2011 From: vineethrakesh at gmail.com (vineeth) Date: Sun, 27 Feb 2011 02:46:32 -0500 Subject: [Tutor] python module to search a website In-Reply-To: References: <4D69C0D3.5050801@gmail.com> Message-ID: <4D6A0158.3090409@gmail.com> Hi Bill, Thanks for the reply, I know how the urllib module works I am not looking for scraping. I am looking to obtain the html page that my query is going to return. Just like when you type in a site like Amazon you get a bunch of product listing the module has to search the website and return the html link. I can ofcourse scrap the information from that link. Thanks Vin On 02/27/2011 12:04 AM, Bill Allen wrote: > n Sat, Feb 26, 2011 at 21:11, vineeth > wrote: > > Hello all, > > I am looking forward for a python module to search a website and > extract the url. > > For example I found a module for Amazon with the name > "amazonproduct", the api does the job of extracting the data based > on the query it even parses the url data. I am looking some more > similar query search python module for other websites like Amazon. > > Any help is appreciated. > > Thank You > Vin > > I am not sure what url you are trying to extract, or from where, but I > can give you an example of basic web scraping if that is your aim. > > The following works for Python 2.x. > > #This one module that gives you the needed methods to read the html > from a webpage > import urllib > > #set a variable to the needed website > mypath = "http://some_website.com" > > #read all the html data from the page into a variable and then parse > through it looking for urls > mylines = urllib.urlopen(mypath).readlines() > for item in mylines: > if "http://" in item: > ...do something with the url that was found in the page html... > ...etc... > > > --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From ewedub at u.washington.edu Sun Feb 27 05:45:16 2011 From: ewedub at u.washington.edu (Ezra Kahn) Date: Sat, 26 Feb 2011 20:45:16 -0800 Subject: [Tutor] numpy import failure Message-ID: <4D69D6DC.5040809@u.washington.edu> I am a total newb, learning to ween myself off of Matlab. I am working off of EPD6.1, and I cannot get numpy to import. Python keeps sending me back this: Traceback (most recent call last): File "", line 1, in import numpy ImportError: No module named numpy How do I trouble shoot this? Thanks Ezra From alan.gauld at btinternet.com Sun Feb 27 10:07:51 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Feb 2011 09:07:51 -0000 Subject: [Tutor] python module to search a website References: <4D69C0D3.5050801@gmail.com> <4D6A0158.3090409@gmail.com> Message-ID: "vineeth" wrote > looking for scraping. I am looking to obtain the html page that my > query > is going to return. I'm still notcompletely sure what you mean. What "query" are you talking about? The http GET request? Or a query transaction on the remote site? > Just like when you type in a site like Amazon you > get a bunch of product listing When I visit Amazon I get a home page which has a bunch of products on it. Those prodiucts are provisded by Amazon's web application and I have no control over it. If I type a string into the search box Amazons app goes off to search their database and returns a bunch of links. Again I ghave no control over which links it returns, that is done by Amazons application logic. > the module has to search the website and > return the html link. It is impossible for any Python module to search a remote website, that can only be done by code on that website server. The best a Python module could do would be to initiate the search by posting the appropriate search string. But that uis just standard html parsing and urllib. If I understand what you are asking for then I think it is impossible. And I suspect you are a bit confused about how web sites work. As a user of a web sitre you are reliant on the functions provided by the server. If the web site is purely static, like my tutorial for example, you could do a search if you knew the file structure and had access to the folders where the html is stored, but when the pages are created dynamically, like Amazon, Ebay etc then it is impossible to search it. You would need access to their database. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Feb 27 10:10:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Feb 2011 09:10:55 -0000 Subject: [Tutor] numpy import failure References: <4D69D6DC.5040809@u.washington.edu> Message-ID: "Ezra Kahn" wrote >I am a total newb, learning to ween myself off of Matlab. I am >working off of EPD6.1, and I cannot get numpy to import. Python >keeps sending me back this: > ImportError: No module named numpy Lets start at the beginning. What OS are you using? What Python version? What numpy version? And are you sure you have installed numpy correctly? Can you see the numpy installation on your PC? Where is it located? Is that location in your sys.path value? Lets start with those.. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Feb 27 10:24:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 27 Feb 2011 20:24:58 +1100 Subject: [Tutor] numpy import failure In-Reply-To: <4D69D6DC.5040809@u.washington.edu> References: <4D69D6DC.5040809@u.washington.edu> Message-ID: <4D6A186A.9000407@pearwood.info> Ezra Kahn wrote: > I am a total newb, learning to ween myself off of Matlab. I am working > off of EPD6.1, and I cannot get numpy to import. Python keeps sending > me back this: > > Traceback (most recent call last): > File "", line 1, in > import numpy > ImportError: No module named numpy What's EPD6.1? Googling finds "Enthought Python Distribution", is that what you're using? If so, this is not a Python problem but specifically an issue with Enthought's build. I suggest you ask on their help forums. -- Steven From davea at ieee.org Sun Feb 27 14:07:39 2011 From: davea at ieee.org (Dave Angel) Date: Sun, 27 Feb 2011 08:07:39 -0500 Subject: [Tutor] Running Existing Python In-Reply-To: <4F8FF1D0-B735-43EA-BCE5-549B22571795@gmail.com> References: <8C5B4FE0-25DC-4D79-AC0C-9D1E73799ACF@gmail.com> <4D68DAA4.4000308@ieee.org> <4D697913.8050400@ieee.org> <5327EB12-3980-4363-94CD-1AADEAA6917A@gmail.com> <4D69D859.3020609@ieee.org> <4F8FF1D0-B735-43EA-BCE5-549B22571795@gmail.com> Message-ID: <4D6A4C9B.80904@ieee.org> On 02/27/2011 02:50 AM, Justin Bonnell wrote: > > On Feb 26, 2011, at 10:51 PM, Dave Angel wrote: > >> On 02/26/2011 06:03 PM, Justin Bonnell wrote: >>> >>> On Feb 26, 2011, at 4:05 PM, Dave Angel wrote: >>> >>>> >> >>>> >>>> As for cd not working, someone else has pointed out that in the shell, you need to escape certain characters, the space being one. I try to avoid ever having spaces in directory or file names. >>> >>> --I will remember to escape spaces in the future. Are there other characters that would need to be escaped? >>> Part of the problem I was having was that hello.py wasn't a script that I wrote, it was placed on my computer when I downloaded Python and IDLE so I was just trying to figure out how to run it from the Terminal. Thanks for your help. >>> >>>> >> >> Alan's advice was, as usual, spot on. But to explicitly answer your question, it depends on your shell. I don't know MacOS explicitly, but this should be close: >> >> The backslash character itself >> quotation marks >> ampersand >> pipe symbol (|) >> Greater-than> >> any whitespace (space, newline, for example) > > --Okay. I can most likely google this or find it when I need it, but I will try to keep my file names simpler so I can avoid it. > >> >> DaveA > Sorry, but I forgot some others which can mean sonmething special: asterisk question-mark less-than back quote (I already implied single and double quote marks above) And if a file name begins with a period, or a dash, it needs some special treatment. And maybe a tilda as well. These are restrictions and issues with the shell (eg. bash, or csh) you use, not with the OS specifically, and most Unix-like systems offer more than one shell. But they are more complex than a simple list can portray. For example, enclosing a name in quotation marks avoids the problem with embedded space, or greater-than and less-than, but then if the same kind of quotation marks appears in the name, it must be escaped. Windows has its own list of restrictions and quirks, so if the filename is shared across systems, you might need to honor those as well. Finally, characters above 0x80 can be problematic, again particularly if they're shared between systems. HTH, DaveA From wallenpb at gmail.com Sun Feb 27 15:52:08 2011 From: wallenpb at gmail.com (Bill Allen) Date: Sun, 27 Feb 2011 08:52:08 -0600 Subject: [Tutor] numpy import failure In-Reply-To: <4D69D6DC.5040809@u.washington.edu> References: <4D69D6DC.5040809@u.washington.edu> Message-ID: On Sat, Feb 26, 2011 at 22:45, Ezra Kahn wrote: > I am a total newb, learning to ween myself off of Matlab. I am working off > of EPD6.1, and I cannot get numpy to import. Python keeps sending me back > this: > > Traceback (most recent call last): > File "", line 1, in > import numpy > ImportError: No module named numpy > > Ezra, You did not mention that you installed the numpy package. Numpy is not included in the standard distribution of Python and may not be in other distributions. You likely need to install the numpy package first. However, how and which numpy package to install depends on the answers to the questions that Alan posed. --Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From fallcolors02 at gmail.com Sun Feb 27 20:27:28 2011 From: fallcolors02 at gmail.com (fall colors) Date: Sun, 27 Feb 2011 11:27:28 -0800 Subject: [Tutor] Converting .pyd to .so Message-ID: Hello, I was wondering if it would be possible to convert a .pyd file that works on Windows into a .so file that works on Linux? I gather that it might not be possible to convert the .pyd file if the underlying DLL file was built with Windows API calls (Swig was used to wrap up the DLL into a pyd file). Is there a wrapper or something that can interface to the .pyd to make it Linux compatible? Any ideas? Thanks, Iyer -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Sun Feb 27 20:54:09 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 27 Feb 2011 20:54:09 +0100 Subject: [Tutor] Converting .pyd to .so In-Reply-To: References: Message-ID: fall colors, 27.02.2011 20:27: > I was wondering if it would be possible to convert a .pyd file that works on > Windows into a .so file that works on Linux? > > I gather that it might not be possible to convert the .pyd file if the > underlying DLL file was built with Windows API calls (Swig was used to wrap > up the DLL into a pyd file). Is there a wrapper or something that can > interface to the .pyd to make it Linux compatible? Well, there's Wine, a free implementation of Windows for Unix systems. You can either try to load the DLL using Wine and ctypes (I suspect that's the hard way), or just run the Windows Python distribution through Wine and load the wrapper .pyd into that. I assume the DLL is only available in binary form? Stefan From modulok at gmail.com Sun Feb 27 22:34:40 2011 From: modulok at gmail.com (Modulok) Date: Sun, 27 Feb 2011 14:34:40 -0700 Subject: [Tutor] Generator expressions... Message-ID: List, I was messing around with generator expressions. I tried to make a script that would read a few bytes from '/dev/urandom' for eternity. It then did something pointless like computing checksums and printing them out. Unfortunately, the script only runs a few seconds and then terminates. I'm not sure why. I tried running it on /dev/zero as well with the same result; The process terminates, albeit normally. (Exit status 0. It's not being killed by the kernel or anything.) I was expecting it to run forever. Below is my code: ## Begin code #!/usr/bin/env python # This script will only work on UNIX flavors with a /dev/urandom # # It reads from /dev/urandom for eternity, or until you press 'ctrl+c' to # interrupt it. It computes the hashes forever. # The point being illustrated is that its memory usage is about constant, # despite an infinitely large file being read. import hashlib fd = open('/dev/urandom', 'rb') gen = (hashlib.sha256(i).hexdigest() for i in fd.read(4096)) try: for i in gen: print i #<-- This loop should never end... but does. Why? except KeyboardInterrupt: gen.close() fd.close() print "\nBye!" ## End code I've got to be missing something obvious. -Modulok- From hugo.yoshi at gmail.com Sun Feb 27 22:45:54 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 27 Feb 2011 22:45:54 +0100 Subject: [Tutor] Generator expressions... In-Reply-To: References: Message-ID: On Sun, Feb 27, 2011 at 10:34 PM, Modulok wrote: > > import hashlib > > fd = open('/dev/urandom', 'rb') > gen = (hashlib.sha256(i).hexdigest() for i in fd.read(4096)) > > try: > ? ?for i in gen: > ? ? ? ?print i ? ? #<-- This loop should never end... but does. Why? > > except KeyboardInterrupt: > ? ?gen.close() > ? ?fd.close() > ? ?print "\nBye!" > Check out the generator expression. What are you iterating over? How long is the string returned by the read? Obviously, it isn't of infinite length. Then why are you expecting the generator expression to run forever? Remember that a generator expression isn't like a function. You can't call it multiple times. You iterate over it once, then it's done, and you'll have to create a new one. HTH, Hugo From kb1pkl at aim.com Sun Feb 27 22:41:27 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 27 Feb 2011 16:41:27 -0500 Subject: [Tutor] Generator expressions... In-Reply-To: References: Message-ID: <4D6AC507.5000508@aim.com> On 02/27/2011 04:34 PM, Modulok wrote: > > import hashlib > > fd = open('/dev/urandom', 'rb') > gen = (hashlib.sha256(i).hexdigest() for i in fd.read(4096)) > I think the problem is that you're only reading 4096 bits (bytes? No idea), and iterating through that. I could be wrong. -- Corey Richardson From modulok at gmail.com Sun Feb 27 23:23:28 2011 From: modulok at gmail.com (Modulok) Date: Sun, 27 Feb 2011 15:23:28 -0700 Subject: [Tutor] Generator expressions... In-Reply-To: References: Message-ID: >> import hashlib >> >> fd = open('/dev/urandom', 'rb') >> gen = (hashlib.sha256(i).hexdigest() for i in fd.read(4096)) >> >> try: >> for i in gen: >> print i #<-- This loop should never end... but does. Why? >> >> except KeyboardInterrupt: >> gen.close() >> fd.close() >> print "\nBye!" >> > Check out the generator expression. What are you iterating over? How > long is the string returned by the read? I knew it was subtle. I was trying to use 'read(4096)' like open()'s buffersize parameter. (Which it's obviously isn't.) Thanks! -Modulok- From ewedub at u.washington.edu Sun Feb 27 17:19:04 2011 From: ewedub at u.washington.edu (Ezra Kahn) Date: Sun, 27 Feb 2011 08:19:04 -0800 Subject: [Tutor] Tutor Digest, Vol 84, Issue 110 In-Reply-To: References: Message-ID: <4D6A7978.2050404@u.washington.edu> > Ezra Kahn wrote: >> > I am a total newb, learning to ween myself off of Matlab. I am working >> > off of EPD6.1, and I cannot get numpy to import. Python keeps sending >> > me back this: >> > >> > Traceback (most recent call last): >> > File "", line 1, in >> > import numpy >> > ImportError: No module named numpy > What's EPD6.1? Googling finds "Enthought Python Distribution", is that > what you're using? > > If so, this is not a Python problem but specifically an issue with > Enthought's build. I suggest you ask on their help forums. > > > -- Steven Yes, all of those things are true. I am using Enthought Python Distribution which installs a suite of libraries all bundled together. Thanks for your replies, and the direction towards appropriate places for help. Ezra From fallcolors02 at gmail.com Mon Feb 28 03:25:19 2011 From: fallcolors02 at gmail.com (fall colors) Date: Sun, 27 Feb 2011 18:25:19 -0800 Subject: [Tutor] Converting .pyd to .so In-Reply-To: References: Message-ID: > Well, there's Wine, a free implementation of Windows for Unix systems. You > can either try to load the DLL using Wine and ctypes (I suspect that's the > hard way), or just run the Windows Python distribution through Wine and load > the wrapper .pyd into that. I assume the DLL is only available in binary form? > > > Wine is a good suggestion, but it takes up 3.53 MB. Is there a lighter alternative? The DLL is available in both source and binary form. -Iyer -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Mon Feb 28 03:58:46 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Sun, 27 Feb 2011 18:58:46 -0800 Subject: [Tutor] numpy import failure In-Reply-To: <4D69D6DC.5040809@u.washington.edu> References: <4D69D6DC.5040809@u.washington.edu> Message-ID: <75198436-F849-4994-8D48-1726C2EE7A56@gmail.com> Hi Ezra, Are you using Mac OSX or LINUX or ... If you have a preexisting python installation, it may be that when you launch python, it loads the older version, and not the new EPD version. When you launch python, what do you see? For example, on my Mac OSX, launched from Terminal, I get % python Enthought Python Distribution -- http://www.enthought.com Version: 6.2-2 (32-bit) Python 2.6.5 |EPD 6.2-2 (32-bit)| (r265:79063, May 28 2010, 15:13:03) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> whereas, if I use an older version, I get % python Python 2.6.6 (r266:84374, Aug 31 2010, 11:00:51) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> You need to get the equivalent of the first option. If you are definitely launching the Enthought python (from your new installation) and getting this error, then there is a problem with the package build on your machine. Andre On Feb 26, 2011, at 8:45 PM, Ezra Kahn wrote: > I am a total newb, learning to ween myself off of Matlab. I am working off of EPD6.1, and I cannot get numpy to import. Python keeps sending me back this: > > Traceback (most recent call last): > File "", line 1, in > import numpy > ImportError: No module named numpy > > How do I trouble shoot this? > > Thanks > > Ezra > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From jwbonnell5 at gmail.com Mon Feb 28 06:36:43 2011 From: jwbonnell5 at gmail.com (Justin Bonnell) Date: Sun, 27 Feb 2011 21:36:43 -0800 Subject: [Tutor] textbook question Message-ID: <972D5ACC-28CC-4FBA-9EC7-88C851A55C64@gmail.com> In trying to learn Python, I'm reading through How to Think Like a Computer Scientist. I'm just on the third chapter but I'm getting stuck on this question: Fill in the body of the function definition for cat_n_times so that it will print the string, s, n times: def cat_n_times(s, n): Save this function in a script named import_test.py. Now at a unix prompt, make sure you are in the same directory where the import_test.py is located ( ls should show import_test.py). Start a Python shell and try the following: >>> from import_test import * >>> cat_n_times('Spam', 7) SpamSpamSpamSpamSpamSpamSpam If all is well, your session should work the same as this one. Experiment with other calls to cat_n_times until you feel comfortable with how it works. I'm thinking it should be pretty easy but, again, I'm a beginner. I copied the whole question but basically I just need some help with what the script should look like, that'd be great. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigenbakuda at yahoo.com Mon Feb 28 07:34:38 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Sun, 27 Feb 2011 22:34:38 -0800 (PST) Subject: [Tutor] textbook question In-Reply-To: <972D5ACC-28CC-4FBA-9EC7-88C851A55C64@gmail.com> References: <972D5ACC-28CC-4FBA-9EC7-88C851A55C64@gmail.com> Message-ID: <816727.55833.qm@web130201.mail.mud.yahoo.com> Hi, Justin, how are you? Most of the nice people here like to see that you try before you ask for help. So next time post some code that you have tried (and failed on) so they can see WHERE you are going wrong or WHAT is throwing you off. I'm a beginner too, also I am using How to Think Like a Computer Scientist. So I really am similar to you. But to give you a bit of help on your problem. Strings can actually have some basic math done on them (like addition and multiplication). for example a = "Resident" b = " Evil" # you can perform addition on these two strings to join one big string. #so... a + b = "Resident Evil" #Like wise, multiplication can be done on a string (string times a number) to achieve a similar effect. c = "Ha " c * 3 = "Ha Ha Ha" So using my example can you think of a way to set up your function to augment strings to produce the effect that you desire? Give it a shot and if you get stuck post here again. ---- What is it about you... that intrigues me so? ________________________________ From: Justin Bonnell To: tutor at python.org Sent: Mon, February 28, 2011 12:36:43 AM Subject: [Tutor] textbook question In trying to learn Python, I'm reading through How to Think Like a Computer Scientist. I'm just on the third chapter but I'm getting stuck on this question: Fill in the body of the function definition for cat_n_times so that it will print the string, s, n times: def cat_n_times(s, n): Save this function in a script named import_test.py. Now at a unix prompt, make sure you are in the same directory where the import_test.py is located ( ls should show import_test.py). Start a Python shell and try the following: >>> from import_test import * >>> cat_n_times('Spam', 7) >>>SpamSpamSpamSpamSpamSpamSpam >>> If all is well, your session should work the same as this one. Experiment with other calls to cat_n_times until you feel comfortable with how it works. I'm thinking it should be pretty easy but, again, I'm a beginner. I copied the whole question but basically I just need some help with what the script should look like, that'd be great. -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Mon Feb 28 08:19:14 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Mon, 28 Feb 2011 07:19:14 +0000 Subject: [Tutor] textbook question In-Reply-To: <816727.55833.qm@web130201.mail.mud.yahoo.com> References: <972D5ACC-28CC-4FBA-9EC7-88C851A55C64@gmail.com><816727.55833.qm@web130201.mail.mud.yahoo.com> Message-ID: <1852591501-1298877554-cardhu_decombobulator_blackberry.rim.net-411524091-@b18.c12.bise7.blackberry> Nice job, Michael. The way it is, you have done the best anyone here would do to answer that question. Justin, in addition to what Michael said, note too that functions don't have to span hundreds of lines. def Useless(): pass That's a function correctly defined but does nothing. Having this in mind and what Michael has sent earlier, give it a shot. All the best. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: michael scott Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Sun, 27 Feb 2011 22:34:38 To: Subject: Re: [Tutor] textbook question _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From stefan_ml at behnel.de Mon Feb 28 08:23:51 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 28 Feb 2011 08:23:51 +0100 Subject: [Tutor] Converting .pyd to .so In-Reply-To: References: Message-ID: fall colors, 28.02.2011 03:25: > Stefan Behnel wrote: >> Well, there's Wine, a free implementation of Windows for Unix systems. You >> can either try to load the DLL using Wine and ctypes (I suspect that's the >> hard way), or just run the Windows Python distribution through Wine and load >> the wrapper .pyd into that. >> >> I assume the DLL is only available in binary form? >> >> > Wine is a good suggestion, but it takes up 3.53 MB. Is there a lighter > alternative? So far, you didn't state whether the DLL actually uses Windows calls, but I would imagine it does, and if so, you can't use it on anything but Windows without emulating those calls, thus using Wine. > The DLL is available in both source and binary form. If it's available in source form (C? C++? What else?), you can extract the part that's interesting to you and wrap that using Cython or ctypes (with Cython being substantially faster than SWIG or ctypes). However, you didn't give us any hints about what the DLL actually does, so we can't know if you really need to go that path or if you just failed to find the obvious portable alternative. Stefan From killerpancakes at msn.com Mon Feb 28 04:02:07 2011 From: killerpancakes at msn.com (Kaden McLaws) Date: Sun, 27 Feb 2011 21:02:07 -0600 Subject: [Tutor] Timer with exe command Message-ID: I would like to set up the following using python: A timer that is activated when a user logs on to our computer, then shuts the computer down when the timer runs out (no matter what, ending all programs). First, a raw input is used, so that if you know the password, you may shut off the timer (set for 90 mins). Otherwise, it is activated. This is a timer to be used so (anonymous) can only spend 90 mins playing Modern Warfare, and not hours upon end like he does. I was also wondering about parsing. It would be effective if the last time the timer activated was recorded in a txt file, logged, so that the program can check and ensure that the last time the timer ended was at least 12 hours ago, so the computer just isnt turned right back on for another 90 mins repeatedly.Is there also a way to run the python hidden in the background so he cannot just figure out how to close it?If you aren't sure off all the details, email me back. Thanks for helping me save (anonymous) from wasting too much time on MW2! :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Mon Feb 28 10:20:15 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 28 Feb 2011 09:20:15 +0000 Subject: [Tutor] Bitwise operation Message-ID: hi, i'm confused with & and AND. for eg: >>> 1110 & 0110 64 >>> 1110 and 0110 72 i'm expecting if 1110 and with 0110 will get 0110 or 6. pls advise. thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at linux-ip.net Mon Feb 28 10:43:18 2011 From: martin at linux-ip.net (Martin A. Brown) Date: Mon, 28 Feb 2011 10:43:18 +0100 Subject: [Tutor] Bitwise operation In-Reply-To: References: Message-ID: : i'm confused with & and AND. for eg: : >>> 1110 & 0110 : 64 : >>> 1110 and 0110 : 72 : : i'm expecting if 1110 and with 0110 will get 0110 or 6. : pls advise. Above, python thinks you are representing one number in decimal notation and the other in octal. Decimal (no leading zeroes): >>> 14 & 6 6 Binary (leading with '0b'): >>> 0b1110 & 0b0110 6 Octal (leading with '0'): >>> 016 & 006 6 Hexadecimal (leading with '0x'): >>> 0xe & 0x06 6 Additionally, you will want to distinguish which operator you intend, bitwise or boolean. It seems fairly clear that you are intending the bitwise operator if you are expecting '6' to be the answer. & bitwise 'and' and boolean 'and' Read these three sections, at least, to understand the operators you are trying to use: http://docs.python.org/reference/expressions.html#unary-arithmetic-and-bitwise-operations http://docs.python.org/reference/expressions.html#boolean-operations http://docs.python.org/reference/expressions.html#summary This may also be useful: http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex Good luck, -Martin -- Martin A. Brown http://linux-ip.net/ From smokefloat at gmail.com Mon Feb 28 10:49:37 2011 From: smokefloat at gmail.com (David Hutto) Date: Mon, 28 Feb 2011 04:49:37 -0500 Subject: [Tutor] Bitwise operation In-Reply-To: References: Message-ID: On Mon, Feb 28, 2011 at 4:43 AM, Martin A. Brown wrote: > > ?: i'm confused with & and AND. for eg: > ?: >>> 1110 & 0110 > ?: 64 > ?: >>> 1110 and 0110 > ?: 72 > ?: > ?: i'm expecting if 1110 and with 0110 will get 0110 or 6. > ?: pls advise. > > Above, python thinks you are representing one number in decimal > notation and the other in octal. > > Decimal (no leading zeroes): >>>> 14 & 6 > 6 > > Binary (leading with '0b'): >>>> 0b1110 & 0b0110 > 6 > > Octal (leading with '0'): >>>> 016 & 006 > 6 > > Hexadecimal (leading with '0x'): >>>> 0xe & 0x06 > 6 > > Additionally, you will want to distinguish which operator you > intend, bitwise or boolean. ?It seems fairly clear that you are > intending the bitwise operator if you are expecting '6' to be the > answer. > > ?& ? ? ? bitwise 'and' > ?and ? ? boolean 'and' > > Read these three sections, at least, to understand the > operators you are trying to use: > > ?http://docs.python.org/reference/expressions.html#unary-arithmetic-and-bitwise-operations > ?http://docs.python.org/reference/expressions.html#boolean-operations > ?http://docs.python.org/reference/expressions.html#summary > > This may also be useful: > > ?http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex > > Good luck, And skill/memory/reference. > > -Martin > > -- > Martin A. Brown > http://linux-ip.net/ > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- According to theoretical physics, the division of spatial intervals as the universe evolves gives rise to the fact that in another timeline, your interdimensional counterpart received helpful advice from me...so be eternally pleased for them. From chris.klaitos at gmail.com Mon Feb 28 14:33:50 2011 From: chris.klaitos at gmail.com (Christopher Brookes) Date: Mon, 28 Feb 2011 14:33:50 +0100 Subject: [Tutor] Multiples python files Message-ID: Hi, first sorry for my poor english, i'm a french guy, i'm trying to make the best :( I would like to split my python script into multiples files. I want : A file which contains only class creations and methods, A file with some personals functions And a main.py which is the main script. But i'm getting some problems In class creation file, i've a init method which create a character (it works). They are created in main.py like this : herosAll = [ Character(1,"Antaa","Soldat moins fort",15,5,8), Character(2,"Klaitos","Soldat moins fort",15,5,8)] But when i want to display all information about my character with : class Character(): def DisplayAll(): print ('There is', Character.CharacterCount, 'heros') for heros in herosAll: heros.DisplayCharacterInfos() I'm getting : Traceback (most recent call last): File "main.py", line 28, in Character.DisplayAll() File "/home/christopher/class_creation.py", line 53, in DisplayAll for heros in herosAll: NameError: global name 'herosAll' is not defined I know the source of the problem. The list herosAll is declared in main.py so he can't access to it. But i'm stuck here. How can he get it ? Have I to append the list in the init method ? Thank you for ready. -- Brookes Christopher. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Mon Feb 28 14:48:38 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Mon, 28 Feb 2011 13:48:38 +0000 Subject: [Tutor] Bitwise operation In-Reply-To: References: , Message-ID: > Binary (leading with '0b'): > >>> 0b1110 & 0b0110 > 6 > > Good luck, > > -Martin > my IDLE seems to be giving me some funny error. i'm using Python 2.5 and Win XP. pls advise. >>> a=0b110010 SyntaxError: invalid syntax >>> 0b1110 & 0b0110 SyntaxError: invalid syntax >>> 0b10 SyntaxError: invalid syntax >>> thanks tcl -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Mon Feb 28 15:00:48 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Mon, 28 Feb 2011 15:00:48 +0100 Subject: [Tutor] Multiples python files In-Reply-To: References: Message-ID: Hi, you must pass the herosAll list to the DisplayAll() method like this class Character(): @classmethod def DisplayAll(herosAll): print ('There is', Character.CharacterCount, 'heros') for heros in herosAll: heros.DisplayCharacterInfos() herosAll = [ Character(1,"Antaa","Soldat moins fort",15,5,8), Character(2,"Klaitos","Soldat moins fort",15,5,8)] Character.DisplayAll(herosAll) 2011/2/28 Christopher Brookes > Hi, first sorry for my poor english, i'm a french guy, i'm trying to make > the best :( > > I would like to split my python script into multiples files. > I want : > A file which contains only class creations and methods, > A file with some personals functions > And a main.py which is the main script. > > But i'm getting some problems > In class creation file, i've a init method which create a character (it > works). > They are created in main.py like this : > > herosAll = [ > Character(1,"Antaa","Soldat moins fort",15,5,8), > Character(2,"Klaitos","Soldat moins fort",15,5,8)] > > But when i want to display all information about my character with : > > class Character(): > def DisplayAll(): > print ('There is', Character.CharacterCount, 'heros') > for heros in herosAll: > heros.DisplayCharacterInfos() > > I'm getting : > > Traceback (most recent call last): > File "main.py", line 28, in > Character.DisplayAll() > File "/home/christopher/class_creation.py", line 53, in DisplayAll > for heros in herosAll: > NameError: global name 'herosAll' is not defined > > I know the source of the problem. The list herosAll is declared in main.py > so he can't access to it. But i'm stuck here. How can he get it ? > Have I to append the list in the init method ? > > Thank you for ready. > > > > -- > Brookes Christopher. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Mon Feb 28 15:01:29 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Mon, 28 Feb 2011 15:01:29 +0100 Subject: [Tutor] Multiples python files In-Reply-To: References: Message-ID: @classmethod def DisplayAll(herosAll): is of course: @classmethod def DisplayAll(cls, herosAll): 2011/2/28 Izz ad-Din Ruhulessin > Hi, you must pass the herosAll list to the DisplayAll() method like this > > class Character(): > @classmethod > def DisplayAll(herosAll): > print ('There is', Character.CharacterCount, 'heros') > for heros in herosAll: > heros.DisplayCharacterInfos() > > herosAll = [ > Character(1,"Antaa","Soldat moins fort",15,5,8), > Character(2,"Klaitos","Soldat moins fort",15,5,8)] > > Character.DisplayAll(herosAll) > > > 2011/2/28 Christopher Brookes > >> Hi, first sorry for my poor english, i'm a french guy, i'm trying to make >> the best :( >> >> I would like to split my python script into multiples files. >> I want : >> A file which contains only class creations and methods, >> A file with some personals functions >> And a main.py which is the main script. >> >> But i'm getting some problems >> In class creation file, i've a init method which create a character (it >> works). >> They are created in main.py like this : >> >> herosAll = [ >> Character(1,"Antaa","Soldat moins fort",15,5,8), >> Character(2,"Klaitos","Soldat moins fort",15,5,8)] >> >> But when i want to display all information about my character with : >> >> class Character(): >> def DisplayAll(): >> print ('There is', Character.CharacterCount, 'heros') >> for heros in herosAll: >> heros.DisplayCharacterInfos() >> >> I'm getting : >> >> Traceback (most recent call last): >> File "main.py", line 28, in >> Character.DisplayAll() >> File "/home/christopher/class_creation.py", line 53, in DisplayAll >> for heros in herosAll: >> NameError: global name 'herosAll' is not defined >> >> I know the source of the problem. The list herosAll is declared in main.py >> so he can't access to it. But i'm stuck here. How can he get it ? >> Have I to append the list in the init method ? >> >> Thank you for ready. >> >> >> >> -- >> Brookes Christopher. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.klaitos at gmail.com Mon Feb 28 15:04:02 2011 From: chris.klaitos at gmail.com (Christopher Brookes) Date: Mon, 28 Feb 2011 15:04:02 +0100 Subject: [Tutor] Multiples python files In-Reply-To: References: Message-ID: I don't understand @classmethod def DisplayAll(cls, herosAll): What is cls ? 2011/2/28 Izz ad-Din Ruhulessin > @classmethod > def DisplayAll(herosAll): > > is of course: > > @classmethod > def DisplayAll(cls, herosAll): > > 2011/2/28 Izz ad-Din Ruhulessin > > Hi, you must pass the herosAll list to the DisplayAll() method like this >> >> class Character(): >> @classmethod >> def DisplayAll(herosAll): >> print ('There is', Character.CharacterCount, 'heros') >> for heros in herosAll: >> heros.DisplayCharacterInfos() >> >> herosAll = [ >> Character(1,"Antaa","Soldat moins fort",15,5,8), >> Character(2,"Klaitos","Soldat moins fort",15,5,8)] >> >> Character.DisplayAll(herosAll) >> >> >> 2011/2/28 Christopher Brookes >> >>> Hi, first sorry for my poor english, i'm a french guy, i'm trying to >>> make the best :( >>> >>> I would like to split my python script into multiples files. >>> I want : >>> A file which contains only class creations and methods, >>> A file with some personals functions >>> And a main.py which is the main script. >>> >>> But i'm getting some problems >>> In class creation file, i've a init method which create a character (it >>> works). >>> They are created in main.py like this : >>> >>> herosAll = [ >>> Character(1,"Antaa","Soldat moins fort",15,5,8), >>> Character(2,"Klaitos","Soldat moins fort",15,5,8)] >>> >>> But when i want to display all information about my character with : >>> >>> class Character(): >>> def DisplayAll(): >>> print ('There is', Character.CharacterCount, 'heros') >>> for heros in herosAll: >>> heros.DisplayCharacterInfos() >>> >>> I'm getting : >>> >>> Traceback (most recent call last): >>> File "main.py", line 28, in >>> Character.DisplayAll() >>> File "/home/christopher/class_creation.py", line 53, in DisplayAll >>> for heros in herosAll: >>> NameError: global name 'herosAll' is not defined >>> >>> I know the source of the problem. The list herosAll is declared in >>> main.py so he can't access to it. But i'm stuck here. How can he get it ? >>> Have I to append the list in the init method ? >>> >>> Thank you for ready. >>> >>> >>> >>> -- >>> Brookes Christopher. >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> > -- Brookes Christopher. -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Mon Feb 28 15:20:41 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Mon, 28 Feb 2011 15:20:41 +0100 Subject: [Tutor] Multiples python files In-Reply-To: References: Message-ID: You can only call methods on a class without instantiating it, if it are classmethods. http://pyref.infogami.com/classmethod 2011/2/28 Christopher Brookes > I don't understand > > @classmethod > def DisplayAll(cls, herosAll > ): > > What is cls ? > > 2011/2/28 Izz ad-Din Ruhulessin > >> @classmethod >> def DisplayAll(herosAll): >> >> is of course: >> >> @classmethod >> def DisplayAll(cls, herosAll): >> >> 2011/2/28 Izz ad-Din Ruhulessin >> >> Hi, you must pass the herosAll list to the DisplayAll() method like this >>> >>> class Character(): >>> @classmethod >>> def DisplayAll(herosAll): >>> print ('There is', Character.CharacterCount, 'heros') >>> for heros in herosAll: >>> heros.DisplayCharacterInfos() >>> >>> herosAll = [ >>> Character(1,"Antaa","Soldat moins fort",15,5,8), >>> Character(2,"Klaitos","Soldat moins fort",15,5,8)] >>> >>> Character.DisplayAll(herosAll) >>> >>> >>> 2011/2/28 Christopher Brookes >>> >>>> Hi, first sorry for my poor english, i'm a french guy, i'm trying to >>>> make the best :( >>>> >>>> I would like to split my python script into multiples files. >>>> I want : >>>> A file which contains only class creations and methods, >>>> A file with some personals functions >>>> And a main.py which is the main script. >>>> >>>> But i'm getting some problems >>>> In class creation file, i've a init method which create a character (it >>>> works). >>>> They are created in main.py like this : >>>> >>>> herosAll = [ >>>> Character(1,"Antaa","Soldat moins fort",15,5,8), >>>> Character(2,"Klaitos","Soldat moins fort",15,5,8)] >>>> >>>> But when i want to display all information about my character with : >>>> >>>> class Character(): >>>> def DisplayAll(): >>>> print ('There is', Character.CharacterCount, 'heros') >>>> for heros in herosAll: >>>> heros.DisplayCharacterInfos() >>>> >>>> I'm getting : >>>> >>>> Traceback (most recent call last): >>>> File "main.py", line 28, in >>>> Character.DisplayAll() >>>> File "/home/christopher/class_creation.py", line 53, in DisplayAll >>>> for heros in herosAll: >>>> NameError: global name 'herosAll' is not defined >>>> >>>> I know the source of the problem. The list herosAll is declared in >>>> main.py so he can't access to it. But i'm stuck here. How can he get it ? >>>> Have I to append the list in the init method ? >>>> >>>> Thank you for ready. >>>> >>>> >>>> >>>> -- >>>> Brookes Christopher. >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>> >> > > > -- > Brookes Christopher. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Feb 28 15:38:37 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 28 Feb 2011 08:38:37 -0600 Subject: [Tutor] Timer with exe command In-Reply-To: References: Message-ID: On Sun, Feb 27, 2011 at 9:02 PM, Kaden McLaws wrote: > > > I would like to set up the following using python: A timer that is > activated when a user logs on to our computer, then shuts the computer down > when the timer runs out (no matter what, ending all programs). First, a raw > input is used, so that if you know the password, you may shut off the timer > (set for 90 mins). Otherwise, it is activated. This is a timer to be used so > (anonymous) can only spend 90 mins playing Modern Warfare, and not hours > upon end like he does. > I was also wondering about parsing. It would be effective if the last time > the timer activated was recorded in a txt file, logged, so that the program > can check and ensure that the last time the timer ended was at least 12 > hours ago, so the computer just isnt turned right back on for another 90 > mins repeatedly. > Is there also a way to run the python hidden in the background so he cannot > just figure out how to close it? > If you aren't sure off all the details, email me back. Thanks for helping > me save (anonymous) from wasting too much time on MW2! :) > Well, most of this should be possible on a windows box, however it would probably make more sense to get one of the net cafe softwares - unless you're truly interested in learning. Having made my own kiosk software for some internet terminals at work, I can tell you that it's a fairly difficult process - and I was using Linux which makes a lot of these things easier to do. But if you get some of the software gaming cafes use it should have exactly what you need - and unless you make about $0.25/hr, it will probably be cheaper to spend $50-100 on one of those solutions. Also, I'm very impressed that you thought out the requirements and possible steps to accomplish your desires. So, to summarize - spending the amount of time to make such a specific software will probably not be worth your time - unless you're interested in learning - so you could get a commercial solution. However, if you /are/ interested in learning, I'll recommend the win32api which should make possible several of the things you want. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Feb 28 15:44:38 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Mar 2011 01:44:38 +1100 Subject: [Tutor] Bitwise operation In-Reply-To: References: , Message-ID: <4D6BB4D6.5020901@pearwood.info> tee chwee liong wrote: > my IDLE seems to be giving me some funny error. i'm using Python 2.5 and Win XP. pls advise. > >>>> a=0b110010 > SyntaxError: invalid syntax Base two literals were only added to Python in version 2.6. [steve at sylar ~]$ python2.6 ... >>> 0b111 7 In 2.5 and older, this is a syntax error: [steve at sylar ~]$ python2.5 ... >>> 0b111 File "", line 1 0b111 ^ SyntaxError: invalid syntax Either upgrade to 2.6, or learn to convert between binary and decimal or hexadecimal in your head: >>> 0x07 # like binary 111 7 You can still convert from binary number *strings* in Python 2.5: >>> int("111", 2) 7 -- Steven From ewedub at u.washington.edu Mon Feb 28 16:34:45 2011 From: ewedub at u.washington.edu (Ezra Kahn) Date: Mon, 28 Feb 2011 07:34:45 -0800 Subject: [Tutor] numpy import failure In-Reply-To: References: Message-ID: <4D6BC095.1070202@u.washington.edu> On 2/27/2011 9:36 PM, tutor-request at python.org wrote: > Date: Sun, 27 Feb 2011 18:58:46 -0800 > From: Andre' Walker-Loud > To: Ezra Kahn > Cc:tutor at python.org > Subject: Re: [Tutor] numpy import failure > Message-ID:<75198436-F849-4994-8D48-1726C2EE7A56 at gmail.com> > Content-Type: text/plain; charset=us-ascii > > Hi Ezra, > > Are you using Mac OSX or LINUX or ... > > If you have a preexisting python installation, it may be that when you launch python, it loads the older version, and not the new EPD version. When you launch python, what do you see? For example, on my Mac OSX, launched from Terminal, I get > > % python > Enthought Python Distribution --http://www.enthought.com > Version: 6.2-2 (32-bit) > > Python 2.6.5 |EPD 6.2-2 (32-bit)| (r265:79063, May 28 2010, 15:13:03) > [GCC 4.0.1 (Apple Inc. build 5488)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> >>> > whereas, if I use an older version, I get > > % python > Python 2.6.6 (r266:84374, Aug 31 2010, 11:00:51) > [GCC 4.0.1 (Apple Inc. build 5493)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> >>> > You need to get the equivalent of the first option. If you are definitely launching the Enthought python (from your new installation) and getting this error, then there is a problem with the package build on your machine. > > > Andre Thanks again for your responses. I am using MS Windows 7, and it turns out there was a problem with build and re-installing EPD fixed it. I appreciate the help, I am so new at this, I don't know if things aren't working because it is me, or because something else is wrong (I feel like a person who has known how to drive for years, but never bothered to look under the hood of the car). Anyway, thanks again. Ezra From buggyballs at gmail.com Mon Feb 28 18:49:37 2011 From: buggyballs at gmail.com (j ram) Date: Mon, 28 Feb 2011 09:49:37 -0800 Subject: [Tutor] Converting .pyd to .so In-Reply-To: References: Message-ID: > Wine is a good suggestion, but it takes up 3.53 MB. Is there a lighter >> alternative? >> > > So far, you didn't state whether the DLL actually uses Windows calls, but I > would imagine it does, and if so, you can't use it on anything but Windows > without emulating those calls, thus using Wine. > > Sorry for not being more specific, the DLL actually uses Windows calls. > If it's available in source form (C? C++? What else?), you can extract the > part that's interesting to you and wrap that using Cython or ctypes (with > Cython being substantially faster than SWIG or ctypes). > > The Source is C. I've heard of Cython, would Cython be a more portable alternative? > However, you didn't give us any hints about what the DLL actually does, so > we can't know if you really need to go that path or if you just failed to > find the obvious portable alternative. > > > The DLL wraps a device driver, and the library of the SWIG wrapped device driver calls is invoked from a Python app. I was trying to find how this device driver (DLL) could be used on Linux without having to re-write the whole driver code for Linux. Thanks, Iyer -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Mon Feb 28 20:02:04 2011 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Mon, 28 Feb 2011 11:02:04 -0800 Subject: [Tutor] numpy import failure In-Reply-To: <4D6BC095.1070202@u.washington.edu> References: <4D6BC095.1070202@u.washington.edu> Message-ID: >> Andre > Thanks again for your responses. I am using MS Windows 7, and it turns out there was a problem with build and re-installing EPD fixed it. I appreciate the help, I am so new at this, I don't know if things aren't working because it is me, or because something else is wrong (I feel like a person who has known how to drive for years, but never bothered to look under the hood of the car). Anyway, thanks again. welcome to the club! Andre On Feb 28, 2011, at 7:34 AM, Ezra Kahn wrote: > On 2/27/2011 9:36 PM, tutor-request at python.org wrote: >> Date: Sun, 27 Feb 2011 18:58:46 -0800 >> From: Andre' Walker-Loud >> To: Ezra Kahn >> Cc:tutor at python.org >> Subject: Re: [Tutor] numpy import failure >> Message-ID:<75198436-F849-4994-8D48-1726C2EE7A56 at gmail.com> >> Content-Type: text/plain; charset=us-ascii >> >> Hi Ezra, >> >> Are you using Mac OSX or LINUX or ... >> >> If you have a preexisting python installation, it may be that when you launch python, it loads the older version, and not the new EPD version. When you launch python, what do you see? For example, on my Mac OSX, launched from Terminal, I get >> >> % python >> Enthought Python Distribution --http://www.enthought.com >> Version: 6.2-2 (32-bit) >> >> Python 2.6.5 |EPD 6.2-2 (32-bit)| (r265:79063, May 28 2010, 15:13:03) >> [GCC 4.0.1 (Apple Inc. build 5488)] on darwin >> Type "help", "copyright", "credits" or "license" for more information. >>>>> >>> >> whereas, if I use an older version, I get >> >> % python >> Python 2.6.6 (r266:84374, Aug 31 2010, 11:00:51) >> [GCC 4.0.1 (Apple Inc. build 5493)] on darwin >> Type "help", "copyright", "credits" or "license" for more information. >>>>> >>> >> You need to get the equivalent of the first option. If you are definitely launching the Enthought python (from your new installation) and getting this error, then there is a problem with the package build on your machine. >> >> >> Andre > Thanks again for your responses. I am using MS Windows 7, and it turns out there was a problem with build and re-installing EPD fixed it. I appreciate the help, I am so new at this, I don't know if things aren't working because it is me, or because something else is wrong (I feel like a person who has known how to drive for years, but never bothered to look under the hood of the car). Anyway, thanks again. > > Ezra > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From stefan_ml at behnel.de Mon Feb 28 20:14:15 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 28 Feb 2011 20:14:15 +0100 Subject: [Tutor] Converting .pyd to .so In-Reply-To: References: Message-ID: j ram, 28.02.2011 18:49: >>> Wine is a good suggestion, but it takes up 3.53 MB. Is there a lighter >>> alternative? >> >> So far, you didn't state whether the DLL actually uses Windows calls, but I >> would imagine it does, and if so, you can't use it on anything but Windows >> without emulating those calls, thus using Wine. > > Sorry for not being more specific, the DLL actually uses Windows calls. > >> If it's available in source form (C? C++? What else?), you can extract the >> part that's interesting to you and wrap that using Cython or ctypes (with >> Cython being substantially faster than SWIG or ctypes). > > The Source is C. I've heard of Cython, would Cython be a more portable > alternative? It's likely not more portable than SWIG. >> However, you didn't give us any hints about what the DLL actually does, so >> we can't know if you really need to go that path or if you just failed to >> find the obvious portable alternative. > > The DLL wraps a device driver, and the library of the SWIG wrapped device > driver calls is invoked from a Python app. I was trying to find how this > device driver (DLL) could be used on Linux without having to re-write the > whole driver code for Linux. Again, you're not giving us enough information - what kind of device are you talking about? Generally speaking, I doubt that a Windows device driver is of any use on a non-Windows operating system. There are exceptions such as NDISWrapper http://en.wikipedia.org/wiki/NDISwrapper but they are just that: exceptions. It's hard to emulate enough of the Windows driver support layer to make use of a Windows driver. Anyway, this is no longer a Python problem, so this is getting off-topic for this list. Stefan From alan.gauld at btinternet.com Mon Feb 28 20:15:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Feb 2011 19:15:19 -0000 Subject: [Tutor] Multiples python files References: Message-ID: "Christopher Brookes" wrote >I don't understand > > @classmethod > def DisplayAll(cls, herosAll): > > What is cls ? This is one of the advanced techniques I referred to a few days ago. Basically the "best"(?) solution to your problem is to store the list of characters inside the Character class as what is known as a class variable. Then everytime you create a new Character you can add it to the list by the init method. And when a character is deleted you remove it via the del method. You can then define class methods to read/print the list, find out how many characters exist etc. This is much cleaner than keeping a separate global variable since the code for managing characters is all in one place with the classs definition. But it does introduce a bunch of new syntax features which I didn't think you were ready for yet! :-) One thing you will need to be very careful about as you go forward is namespaces. Remember that everytime you import a module you need to precede any names in that module with the module name. And names inside a class need to be preceded by the class name. And names inside objects need to be preceded by the object (variable) name. If the class is inside a module you need to use both module and class. Thus if the Character class is defined inside character.py you would have something like this in main.py: import character myObj = character.Character(....) print myObj.display() print character.Character.displayAll() etc. You can simplify it by using the "from m import v" style: from character import Character myObj = Character(....) myObj.display() Character.displayAll() etc. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Feb 28 21:29:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Feb 2011 20:29:15 -0000 Subject: [Tutor] Converting .pyd to .so References: Message-ID: "j ram" wrote > The DLL wraps a device driver, and the library of the SWIG wrapped > device > driver calls is invoked from a Python app. I was trying to find how > this > device driver (DLL) could be used on Linux without having to > re-write the > whole driver code for Linux. In general you can't use a device driver from one OS on another. A device driver exposes a set of standard APIs that the OS expects to find and use to make the device function. But the way one OS (Windows) interacts with devices is very different to the way another OS (Linux) will do it so the Windows API will be completely useless to Linux. Device drivers are amongst the least portable bits of software you can create. They can be made portable across compilers and even across dfferent OS from the same family - you can often write one device driver for Linux/BSD/MacOS(Darwin) because they are all flavours of Unix. But unless you are very lucky a Windows device driver - even if you recompiled the C code - would be completely useless on Linux. But as Stefan says, this has now moved to the stage where it has nothing to do with Python. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kb1pkl at aim.com Mon Feb 28 21:30:53 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Mon, 28 Feb 2011 15:30:53 -0500 Subject: [Tutor] Timer with exe command In-Reply-To: References: Message-ID: <4D6C05FD.5050902@aim.com> On 02/27/2011 10:02 PM, Kaden McLaws wrote: > I would like to set up the following using python: A timer that is activated when a user logs on to our computer, then shuts the computer down when the timer runs out (no matter what, ending all programs). First, a raw input is used, so that if you know the password, you may shut off the timer (set for 90 mins). Otherwise, it is activated. This is a timer to be used so (anonymous) can only spend 90 mins playing Modern Warfare, and not hours upon end like he does. I was also wondering about parsing. It would be effective if the last time the timer activated was recorded in a txt file, logged, so that the program can check and ensure that the last time the timer ended was at least 12 hours ago, so the computer just isnt turned right back on for another 90 mins repeatedly.Is there also a way to run the python hidden in the background so he cannot just figure out how to close it?If you aren't sure off all the details, email me back. Thanks for helping me save (anonymous) from w asting too much time on MW2! :) http://docs.python.org/library/time.html#time.sleep http://www.microsoft.com/windowsxp/using/helpandsupport/learnmore/ballew_commandline.mspx (See "Shut Down the System") http://docs.python.org/whatsnew/2.2.html?highlight=pyw (scroll down) http://www.tutorial5.com/content/view/157/47/ http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files Should be everything you need. -- Corey Richardson From alan.gauld at btinternet.com Mon Feb 28 21:32:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Feb 2011 20:32:37 -0000 Subject: [Tutor] numpy import failure References: <4D6BC095.1070202@u.washington.edu> Message-ID: "Ezra Kahn" wrote > appreciate the help, I am so new at this, I don't know if things > aren't working because it is me, or because something else is wrong > (I feel like a person who has known how to drive for years, but > never bothered to look under the hood of the car). Thats a good analogy and one that is true for many (most?) drivers today. If they suddenly tried to service their own vehicle they would be lost. (Nowadays, with the amount of electronics in there, even those of us who have servivced an engine are a bit lost!! :-) Its all a bit scary but eventually it starts making sense, just stick with it :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kb1pkl at aim.com Mon Feb 28 21:36:27 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Mon, 28 Feb 2011 15:36:27 -0500 Subject: [Tutor] Timer with exe command In-Reply-To: <4D6C05FD.5050902@aim.com> References: <4D6C05FD.5050902@aim.com> Message-ID: <4D6C074B.3040603@aim.com> On 02/28/2011 03:30 PM, Corey Richardson wrote: > On 02/27/2011 10:02 PM, Kaden McLaws wrote: >> I would like to set up the following using python: A timer that is activated when a user logs on to our computer, then shuts the computer down when the timer runs out (no matter what, ending all programs). First, a raw input is used, so that if you know the password, you may shut off the timer (set for 90 mins). Otherwise, it is activated. This is a timer to be used so (anonymous) can only spend 90 mins playing Modern Warfare, and not hours upon end like he does. I was also wondering about parsing. It would be effective if the last time the timer activated was recorded in a txt file, logged, so that the program can check and ensure that the last time the timer ended was at least 12 hours ago, so the computer just isnt turned right back on for another 90 mins repeatedly.Is there also a way to run the python hidden in the background so he cannot just figure out how to close it?If you aren't sure off all the details, email me back. Thanks for helping me save (anonymous) from w > asting too much time on MW2! :) > > [...] > > Should be everything you need. > Oh, and http://docs.python.org/library/subprocess.html I partially disagree with Wayne, it is certainly doable, and isn't too too hard, but it will certainly take some doing without any Python knowledge, so do take the time to learn. I suggest http://www.alan-g.me.uk/l2p/ -- Corey Richardson From robert.clement at ed.ac.uk Mon Feb 28 22:28:23 2011 From: robert.clement at ed.ac.uk (Robert Clement) Date: Mon, 28 Feb 2011 21:28:23 +0000 Subject: [Tutor] string conversion Message-ID: <4D6C1377.4040407@ed.ac.uk> Hi I have a wxpython control in which users are intended to enter control characters used to define binary string delimiters, eg. '\xBA\xBA' or '\t\r\n' . The string returned by the control is a unicode version of the string entered by the user, eg. u'\\xBA\\xBA' or u'\\t\\r\\n' . I would like to be able retrieve the original string containing the escaped control characters or hex values so that I can assign it to a variable to be used to split the binary string. Does anyone know of a way this can be achieved? Thanks Rob -- The University of Edinburgh is a charitable body, registered in Scotland, with registration number SC005336.