From breamoreboy at yahoo.co.uk Tue May 1 00:57:21 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 30 Apr 2012 23:57:21 +0100 Subject: [Tutor] Python Variable Addition In-Reply-To: References: <87191701-1335780026-cardhu_decombobulator_blackberry.rim.net-220256374-@b4.c5.bise3.blackberry> Message-ID: On 30/04/2012 19:40, Alan Gauld wrote: > On 30/04/12 19:27, Mark Lawrence wrote: > >>> print 'Addition of above two numbers are : ', z >> >> Except that you'll get two spaces after the colon :) > > OK thats true, > Try this: > > print 'Addition of above two numbers are :', z > > for one. :-) > > But if the number of spaces is critical string formatting is better > still. And better than string addition. > True indeed, but which of the three versions of string formatting that I'm aware of? -- Cheers. Mark Lawrence. From steve at pearwood.info Tue May 1 01:35:50 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 May 2012 09:35:50 +1000 Subject: [Tutor] Python Variable Addition In-Reply-To: References: <87191701-1335780026-cardhu_decombobulator_blackberry.rim.net-220256374-@b4.c5.bise3.blackberry> Message-ID: <4F9F21D6.5010208@pearwood.info> Mark Lawrence wrote: > On 30/04/2012 19:40, Alan Gauld wrote: >> But if the number of spaces is critical string formatting is better >> still. And better than string addition. >> > > True indeed, but which of the three versions of string formatting that > I'm aware of? Any of them. -- Steven From alan.gauld at btinternet.com Tue May 1 01:43:32 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 May 2012 00:43:32 +0100 Subject: [Tutor] question about listing variables defined since session started In-Reply-To: References: Message-ID: On 30/04/12 22:25, Comer Duncan wrote: > I have a newbie type question. Say I have started a python (or > ipython) session and have done some imports and have also defined some > new variables since the session started. So, I have in my current > namespace a bunch of things. Suppose I want to list just those > variable names which have been defined since the session started You could save the initial startup state then later do a delta. Saving startup state only needs doing once since it should be the same each time - unless you define local startup commands - in whioch case you will need to regenerate the startup state.. > not include the names of the objects that who and whos will return. What are who and whos? They are not defined in my version of Python... > How to do that? In matlab, this is what the who returns, No idea what Matlab does, sorry. > python I seem to always get a raft of things since I typically do > import a bunch of things. So I'm guessing you don't want any of the imported stuff? What if you define a variable in an imported module? Should that be listed or not? But basically I think you want locals() - startup() [where you define startup as described above] -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Tue May 1 01:44:22 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 01 May 2012 00:44:22 +0100 Subject: [Tutor] Python Variable Addition In-Reply-To: <4F9F21D6.5010208@pearwood.info> References: <87191701-1335780026-cardhu_decombobulator_blackberry.rim.net-220256374-@b4.c5.bise3.blackberry> <4F9F21D6.5010208@pearwood.info> Message-ID: On 01/05/2012 00:35, Steven D'Aprano wrote: > Mark Lawrence wrote: >> On 30/04/2012 19:40, Alan Gauld wrote: > >>> But if the number of spaces is critical string formatting is better >>> still. And better than string addition. >>> >> >> True indeed, but which of the three versions of string formatting that >> I'm aware of? > > Any of them. > > Alright you **** antipodean :) -- Cheers. Mark Lawrence. From steve at pearwood.info Tue May 1 01:44:59 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 May 2012 09:44:59 +1000 Subject: [Tutor] question about listing variables defined since session started In-Reply-To: References: Message-ID: <4F9F23FB.2080105@pearwood.info> Comer Duncan wrote: > Hi, > > I have a newbie type question. Say I have started a python (or > ipython) session and have done some imports and have also defined some > new variables since the session started. So, I have in my current > namespace a bunch of things. Suppose I want to list just those > variable names which have been defined since the session started but > not include the names of the objects that who and whos will return. What's "who and whos"? > How to do that? In matlab, this is what the who returns, but in > python I seem to always get a raft of things since I typically do > import a bunch of things. That depends on what you are doing. If you are using dir(), then you will get a list of all the currently existing objects in your session. There's no way to show only "names defined since the session started". Maybe iPython does something like that, but I doubt it. Taken literally, I don't think you want is possible in Python. When objects are created, they aren't timestamped with the moment of when they were created, or who created them, or anything else. So there's no way to tell the difference between "x = 1" done during system startup and "x = 1" done after system startup. But why do you care? If you explain in more detail what you are hoping to accomplish, perhaps we can think of an alternative way to do so. -- Steven From robert.sjoblom at gmail.com Tue May 1 02:04:54 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Tue, 1 May 2012 02:04:54 +0200 Subject: [Tutor] question about listing variables defined since session started In-Reply-To: <4F9F23FB.2080105@pearwood.info> References: <4F9F23FB.2080105@pearwood.info> Message-ID: > What's "who and whos"? They're matlab functions: who lists the variables currently in the workspace. whos lists the current variables and their sizes and types. It also reports the totals for sizes. -- best regards, Robert S. From steve at pearwood.info Tue May 1 02:38:48 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 May 2012 10:38:48 +1000 Subject: [Tutor] question about listing variables defined since session started In-Reply-To: References: Message-ID: <4F9F3098.50301@pearwood.info> Robert Sjoblom wrote: > On 30 April 2012 23:25, Comer Duncan wrote: >> Hi, >> >> I have a newbie type question. Say I have started a python (or >> ipython) session and have done some imports and have also defined some >> new variables since the session started. So, I have in my current >> namespace a bunch of things. Suppose I want to list just those >> variable names which have been defined since the session started but >> not include the names of the objects that who and whos will return. >> How to do that? > > Not entirely sure, but something like this might work (untested): > for name in dir(): > myvalue = eval(name) > print name, "is", type(name), "and is equal to ", myvalue Please do not use eval unless you know what you are doing, and certainly don't encourage newbies to use it without a word about the risks. (I really wish eval and exec were hidden inside a module that you had to import, to discourage people from using them unnecessarily.) My advice is: Never use eval. For experts only: hardly ever use eval. eval is slow. eval is tricky to use correctly for all but the simplest uses. eval is dangerous. In this *specific* case, using eval is probably safe. But as a matter of best practice, you should not use eval when there is a simpler and safer alternative: for name in dir(): print name, "is", vars()[name] You can replace vars() with globals() if you prefer. Possibly better still: from pprint import pprint pprint(vars()) Why is eval so dangerous? Because it executes code. The risk with eval is not using it at the interactive interpreter. If you want to destroy your own data, there are easier ways than using eval. But the risk is that you write a function that uses eval, and then some day that function gets used in your web application, and you collect text from users on the Internet who feed your application something that causes eval to execute code. Suddenly, your web server is under their control and they can do *anything*. Sound far-fetched? But it happens, and very frequently. Code injection attacks are now the *most* common security vulnerability, more common than even buffer overflows. Whenever you hear about some website being compromised, or a virus or trojan horse taking over people's desktops, there is a high probability that it is because some coder used the equivalent of "eval" incorrectly. Here is a humorous look at the issue of code injection: http://xkcd.com/327/ and a more serious discussion: http://en.wikipedia.org/wiki/Code_injection -- Steven From steve at pearwood.info Tue May 1 03:29:40 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 May 2012 11:29:40 +1000 Subject: [Tutor] Imaplib Select Fails while connecting folder(**Labelname) of gmail In-Reply-To: References: Message-ID: <4F9F3C84.7010303@pearwood.info> Anurag Maherchandani wrote: > I am using imaplib module for connecting to Gmail Imap, and i am getting > the below mentioned error. > I am using select command to connect > > Labelname is **LabelName > > > I Get this Error: > > resp, data = self._imap.select("**LabelName") > File "/usr/lib/python2.6/imaplib.py", line 642, in select > typ, dat = self._simple_command(name, mailbox) > File "/usr/lib/python2.6/imaplib.py", line 1060, in _simple_command > return self._command_complete(name, self._command(name, *args)) > File "/usr/lib/python2.6/imaplib.py", line 895, in _command_complete > raise self.error('%s command error: %s %s' % (name, typ, data)) > imaplib.error: SELECT command error: BAD ['Could not parse command'] > > whereas if the Labelname is > ** LabelName > > It successfully connects. Do you have a question? Since it successfully connects when you give the name "** LabelName", I don't understand what your problem is. Is there something that makes you think that select("**LabelName") should also work? -- Steven From emailkgnow at gmail.com Tue May 1 11:19:30 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Tue, 1 May 2012 12:19:30 +0300 Subject: [Tutor] advice on an app Message-ID: hi all, I'm trying to create an app that schedules 3000 to 5000 trainees' practical exams. All the trainees basic info (name, badge, major, etc.) is in excel and i've managed to convert it into a *HUGE *list via a csv.reader object. My question is: is this the right way to go or should i use sqlight3 instead? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue May 1 12:35:05 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 1 May 2012 06:35:05 -0400 Subject: [Tutor] advice on an app In-Reply-To: References: Message-ID: On Tue, May 1, 2012 at 5:19 AM, Khalid Al-Ghamdi wrote: > hi all, > > I'm trying to create an app that schedules 3000 to 5000 trainees' > practical?exams. > > All the trainees basic info (name, badge, major, etc.) is in excel and i've > managed to convert it into a HUGE list via a csv.reader object. > > My question is: is this the right way to go or should i use sqlight3 > instead? > > thanks > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I would first start with all my fields and understanding how they relate to each other. The student/course situation you may be describing is often used as an example in sql tutorials since it is easy to understand and lends itself to a nice discussion about joins. The size of your data set isn't really a problem. Thousands of records are a lot to look at on a printout, but not a big deal for a computer script (python) or a database endgine (sqlite3). -- Joel Goldstick From sntshkmr60 at gmail.com Tue May 1 15:55:43 2012 From: sntshkmr60 at gmail.com (Santosh Kumar) Date: Tue, 1 May 2012 19:25:43 +0530 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? Message-ID: Is there space a between "#!" and "/usr/bin/env python"? I have seen Python manual, it says <#! /usr/bin/env python> But snippet manager of many text editing programs have <#!/usr/bin/env python>. Python is a strongly typed language, which one is correct? From ramit.prasad at jpmorgan.com Tue May 1 15:59:20 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 1 May 2012 13:59:20 +0000 Subject: [Tutor] question about listing variables defined since session started In-Reply-To: <4F9F3098.50301@pearwood.info> References: <4F9F3098.50301@pearwood.info> Message-ID: <5B80DD153D7D744689F57F4FB69AF47409301250@SCACMX008.exchad.jpmchase.net> > Steven D'Aprano wrote: > Robert Sjoblom wrote: > > On 30 April 2012 23:25, Comer Duncan wrote: > >> Hi, > >> > >> I have a newbie type question. Say I have started a python (or > >> ipython) session and have done some imports and have also defined some > >> new variables since the session started. So, I have in my current > >> namespace a bunch of things. Suppose I want to list just those > >> variable names which have been defined since the session started but > >> not include the names of the objects that who and whos will return. > >> How to do that? > > > > Not entirely sure, but something like this might work (untested): > > for name in dir(): > > myvalue = eval(name) > > print name, "is", type(name), "and is equal to ", myvalue > > Please do not use eval unless you know what you are doing, and certainly > don't > encourage newbies to use it without a word about the risks. > ast.literal_eval(name) is probably safer. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From d at davea.name Tue May 1 16:12:00 2012 From: d at davea.name (Dave Angel) Date: Tue, 01 May 2012 10:12:00 -0400 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: References: Message-ID: <4F9FEF30.9070105@davea.name> On 05/01/2012 09:55 AM, Santosh Kumar wrote: > Is there space a between "#!" and "/usr/bin/env python"? > > I have seen Python manual, it says <#! /usr/bin/env python> > But snippet manager of many text editing programs have <#!/usr/bin/env > python>. Python is a strongly typed language, which one is correct? > That's a comment, so it's irrelevant to Python. That line is called a shebang line, and is used by the various Unix command shells to specify what program shall interpret this particular script. I have no idea whether your shell will ignore a leading space or not. The bash that happens to be on my system will ignore the leading space. -- DaveA From kellyadrian at hotmail.com Tue May 1 16:40:27 2012 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Tue, 1 May 2012 14:40:27 +0000 Subject: [Tutor] binding a button to an entry Message-ID: Hi all, Please can anyone tell me how i bind the activation of a button with input from an entry widget. i know i should be using classes etc. but i don't understand them fully yet.. problem here is that no matter what i enter in the entry window it displays as password incorrect. from Tkinter import * password="trial" def reveal(): """Display message based on password""" contents=s if contents=="trial": print "password correct" else: print "password wrong" #mainroot=Tk()root.title("Password entry box")root.geometry("300x100")app=Frame(root)app.grid() #labelslbl=Label(app, text="Enter your password: ")lbl.grid(row=1, column=0) #create entry widgetse = Entry(root)e.grid(row=1, column=1)s=e.get() #create a submit buttonb=Button(root, text="SUBMIT", command=reveal)b.grid(row=0, column=2) root.mainloop() thanks all,adrian -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue May 1 16:51:26 2012 From: d at davea.name (Dave Angel) Date: Tue, 01 May 2012 10:51:26 -0400 Subject: [Tutor] binding a button to an entry In-Reply-To: References: Message-ID: <4F9FF86E.3000108@davea.name> On 05/01/2012 10:40 AM, ADRIAN KELLY wrote: > Hi all, Please can anyone tell me how i bind the activation of a button with input from an entry widget. i know i should be using classes etc. but i don't understand them fully yet.. problem here is that no matter what i enter in the entry window it displays as password incorrect. > from Tkinter import * > password="trial" > def reveal(): """Display message based on password""" contents=s if contents=="trial": print "password correct" else: print "password wrong" > #mainroot=Tk()root.title("Password entry box")root.geometry("300x100")app=Frame(root)app.grid() > #labelslbl=Label(app, text="Enter your password: ")lbl.grid(row=1, column=0) > #create entry widgetse = Entry(root)e.grid(row=1, column=1)s=e.get() > #create a submit buttonb=Button(root, text="SUBMIT", command=reveal)b.grid(row=0, column=2) > > root.mainloop() > > thanks all,adrian > > Please post as text; this program is incomprehensible as viewed in Thunderbird. -- DaveA From Steve.Flynn at capita.co.uk Tue May 1 16:12:22 2012 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Tue, 1 May 2012 15:12:22 +0100 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: References: Message-ID: > I have seen Python manual, it says <#! /usr/bin/env python> > But snippet manager of many text editing programs have <#!/usr/bin/env > python>. Python is a strongly typed language, which one is correct? That's not python code - it's interpreted by the shell (on Linux/Unix) to determine what to invoke to process the file - in this case the python interpreter. Whether there's a space there or not doesn't usually matter to the shell, and python doesn't care because it's seen as a comment when the code is compiled. In short - either is fine. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From steve at pearwood.info Tue May 1 17:21:04 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 May 2012 01:21:04 +1000 Subject: [Tutor] question about listing variables defined since session started In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47409301250@SCACMX008.exchad.jpmchase.net> References: <4F9F3098.50301@pearwood.info> <5B80DD153D7D744689F57F4FB69AF47409301250@SCACMX008.exchad.jpmchase.net> Message-ID: <4F9FFF60.8010500@pearwood.info> Prasad, Ramit wrote: >> Steven D'Aprano wrote: >> Robert Sjoblom wrote: >>> On 30 April 2012 23:25, Comer Duncan wrote: >>>> Hi, >>>> >>>> I have a newbie type question. Say I have started a python (or >>>> ipython) session and have done some imports and have also defined some >>>> new variables since the session started. So, I have in my current >>>> namespace a bunch of things. Suppose I want to list just those >>>> variable names which have been defined since the session started but >>>> not include the names of the objects that who and whos will return. >>>> How to do that? >>> Not entirely sure, but something like this might work (untested): >>> for name in dir(): >>> myvalue = eval(name) >>> print name, "is", type(name), "and is equal to ", myvalue >> Please do not use eval unless you know what you are doing, and certainly >> don't >> encourage newbies to use it without a word about the risks. >> > > ast.literal_eval(name) is probably safer. Safer, but doesn't work: py> import ast py> name = 25 py> ast.literal_eval('name') Traceback (most recent call last): File "", line 1, in File "ast.py", line 87, in literal_eval return _convert(node_or_string) File "ast.py", line 86, in _convert raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: <_ast.Name object at 0xb7a9560c> literal_eval is for evaluating literals, not names. py> ast.literal_eval('[123, "ABC", None, {}]') [123, 'ABC', None, {}] It apparently can also do simply arithmetic, but that's *possibly* an implementation detail due to the keyhole optimizer in CPython's compiler. -- Steven From ramit.prasad at jpmorgan.com Tue May 1 17:42:13 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 1 May 2012 15:42:13 +0000 Subject: [Tutor] question about listing variables defined since session started In-Reply-To: <4F9FFF60.8010500@pearwood.info> References: <4F9F3098.50301@pearwood.info> <5B80DD153D7D744689F57F4FB69AF47409301250@SCACMX008.exchad.jpmchase.net> <4F9FFF60.8010500@pearwood.info> Message-ID: <5B80DD153D7D744689F57F4FB69AF4740930144F@SCACMX008.exchad.jpmchase.net> Steven D'Aprano wrote: > Prasad, Ramit wrote: > >> Steven D'Aprano wrote: > >> Robert Sjoblom wrote: > >>> On 30 April 2012 23:25, Comer Duncan wrote: > >>>> Hi, > >>>> > >>>> I have a newbie type question. Say I have started a python (or > >>>> ipython) session and have done some imports and have also defined > some > >>>> new variables since the session started. So, I have in my current > >>>> namespace a bunch of things. Suppose I want to list just those > >>>> variable names which have been defined since the session started but > >>>> not include the names of the objects that who and whos will return. > >>>> How to do that? > >>> Not entirely sure, but something like this might work (untested): > >>> for name in dir(): > >>> myvalue = eval(name) > >>> print name, "is", type(name), "and is equal to ", myvalue > >> Please do not use eval unless you know what you are doing, and > certainly > >> don't > >> encourage newbies to use it without a word about the risks. > >> > > > > ast.literal_eval(name) is probably safer. > > Safer, but doesn't work: > > > py> import ast > py> name = 25 > py> ast.literal_eval('name') > Traceback (most recent call last): > File "", line 1, in > File "ast.py", line 87, in literal_eval > return _convert(node_or_string) > File "ast.py", line 86, in _convert > raise ValueError('malformed node or string: ' + repr(node)) > ValueError: malformed node or string: <_ast.Name object at 0xb7a9560c> > > > literal_eval is for evaluating literals, not names. > > py> ast.literal_eval('[123, "ABC", None, {}]') > [123, 'ABC', None, {}] > > > It apparently can also do simply arithmetic, but that's *possibly* an > implementation detail due to the keyhole optimizer in CPython's compiler. > What about just using dir / globals / locals? global_variables = globals() for name in dir(): value = globals_variables[ name ] if name in global_variables else locals[ name ] print '{0} is {1} and is equal to {2}'.format( name, type(value), value ) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Tue May 1 17:52:04 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 1 May 2012 15:52:04 +0000 Subject: [Tutor] binding a button to an entry In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47409301472@SCACMX008.exchad.jpmchase.net> > Hi all, > Please can anyone tell me how i bind the activation of a button with input > from an entry widget. i know i should be using classes etc. but i don't > understand them fully yet.. problem here is that no matter what i enter in > the entry window it displays as password incorrect. > > from Tkinter import * > > password="trial" > > def reveal(): > """Display message based on password""" > contents=s > if contents=="trial": > print "password correct" > else: > print "password wrong" > > #main > root=Tk() > root.title("Password entry box") > root.geometry("300x100") > app=Frame(root) > app.grid() > > #labels > lbl=Label(app, text="Enter your password: ") > lbl.grid(row=1, column=0) > > #create entry widgets > e = Entry(root) > e.grid(row=1, column=1) > s=e.get() > > #create a submit button > b=Button(root, text="SUBMIT", command=reveal) > b.grid(row=0, column=2) > > > root.mainloop() That is because the value of s never changes once it gets assigned. Change the following in reveal() contents=s to : contents=e.get() You may want to read Alan Gauld's tutorial (he is contributor to this list). It covers classes and basic GUI programming. http://www.alan-g.me.uk/tutor/index.htm Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From lie.1296 at gmail.com Tue May 1 18:31:33 2012 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 2 May 2012 02:31:33 +1000 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: References: Message-ID: > and is used by the various Unix command shells to specify what program > shall interpret this particular script. To be precise, the shell does not care about the shebang line either, the shebang is interpreted by the program loader in the kernel. The shell simply execve()-ed a script containing a shebang line just like a binary executable. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chare at labr.net Tue May 1 22:59:52 2012 From: chare at labr.net (Chris Hare) Date: Tue, 1 May 2012 15:59:52 -0500 Subject: [Tutor] events and popup menus Message-ID: <2C6E567B-CEAA-4070-AEDC-8E508A988518@labr.net> I have four images in a frame. I want to pop up a menu when the user right clicks on an image, and when they choose an option from the menu, execute the action. I can create the popup menu, and bind it to the image. However, what I can't figure out is how to detect in the popup menu code which image fired the event so I can do the right thing (like display a larger version of the image, etc.) # create a menu self.popup = Menu(self.pictureWindow, tearoff=0) self.popup.add_command(label="Change Picture", command=self.selectPicture) self.popup.add_command(label="Make Primary", command=self.selectPicture) self.popup.add_command(label="Large View", command=self.selectPicture) self.picture1.bind("", self.do_popup) def do_popup(self,event): # display the popup menu try: self.popup.tk_popup(event.x_root, event.y_root, 0) finally: # make sure to release the grab (Tk 8.0a1 only) self.popup.grab_release() Thanks for the advice! Chris From ramit.prasad at jpmorgan.com Tue May 1 23:29:42 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 1 May 2012 21:29:42 +0000 Subject: [Tutor] events and popup menus In-Reply-To: <2C6E567B-CEAA-4070-AEDC-8E508A988518@labr.net> References: <2C6E567B-CEAA-4070-AEDC-8E508A988518@labr.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF4740930189E@SCACMX008.exchad.jpmchase.net> > I have four images in a frame. I want to pop up a menu when the user > right clicks on an image, and when they choose an option from the menu, > execute the action. > > I can create the popup menu, and bind it to the image. However, what I > can't figure out is how to detect in the popup menu code which image fired > the event so I can do the right thing (like display a larger version of > the image, etc.) > > # create a menu > self.popup = Menu(self.pictureWindow, tearoff=0) > self.popup.add_command(label="Change Picture", > command=self.selectPicture) > self.popup.add_command(label="Make Primary", command=self.selectPicture) > self.popup.add_command(label="Large View", command=self.selectPicture) > > self.picture1.bind("", self.do_popup) > > def do_popup(self,event): > # display the popup menu > try: > self.popup.tk_popup(event.x_root, event.y_root, 0) > > finally: > # make sure to release the grab (Tk 8.0a1 only) > self.popup.grab_release() > I would probably use a lambda to pass the picture name (where LARGE_VIEW is a module level unique string identifier). self.popup.add_command(label=LARGE_VIEW, command=lambda event: self.selectPicture( LARGE_VIEW) ) Or if you need the event in selectPicture self.popup.add_command(label=LARGE_VIEW, command=lambda event: self.selectPicture( LARGE_VIEW, event) ) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From sntshkmr60 at gmail.com Wed May 2 02:02:10 2012 From: sntshkmr60 at gmail.com (Santosh Kumar) Date: Wed, 2 May 2012 05:32:10 +0530 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: References: Message-ID: Its getting complicated now. Will it effect or not? Give me one word answer with one line description. From leamhall at gmail.com Wed May 2 02:05:50 2012 From: leamhall at gmail.com (Leam Hall) Date: Tue, 01 May 2012 20:05:50 -0400 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: References: Message-ID: <4FA07A5E.3050806@gmail.com> On 05/01/2012 08:02 PM, Santosh Kumar wrote: > Its getting complicated now. Will it effect or not? > Give me one word answer with one line description. "Experiment" -- Try it and see... From alan.gauld at btinternet.com Wed May 2 02:19:11 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 May 2012 01:19:11 +0100 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: References: Message-ID: On 02/05/12 01:02, Santosh Kumar wrote: > Its getting complicated now. Will it effect or not? > Give me one word answer with one line description. impossible. It depends what OS you are on, but you didn't say. If its Windows the line makes no difference. If it's Unix it depends on the variety, but usually no space is needed. Search shebang on wikipedia. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Wed May 2 02:22:36 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 May 2012 10:22:36 +1000 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: References: Message-ID: <4FA07E4C.4070607@pearwood.info> Santosh Kumar wrote: > Its getting complicated now. Will it effect or not? > Give me one word answer with one line description. No. Either of these are fine: #! /usr/bin/env python #!/usr/bin/env python This is not a Python trick. It will work for Ruby, or Perl, or any other language with an interpreter. -- Steven From steve at pearwood.info Wed May 2 02:27:46 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 May 2012 10:27:46 +1000 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: References: Message-ID: <4FA07F82.2080604@pearwood.info> Alan Gauld wrote: > On 02/05/12 01:02, Santosh Kumar wrote: >> Its getting complicated now. Will it effect or not? >> Give me one word answer with one line description. > > impossible. > > It depends what OS you are on, but you didn't say. > > If its Windows the line makes no difference. On Windows, the presence or absence of a space will make no difference, because it's just a comment. > If it's Unix it depends on the variety, but usually no space is needed. As far as I know, on any Unix, Linux or other POSIX system, the presence or absence of a space between the #! and the path is irrelevant. I suppose it is possible that ancient Unixes from 1970 or something might not like the space, but that would surprise me. -- Steven From alan.gauld at btinternet.com Wed May 2 02:28:15 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 May 2012 01:28:15 +0100 Subject: [Tutor] binding a button to an entry In-Reply-To: References: Message-ID: On 01/05/12 15:40, ADRIAN KELLY wrote: > Please can anyone tell me how i bind the activation of a button with > input from an entry widget. I don;t know what you mean. Do you want to make the button press when the entry widget changes? Or change the entry widget when the button presses? Or just read the entry widget content in the button event handler - which is what the code below does - kind of... > i know i should be using classes etc. but i > don't understand them fully yet.. You can write Tkinter code without classes, its just more difficult to avoid complexity... > problem here is that no matter what i > enter in the entry window it displays as password incorrect. > from Tkinter import * > > password="trial" If you must use global variables (and without classes you probably do) at least bring them all together so we don;t need to scan up/down to find them. > def reveal(): > """Display message based on password""" > contents=s > if contents=="trial": You don't need contents here, just use e.get() directly if e.get() == "trial": > print "password correct" > else: > print "password wrong" > > e = Entry(root) > e.grid(row=1, column=1) > s=e.get() You get this before starting the mainloop so any changes will not be seen. Thats why its better to do the get in the event handler. And you save another unnecessary variable too... > #create a submit button > b=Button(root, text="SUBMIT", command=reveal) > b.grid(row=0, column=2) > root.mainloop() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed May 2 02:31:08 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 May 2012 01:31:08 +0100 Subject: [Tutor] events and popup menus In-Reply-To: <2C6E567B-CEAA-4070-AEDC-8E508A988518@labr.net> References: <2C6E567B-CEAA-4070-AEDC-8E508A988518@labr.net> Message-ID: On 01/05/12 21:59, Chris Hare wrote: > ... what I can't figure out is how to detect in the popup menu code > which image fired the event > def do_popup(self,event): The event argument has various attributes. For a mouse click it should include the screen coordinates. You can use those to determine which widget was being clicked. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed May 2 03:49:29 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 May 2012 02:49:29 +0100 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: <4FA07F82.2080604@pearwood.info> References: <4FA07F82.2080604@pearwood.info> Message-ID: On 02/05/12 01:27, Steven D'Aprano wrote: >> If it's Unix it depends on the variety, but usually no space is needed. > > As far as I know, on any Unix, Linux or other POSIX system, the presence > or absence of a space between the #! and the path is irrelevant. So far as I know you are right. One thing nobody has mentioned is that the presence of a space between the # and ! will usually (always?) not work. I have been caught out by that before... ie #! /bin/sh #!/bin/sh will both work # ! /bin/sh # !/bin/sh will not. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From modulok at gmail.com Wed May 2 08:13:38 2012 From: modulok at gmail.com (Modulok) Date: Wed, 2 May 2012 00:13:38 -0600 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: References: Message-ID: On 5/1/12, Santosh Kumar wrote: > Its getting complicated now. Will it effect or not? No. It won't. Spaces between '#!' and '/foo/bar/whatever' are ignored. Long Answer: Don't worry about it. For example, on one of my Ubuntu linux boxes there's 69 rc files shipped with the OS that use the variant: '#! /bin/sh' (with space). And there's 26 that use the variant '#!/bin/sh' without a space; It really doesn't matter. (For the curious, you can find out like this):: grep --ignore-case --regex '^#!/. *' --recursive /etc/rc* | wc And this respectively:: grep --ignore-case --regex '^#!/.*' --recursive /etc/rc* | wc On my FreeBSD server all files shipped with the OS don't uses spaces. They're just '#!/bin/sh'. However, some of my own scripts do, and they work regardless. i.e. It doesn't really matter. On Windows they're ignored entirely. -Modulok- From sntshkmr60 at gmail.com Wed May 2 10:45:15 2012 From: sntshkmr60 at gmail.com (Santosh Kumar) Date: Wed, 2 May 2012 14:15:15 +0530 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: References: Message-ID: Now its enough info. Thanks all for clearing my doubt. From spawgi at gmail.com Wed May 2 10:48:34 2012 From: spawgi at gmail.com (spawgi at gmail.com) Date: Wed, 2 May 2012 14:18:34 +0530 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: References: Message-ID: I have observed that either ways, works fine. On Wed, May 2, 2012 at 2:15 PM, Santosh Kumar wrote: > Now its enough info. Thanks all for clearing my doubt. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed May 2 12:59:57 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 02 May 2012 11:59:57 +0100 Subject: [Tutor] Is there space a between "#!" and "/usr/bin/env python" ? In-Reply-To: <4FA07F82.2080604@pearwood.info> References: <4FA07F82.2080604@pearwood.info> Message-ID: On 02/05/2012 01:27, Steven D'Aprano wrote: > Alan Gauld wrote: >> If its Windows the line makes no difference. > > On Windows, the presence or absence of a space will make no difference, > because it's just a comment. > This is changed by PEP397, which also refers to an implementation. -- Cheers. Mark Lawrence. From chare at labr.net Wed May 2 13:33:12 2012 From: chare at labr.net (Chris Hare) Date: Wed, 2 May 2012 06:33:12 -0500 Subject: [Tutor] events and popup menus In-Reply-To: References: <2C6E567B-CEAA-4070-AEDC-8E508A988518@labr.net> Message-ID: Using the event coordinates to figure out which widget was clicked sounds like a good idea. So, since the user might have moved the window on the screen, how do I figure out the widget's coordinates in order to figure out which of the four widgets the mouse was over when the user clicked a button? this is the first time I am doing this so I am not even sure what I need to search for online. Thanks On May 1, 2012, at 7:31 PM, Alan Gauld wrote: > On 01/05/12 21:59, Chris Hare wrote: >> ... what I can't figure out is how to detect in the popup menu code > > which image fired the event > > >> def do_popup(self,event): > > > The event argument has various attributes. For a mouse click it should include the screen coordinates. You can use those to determine which widget was being clicked. > > HTH > > -- > Alan G > 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 chnlion79 at gmail.com Wed May 2 16:28:53 2012 From: chnlion79 at gmail.com (Lion Chen) Date: Wed, 02 May 2012 22:28:53 +0800 Subject: [Tutor] why list is not thread-safe, but deque and queue are thread-safe? Message-ID: <4FA144A5.1040906@gmail.com> Hi, All, i can not understand why list is not thread-safe, but deque and queue are thread-safe? that's all. thanks. Lion Chen From spawgi at gmail.com Wed May 2 16:44:05 2012 From: spawgi at gmail.com (spawgi at gmail.com) Date: Wed, 2 May 2012 20:14:05 +0530 Subject: [Tutor] why list is not thread-safe, but deque and queue are thread-safe? In-Reply-To: <4FA144A5.1040906@gmail.com> References: <4FA144A5.1040906@gmail.com> Message-ID: http://stackoverflow.com/questions/6319207/are-lists-thread-safe On Wed, May 2, 2012 at 7:58 PM, Lion Chen wrote: > Hi, All, > i can not understand why list is not thread-safe, but deque and queue > are thread-safe? > > that's all. thanks. > > Lion Chen > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chnlion79 at gmail.com Wed May 2 18:13:26 2012 From: chnlion79 at gmail.com (Lion Chen) Date: Thu, 03 May 2012 00:13:26 +0800 Subject: [Tutor] why list is not thread-safe, but deque and queue are thread-safe? In-Reply-To: References: <4FA144A5.1040906@gmail.com> Message-ID: <4FA15D26.1080303@gmail.com> i have read it, as the "Answer" said, seems like deque is not thread-safe either, because deque has the operator +=, and others like that. i got some material about atomoperation from google: An operation during which a processor can simultaneously read a location and write it in the same bus operation. This prevents any other processor or I/O device from writing or reading memory until the operation is complete./ Atomic/ implies indivisibility and irreducibility, so an atomic operation must be performed entirely or not performed at all. so deque is not thread-safe either. right? > http://stackoverflow.com/questions/6319207/are-lists-thread-safe > > > > On Wed, May 2, 2012 at 7:58 PM, Lion Chen > wrote: > > Hi, All, > i can not understand why list is not thread-safe, but deque and queue > are thread-safe? > > that's all. thanks. > > Lion Chen > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > http://spawgi.wordpress.com > We can do it and do it better. From alan.gauld at btinternet.com Wed May 2 18:55:41 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 May 2012 17:55:41 +0100 Subject: [Tutor] events and popup menus In-Reply-To: References: <2C6E567B-CEAA-4070-AEDC-8E508A988518@labr.net> Message-ID: On 02/05/12 12:33, Chris Hare wrote: > Using the event coordinates to figure out which widget was clicked sounds like a good idea. > So, since the user might have moved the window on the screen, Sorry I wasn't precise enough, I believe the mouse coordinates are the relative coordinates in your window. Not the full screen. So if you used the placer its whatever you placed it at. Otherwise you can query each widget for their current location/size. Or there may be an included() method that tells you if the point is included in the widgets area. I can't recall how Tkinter does it and I'm seen GUIs do it both ways... Sorry, not near a Tkinter reference right now! I think its in the "winfo" methods somewhere... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed May 2 19:02:29 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 May 2012 18:02:29 +0100 Subject: [Tutor] why list is not thread-safe, but deque and queue are thread-safe? In-Reply-To: <4FA15D26.1080303@gmail.com> References: <4FA144A5.1040906@gmail.com> <4FA15D26.1080303@gmail.com> Message-ID: On 02/05/12 17:13, Lion Chen wrote: > i have read it, as the "Answer" said, seems like deque is not > thread-safe either, because deque has the operator +=, and others like > that. I'm no expert and have never used dequeue. But I notice the documentation says: """Deques are a generalization of stacks and queues... Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.""" So only append() and pop() are listed as being thread safe. If you use any other operation I read that as being a risk. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bjorn.h.madsen at googlemail.com Wed May 2 21:56:04 2012 From: bjorn.h.madsen at googlemail.com (Bjorn Madsen) Date: Wed, 2 May 2012 20:56:04 +0100 Subject: [Tutor] is it possible to create and amend classes during run-time? Message-ID: Hi, I have been studying http://docs.python.org/tutorial/classes.html for a while, but still have two questions which I could not answer. Perhaps you could help? Does anyone know if it is possible during run-time to: a) add attributes to classes, which will unknown at program start, but "emerge" later whilst the program is running? b) add subclasses to class (also during runtime) I thank you in advance... Kind Regards, -- Bjorn -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Wed May 2 22:44:54 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 2 May 2012 16:44:54 -0400 Subject: [Tutor] is it possible to create and amend classes during run-time? In-Reply-To: References: Message-ID: On Wed, May 2, 2012 at 3:56 PM, Bjorn Madsen wrote: > Hi, > I have been studying?http://docs.python.org/tutorial/classes.html?for a > while, but still have two questions which I could not answer. Perhaps you > could help? > > Does anyone know if it is possible during run-time to: > a) add attributes to classes, which will unknown at program start, but > "emerge" later whilst the program is running? > b) add subclasses to class (also during runtime) As far as I understand your questions, the answer to both of those is yes. It might help for you to provide an example of exactly what you mean, though. Here's a quick examples (python 2.6, from the interactive interpreter) of adding an attribute to an existing class: >>> class Foo(object): pass >>> my_foo = Foo() >>> Foo.bar = True >>> print my_foo.bar True >>> I defined the class Foo, created an instance of that class, then later added an attribute to the class itself. As you'd expect, that attribute is also visible on the instance. You second question is a little more difficult to understand. Classes don't know about their subclasses, so you wouldn't normally "add a subclass to a class". Perhaps if you describe what you're trying to accomplish, it would be easier to demonstrate how to do it. -- Jerry From ramit.prasad at jpmorgan.com Wed May 2 22:56:10 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 2 May 2012 20:56:10 +0000 Subject: [Tutor] is it possible to create and amend classes during run-time? In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47409303E91@SCACMX008.exchad.jpmchase.net> > > > > Does anyone know if it is possible during run-time to: > > a) add attributes to classes, which will unknown at program start, but > > "emerge" later whilst the program is running? > > b) add subclasses to class (also during runtime) > > As far as I understand your questions, the answer to both of those is > yes. It might help for you to provide an example of exactly what you > mean, though. > > Here's a quick examples (python 2.6, from the interactive interpreter) > of adding an attribute to an existing class: > > >>> class Foo(object): > pass > > >>> my_foo = Foo() > >>> Foo.bar = True > >>> print my_foo.bar > True > >>> > > I defined the class Foo, created an instance of that class, then later > added an attribute to the class itself. As you'd expect, that > attribute is also visible on the instance. > > You second question is a little more difficult to understand. Classes > don't know about their subclasses, so you wouldn't normally "add a > subclass to a class". Perhaps if you describe what you're trying to > accomplish, it would be easier to demonstrate how to do it. > Typically unless you need it to be shared across instances (like a singleton pattern) you would probably add it to the instance instead of the class. So the first answer is Yes. Like Jerry, I am not sure what you mean by adding a subclass. Rather than misinterpret I will just wait for you to clarify. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Thu May 3 01:01:27 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 03 May 2012 00:01:27 +0100 Subject: [Tutor] is it possible to create and amend classes during run-time? In-Reply-To: References: Message-ID: >> Does anyone know if it is possible during run-time to: >> a) add attributes to classes, which will unknown at program start, but >> "emerge" later whilst the program is running? Yes, but its not very useful since the rest of your code won't know how to access those attributes. There are ways around that (getattr() etc) but in general it's a bad design pattern that should be avoided. But Python is an interpreted language so anything you can do in a script file can also be done at runtime. >> b) add subclasses to class (also during runtime) I'm not sure what you mean, but I'm guessing you are asking if you can subclass an existing class. That is create a new class, and again the answer is yes. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kushal.kumaran+python at gmail.com Thu May 3 08:59:02 2012 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Thu, 3 May 2012 12:29:02 +0530 Subject: [Tutor] VirutalEnv not working on Ubuntu server 9.10 In-Reply-To: References: Message-ID: On Sun, Apr 29, 2012 at 7:34 PM, Marco Mistroni wrote: > HI all > ?i have a VPS which is running Ubuntu server 9.10 > > i have downloaded virtualenv 1.4.2 and installed it in a tmp directory > > i have created a environment for using googlemaps.. > > i am able to download googlemaps package,? but when i activate the > environment , run python? and type? import googlemaps > i receive the following error > > ImportError: no module caleld googlemaps > > > ..BUt i have just imported it using pip install. here's output of doing pip > install googlemaps > > Downloadign googlemaps-1.0.2 > ... > > Running setup.py install for googlemaps > Successfully installed googlemaps > > yet, when i type pytyon? and start to import googlemaps all i receive is an > error that the package does not exist > > what am i missing? > Did you activate the virtualenv before installing the googlemaps module? It is not clear from your email whether that was the case. Look into the site-packages directory in your virtualenv and check if googlemaps.py is present there. -- regards, kushal From __peter__ at web.de Thu May 3 12:30:13 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 May 2012 12:30:13 +0200 Subject: [Tutor] events and popup menus References: <2C6E567B-CEAA-4070-AEDC-8E508A988518@labr.net> Message-ID: Chris Hare wrote: > I have four images in a frame. I want to pop up a menu when the user > right clicks on an image, and when they choose an option from the menu, > execute the action. > > I can create the popup menu, and bind it to the image. However, what I > can't figure out is how to detect in the popup menu code which image fired > the event so I can do the right thing (like display a larger version of > the image, etc.) > > # create a menu > self.popup = Menu(self.pictureWindow, tearoff=0) > self.popup.add_command(label="Change Picture", > command=self.selectPicture) self.popup.add_command(label="Make Primary", > command=self.selectPicture) self.popup.add_command(label="Large View", > command=self.selectPicture) You should have a different callback for every menu item: self.popup.add_command(label="Change Picture", command=self.change_picture) ... self.popup.add_command(label="Large View", command=self.large_view) > self.picture1.bind("", self.do_popup) > > def do_popup(self,event): > # display the popup menu > try: > self.popup.tk_popup(event.x_root, event.y_root, 0) > > finally: > # make sure to release the grab (Tk 8.0a1 only) > self.popup.grab_release() > > Thanks for the advice! You can remember the widget from do_popup()'s event argument def do_popup(self, event): self.current_picture = event.widget ... and later refer to it in the menu callbacks def select_picture(self): picture = self.current_picture ... I got a bit distracted struggling with PIL, therefore my "self-contained demo" got rather baroque. You may still find it useful: $ cat tk_popup_demo.py import sys import Tkinter as tk import ImageTk import Image current_label = None def do_popup(event): global current_label current_label = event.widget try: popup.tk_popup(event.x_root, event.y_root, 0) finally: popup.grab_release() def rotate_picture(): image = current_label.photoimage.image.rotate(90) photoimage = ImageTk.PhotoImage(image) photoimage.image = image current_label.photoimage = current_label["image"] = photoimage def flip_picture(): print "flip picture" def load_image(filename, maxsize=(500, 500), padcolor="#f80"): image = Image.open(filename) image.thumbnail(maxsize) if image.size != maxsize: padded_image = Image.new(image.mode, maxsize, color=padcolor) maxx, maxy = maxsize x, y = image.size padded_image.paste(image, ((maxx-x)//2, (maxy-y)//2)) image = padded_image assert image.size == maxsize return image root = tk.Tk() picturefiles = sys.argv[1:4] for i, filename in enumerate(picturefiles): image = load_image(filename) photoimage = ImageTk.PhotoImage(image) photoimage.image = image label = tk.Label(root, image=photoimage) label.photoimage = photoimage label.grid(row=0, column=i) label.bind("", do_popup) popup = tk.Menu(root, tearoff=0) popup.add_command(label="Rotate", command=rotate_picture) popup.add_command(label="Flip", command=flip_picture) root.mainloop() Invoke with a few picture names (all but the first three will be ignored): $ python tk_popup_demo.py *.jpg From alkopop79 at gmail.com Thu May 3 13:14:05 2012 From: alkopop79 at gmail.com (=?UTF-8?Q?Gergely_L=C5=91rincz?=) Date: Thu, 3 May 2012 12:14:05 +0100 Subject: [Tutor] python installation problem Message-ID: Dear folks, I've been struggling to set up python on snow leopard, mac os x. Stupidly I downloaded and installed python 3.2 and since then the 'python' command in the terminal yields 'no command found'. In addition when opening the terminal I get this error message on the top of the window: http://pastebin.com/QS3gpkjK For some reason the installation littered my Android SDK folder with main.py and other kind of python files. Don't ask me why, it's beyond me. I removed the offending files manually and deleted the python 3.2.2 folder form /Library/Frameworks/python.framework/versions folder. After rebooting the terminal still complains about those files. I wonder how can I fix it? I would love to learn to use python! Your help would be appreciated! -- Greg Lorincz www.greglorincz.com +447824817676 -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Thu May 3 15:57:04 2012 From: spawgi at gmail.com (spawgi at gmail.com) Date: Thu, 3 May 2012 19:27:04 +0530 Subject: [Tutor] How to exit this loop in the interpreter Message-ID: Hello all, I have encountered the following scenario. Here is the code - on IDLE on Windows XP. *>>> while True: try: number = raw_input("enter number - ") print number * number except ValueError: print "invalid number" except: print "unspecified exception" else: print "other conditions" enter number - 3 unspecified exception * What I noticed is that no matter, what input I give, I cannot exit this loop. I have tried control-C, control-D etc. all the keys. So how can I exit from this loop? Thanks and Regards, Sumod -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Thu May 3 16:18:11 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 3 May 2012 10:18:11 -0400 Subject: [Tutor] How to exit this loop in the interpreter In-Reply-To: References: Message-ID: On Thu, May 3, 2012 at 9:57 AM, wrote: > Hello all, > > I have encountered the following scenario. > Here is the code - on IDLE on Windows XP. > >>>> while True: > ??? try: > ??? ??? number = raw_input("enter number - ") > ??? ??? print number * number > ??? except ValueError: > ??? ??? print "invalid number" > ??? except: > ??? ??? print "unspecified exception" > ??? else: > ??? ??? print "other conditions" > > > enter number - 3 > unspecified exception > > What I noticed is that no matter, what input I give, I cannot exit this > loop. I have tried control-C, control-D etc. all the keys. So how can I exit > from this loop? You can't, because you've painted yourself into a corner. The bare "except:" line will catch any exception at all. Including the KeyboardInterrupt exception that is raised when you hit control-c. If you must catch unknown exceptions, but still want to allow the KeyboardInterrupt exception from pressing control-c to exit your program, then use "except Exception:" instead of a bare "except:" statement. Since KeyboardInterrupt (and SystemExit) are not subclasses of Exception, they won't be caught. KeyboardInterrupt and SystemExit are subclasses of a class called BaseException, instead of Exception, for this exact purpose. See more about python's exception hierarchy here: http://docs.python.org/library/exceptions.html -- Jerry From simonyan at fedoraproject.org Thu May 3 16:22:10 2012 From: simonyan at fedoraproject.org (Simon Yan) Date: Thu, 3 May 2012 22:22:10 +0800 Subject: [Tutor] How to exit this loop in the interpreter In-Reply-To: References: Message-ID: On Thu, May 3, 2012 at 9:57 PM, wrote: > Hello all, > > I have encountered the following scenario. > Here is the code - on IDLE on Windows XP. > > *>>> while True: > try: > number = raw_input("enter number - ") > print number * number > except ValueError: > print "invalid number" > except: > print "unspecified exception" > else: > print "other conditions" > > > enter number - 3 > unspecified exception > * > What I noticed is that no matter, what input I give, I cannot exit this > loop. I have tried control-C, control-D etc. all the keys. So how can I > exit from this loop? > If you simply want to stop after an exception was caught, you can insert "break" after each print line. Like below: >>> while True: try: number = raw_input("enter number - ") print number * number except ValueError: print "invalid number" break except: print "unspecified exception" break else: print "other conditions" break > > Thanks and Regards, > Sumod > > -- > http://spawgi.wordpress.com > We can do it and do it better. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Regards, YeeYaa (Simon Yan) http://simonyan.fedorapeople.org/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alkopop79 at gmail.com Thu May 3 17:52:31 2012 From: alkopop79 at gmail.com (=?UTF-8?Q?Gergely_L=C5=91rincz?=) Date: Thu, 3 May 2012 16:52:31 +0100 Subject: [Tutor] How to exit this loop in the interpreter In-Reply-To: References: Message-ID: Dear folks, I've been struggling to set up python on snow leopard, mac os x. Stupidly I downloaded and installed python 3.2 and since then the 'python' command in the terminal yields 'no command found'. In addition when opening the terminal I get this error message on the top of the window: http://pastebin.com/QS3gpkjK For some reason the installation littered my Android SDK folder with main.py and other kind of python files. Don't ask me why, it's beyond me. I removed the offending files manually and deleted the python 3.2.2 folder form /Library/Frameworks/python.framework/versions folder. After rebooting the terminal still complains about those files. I wonder how can I fix it? I would love to learn to use python! Your help would be appreciated! On 3 May 2012 15:22, Simon Yan wrote: > > > On Thu, May 3, 2012 at 9:57 PM, wrote: > >> Hello all, >> >> I have encountered the following scenario. >> Here is the code - on IDLE on Windows XP. >> >> *>>> while True: >> try: >> number = raw_input("enter number - ") >> print number * number >> except ValueError: >> print "invalid number" >> except: >> print "unspecified exception" >> else: >> print "other conditions" >> >> >> enter number - 3 >> unspecified exception >> * >> What I noticed is that no matter, what input I give, I cannot exit this >> loop. I have tried control-C, control-D etc. all the keys. So how can I >> exit from this loop? >> > > If you simply want to stop after an exception was caught, you can insert > "break" after each print line. Like below: > >>> while True: > try: > number = raw_input("enter number - ") > print number * number > except ValueError: > print "invalid number" > break > except: > print "unspecified exception" > break > else: > print "other conditions" > break > > >> >> Thanks and Regards, >> Sumod >> >> -- >> http://spawgi.wordpress.com >> We can do it and do it better. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Regards, > YeeYaa (Simon Yan) > > http://simonyan.fedorapeople.org/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Greg Lorincz www.greglorincz.com +447824817676 -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Thu May 3 18:30:54 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 03 May 2012 17:30:54 +0100 Subject: [Tutor] How to exit this loop in the interpreter In-Reply-To: References: Message-ID: On 03/05/2012 16:52, Gergely L?rincz wrote: > Dear folks, > > I've been struggling to set up python on snow leopard, mac os x. Stupidly I > downloaded and installed python 3.2 and since then the 'python' command in > the terminal yields 'no command found'. In addition when opening the > terminal I get this error message on the top of the window: > http://pastebin.com/QS3gpkjK > > For some reason the installation littered my Android SDK folder with > main.py and other kind of python files. Don't ask me why, it's beyond me. I > removed the offending files manually and deleted the python 3.2.2 folder > form /Library/Frameworks/python.framework/versions folder. After rebooting > the terminal still complains about those files. I wonder how can I fix it? > I would love to learn to use python! Your help would be appreciated! > > On 3 May 2012 15:22, Simon Yan wrote: > >> >> >> On Thu, May 3, 2012 at 9:57 PM, wrote: >> >>> Hello all, >>> >>> I have encountered the following scenario. >>> Here is the code - on IDLE on Windows XP. >>> >>> *>>> while True: >>> try: >>> number = raw_input("enter number - ") >>> print number * number >>> except ValueError: >>> print "invalid number" >>> except: >>> print "unspecified exception" >>> else: >>> print "other conditions" >>> >>> >>> enter number - 3 >>> unspecified exception >>> * >>> What I noticed is that no matter, what input I give, I cannot exit this >>> loop. I have tried control-C, control-D etc. all the keys. So how can I >>> exit from this loop? >>> >> >> If you simply want to stop after an exception was caught, you can insert >> "break" after each print line. Like below: >> >>> while True: >> try: >> number = raw_input("enter number - ") >> print number * number >> except ValueError: >> print "invalid number" >> break >> except: >> print "unspecified exception" >> break >> else: >> print "other conditions" >> break >> >> >>> >>> Thanks and Regards, >>> Sumod >>> >>> -- >>> http://spawgi.wordpress.com >>> We can do it and do it better. >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> >> -- >> Regards, >> YeeYaa (Simon Yan) >> >> http://simonyan.fedorapeople.org/ >> >> _______________________________________________ >> 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 I say old chap, it's simply not cricket to hijack a thread, particularly when you've already asked your question some 4 hours and 38 minutes earlier. -- Cheers. Mark Lawrence. From alkopop79 at gmail.com Thu May 3 18:44:22 2012 From: alkopop79 at gmail.com (=?UTF-8?Q?Gergely_L=C5=91rincz?=) Date: Thu, 3 May 2012 17:44:22 +0100 Subject: [Tutor] How to exit this loop in the interpreter In-Reply-To: References: Message-ID: I say old bean, did not get an answer and wasn't sure if it went through. Sorry me for asking help with python in a python mailing list! On 3 May 2012 17:30, Mark Lawrence wrote: > On 03/05/2012 16:52, Gergely L?rincz wrote: > >> Dear folks, >> >> I've been struggling to set up python on snow leopard, mac os x. Stupidly >> I >> downloaded and installed python 3.2 and since then the 'python' command in >> the terminal yields 'no command found'. In addition when opening the >> terminal I get this error message on the top of the window: >> http://pastebin.com/QS3gpkjK >> >> For some reason the installation littered my Android SDK folder with >> main.py and other kind of python files. Don't ask me why, it's beyond me. >> I >> removed the offending files manually and deleted the python 3.2.2 folder >> form /Library/Frameworks/python.**framework/versions folder. After >> rebooting >> the terminal still complains about those files. I wonder how can I fix it? >> I would love to learn to use python! Your help would be appreciated! >> >> On 3 May 2012 15:22, Simon Yan wrote: >> >> >>> >>> On Thu, May 3, 2012 at 9:57 PM, wrote: >>> >>> Hello all, >>>> >>>> I have encountered the following scenario. >>>> Here is the code - on IDLE on Windows XP. >>>> >>>> *>>> while True: >>>> >>>> try: >>>> number = raw_input("enter number - ") >>>> print number * number >>>> except ValueError: >>>> print "invalid number" >>>> except: >>>> print "unspecified exception" >>>> else: >>>> print "other conditions" >>>> >>>> >>>> enter number - 3 >>>> unspecified exception >>>> * >>>> What I noticed is that no matter, what input I give, I cannot exit this >>>> loop. I have tried control-C, control-D etc. all the keys. So how can I >>>> exit from this loop? >>>> >>>> >>> If you simply want to stop after an exception was caught, you can insert >>> "break" after each print line. Like below: >>> >>> while True: >>> try: >>> number = raw_input("enter number - ") >>> print number * number >>> except ValueError: >>> print "invalid number" >>> break >>> except: >>> print "unspecified exception" >>> break >>> else: >>> print "other conditions" >>> break >>> >>> >>> >>>> Thanks and Regards, >>>> Sumod >>>> >>>> -- >>>> http://spawgi.wordpress.com >>>> We can do it and do it better. >>>> >>>> ______________________________**_________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/**mailman/listinfo/tutor >>>> >>>> >>>> >>> >>> -- >>> Regards, >>> YeeYaa (Simon Yan) >>> >>> http://simonyan.fedorapeople.**org/ >>> >>> ______________________________**_________________ >>> 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 >> > > I say old chap, it's simply not cricket to hijack a thread, particularly > when you've already asked your question some 4 hours and 38 minutes earlier. > > -- > Cheers. > > Mark Lawrence. > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Greg Lorincz www.greglorincz.com +447824817676 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alkopop79 at gmail.com Thu May 3 18:46:46 2012 From: alkopop79 at gmail.com (=?UTF-8?Q?Gergely_L=C5=91rincz?=) Date: Thu, 3 May 2012 17:46:46 +0100 Subject: [Tutor] How to exit this loop in the interpreter In-Reply-To: References: Message-ID: I'm new to python, is schooling a python-developer thing? Whether I ask for help at forums, IRC or here, someone schools me. Should I stick with Java? On 3 May 2012 17:44, Gergely L?rincz wrote: > I say old bean, did not get an answer and wasn't sure if it went through. > Sorry me for asking help with python in a python mailing list! > > > On 3 May 2012 17:30, Mark Lawrence wrote: > >> On 03/05/2012 16:52, Gergely L?rincz wrote: >> >>> Dear folks, >>> >>> I've been struggling to set up python on snow leopard, mac os x. >>> Stupidly I >>> downloaded and installed python 3.2 and since then the 'python' command >>> in >>> the terminal yields 'no command found'. In addition when opening the >>> terminal I get this error message on the top of the window: >>> http://pastebin.com/QS3gpkjK >>> >>> For some reason the installation littered my Android SDK folder with >>> main.py and other kind of python files. Don't ask me why, it's beyond >>> me. I >>> removed the offending files manually and deleted the python 3.2.2 folder >>> form /Library/Frameworks/python.**framework/versions folder. After >>> rebooting >>> the terminal still complains about those files. I wonder how can I fix >>> it? >>> I would love to learn to use python! Your help would be appreciated! >>> >>> On 3 May 2012 15:22, Simon Yan wrote: >>> >>> >>>> >>>> On Thu, May 3, 2012 at 9:57 PM, wrote: >>>> >>>> Hello all, >>>>> >>>>> I have encountered the following scenario. >>>>> Here is the code - on IDLE on Windows XP. >>>>> >>>>> *>>> while True: >>>>> >>>>> try: >>>>> number = raw_input("enter number - ") >>>>> print number * number >>>>> except ValueError: >>>>> print "invalid number" >>>>> except: >>>>> print "unspecified exception" >>>>> else: >>>>> print "other conditions" >>>>> >>>>> >>>>> enter number - 3 >>>>> unspecified exception >>>>> * >>>>> What I noticed is that no matter, what input I give, I cannot exit this >>>>> loop. I have tried control-C, control-D etc. all the keys. So how can I >>>>> exit from this loop? >>>>> >>>>> >>>> If you simply want to stop after an exception was caught, you can insert >>>> "break" after each print line. Like below: >>>> >>> while True: >>>> try: >>>> number = raw_input("enter number - ") >>>> print number * number >>>> except ValueError: >>>> print "invalid number" >>>> break >>>> except: >>>> print "unspecified exception" >>>> break >>>> else: >>>> print "other conditions" >>>> break >>>> >>>> >>>> >>>>> Thanks and Regards, >>>>> Sumod >>>>> >>>>> -- >>>>> http://spawgi.wordpress.com >>>>> We can do it and do it better. >>>>> >>>>> ______________________________**_________________ >>>>> Tutor maillist - Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/**mailman/listinfo/tutor >>>>> >>>>> >>>>> >>>> >>>> -- >>>> Regards, >>>> YeeYaa (Simon Yan) >>>> >>>> http://simonyan.fedorapeople.**org/ >>>> >>>> ______________________________**_________________ >>>> 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 >>> >> >> I say old chap, it's simply not cricket to hijack a thread, particularly >> when you've already asked your question some 4 hours and 38 minutes earlier. >> >> -- >> Cheers. >> >> Mark Lawrence. >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > > -- > Greg Lorincz > > www.greglorincz.com +447824817676 > > -- Greg Lorincz www.greglorincz.com +447824817676 -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Thu May 3 19:05:40 2012 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Thu, 3 May 2012 10:05:40 -0700 Subject: [Tutor] How to exit this loop in the interpreter In-Reply-To: References: Message-ID: <592B3331-D2E8-493C-A234-4E238FD441A2@gmail.com> Hi Greg, > I'm new to python, is schooling a python-developer thing? Whether I ask for help at forums, IRC or here, someone schools me. Should I stick with Java? No, the python mailing list is for the most part, very friendly and helpful (in my experience). Mark's message that you not hijack the thread is so that other people in the future, when trying to find similar problems to yours (or this thread) do not get confused by disjoined topics in the same thread. So instead of replying all to a random email from the group, start a new thread by posting an original email to the list. And if you don't get a reply immediately, be patient. Many of the people who may know the answer to your questions may live in a time-zone 12 hours different from yours. My interpretation of Mark's message was a jest-full way of reminding you (letting you know) appropriate behavior for the list. Further information on list behavior/rules can be found starting with the link sent at the bottom of every mail from the list http://mail.python.org/mailman/listinfo/tutor Certainly a way to discourage people from replying to your questions are - steal a thread - when asked not to hijack a thread, continue to do so anyways - "spam" the list with the same question multiple times in a short period of time Regards, Andre From alkopop79 at gmail.com Thu May 3 19:07:32 2012 From: alkopop79 at gmail.com (=?UTF-8?Q?Gergely_L=C5=91rincz?=) Date: Thu, 3 May 2012 18:07:32 +0100 Subject: [Tutor] How to exit this loop in the interpreter In-Reply-To: <592B3331-D2E8-493C-A234-4E238FD441A2@gmail.com> References: <592B3331-D2E8-493C-A234-4E238FD441A2@gmail.com> Message-ID: Thanks Andre, apologies for hijacking the thread! On 3 May 2012 18:05, Andre' Walker-Loud wrote: > Hi Greg, > > > I'm new to python, is schooling a python-developer thing? Whether I ask > for help at forums, IRC or here, someone schools me. Should I stick with > Java? > > No, the python mailing list is for the most part, very friendly and > helpful (in my experience). > > Mark's message that you not hijack the thread is so that other people in > the future, when trying to find similar problems to yours (or this thread) > do not get confused by disjoined topics in the same thread. So instead of > replying all to a random email from the group, start a new thread by > posting an original email to the list. And if you don't get a reply > immediately, be patient. Many of the people who may know the answer to > your questions may live in a time-zone 12 hours different from yours. > > My interpretation of Mark's message was a jest-full way of reminding you > (letting you know) appropriate behavior for the list. Further information > on list behavior/rules can be found starting with the link sent at the > bottom of every mail from the list > > http://mail.python.org/mailman/listinfo/tutor > > > Certainly a way to discourage people from replying to your questions are > - steal a thread > - when asked not to hijack a thread, continue to do so anyways > - "spam" the list with the same question multiple times in a short > period of time > > > Regards, > > Andre > > -- Greg Lorincz www.greglorincz.com +447824817676 -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu May 3 19:22:31 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 3 May 2012 17:22:31 +0000 Subject: [Tutor] python installation problem In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47409304FEB@SCACMX008.exchad.jpmchase.net> > I've been struggling to set up python on snow leopard, mac os x. Stupidly > I downloaded and installed python 3.2 and since then the 'python' command > in the terminal yields 'no command found'. In addition when opening the > terminal I get this error message on the top of the > window: http://pastebin.com/QS3gpkjK > > For some reason the installation littered my Android SDK folder with > main.py and other kind of python files. Don't ask me why, it's beyond me. > I removed the offending files manually and deleted the python 3.2.2 folder > form /Library/Frameworks/python.framework/versions folder. After rebooting > the terminal still complains about those files. I wonder how can I fix it? > I would love to learn to use python! Your help would be appreciated! From what I have read installing other Python versions on OS X should be done from something like MacPorts or fink. Not sure how to fix it though. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Thu May 3 19:53:05 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 03 May 2012 18:53:05 +0100 Subject: [Tutor] python installation problem In-Reply-To: References: Message-ID: On 03/05/12 12:14, Gergely L?rincz wrote: > I've been struggling to set up python on snow leopard, mac os x. > Stupidly I downloaded and installed python 3.2 Nothing stupid about that, although it should have worked! Did you get the MacPython version or the ActiveState Mac package or something else? > For some reason the installation littered my Android SDK folder with > main.py and other kind of python files. Don't ask me why, it's beyond > me. Me too, its a long time since I played Python on my Mac and it never did anything like that. But we do have a few Mac users so maybe they can help... If you are a Mac programmer check out the Python integration with XCode and Cocoa BTW, it works pretty well... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Thu May 3 21:12:34 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 03 May 2012 15:12:34 -0400 Subject: [Tutor] How to exit this loop in the interpreter In-Reply-To: References: Message-ID: <4FA2D8A2.8030002@gmail.com> On 5/3/2012 9:57 AM, spawgi at gmail.com wrote: > Hello all, > > I have encountered the following scenario. > Here is the code - on IDLE on Windows XP. > > *>>> while True:* Please do not use color. Post plain text. That is very hard for me to read and there is no need for color. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Thu May 3 23:28:46 2012 From: kellyadrian at hotmail.com (Adrian) Date: Thu, 3 May 2012 22:28:46 +0100 Subject: [Tutor] Embed python in a website Message-ID: I recently created a gui form using tkinter, is it possible to integrate this form to my website page? How do i integrate? Adrian Sent from my iPad From emile at fenx.com Fri May 4 00:56:56 2012 From: emile at fenx.com (Emile van Sebille) Date: Thu, 03 May 2012 15:56:56 -0700 Subject: [Tutor] Embed python in a website In-Reply-To: References: Message-ID: On 5/3/2012 2:28 PM Adrian said... > > I recently created a gui form using tkinter, is it possible to integrate this form to my website page? How do i integrate? > pyjs aka pyjamas allows you to write once and run on both web and desktop. I'd start there. Emile From alan.gauld at btinternet.com Fri May 4 01:21:02 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 04 May 2012 00:21:02 +0100 Subject: [Tutor] Embed python in a website In-Reply-To: References: Message-ID: On 03/05/12 23:56, Emile van Sebille wrote: >> I recently created a gui form using tkinter, is it possible to >> integrate this form to my website page? How do i integrate? > > pyjs aka pyjamas allows you to write once and run on both web and > desktop. I'd start there. I don't think pyjs can do Tkinter though. You have to use the pyjs widgets. Also if you are using any non Python modules you might have to do some mixed mode design. If you built the Tk app properly (with separation of logic and presentation) it shouldn't be too hard to refactor it to be viable to display on both but I don't think there is a way to do Tk apps on the web without significant change. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wescpy at gmail.com Fri May 4 01:55:30 2012 From: wescpy at gmail.com (wesley chun) Date: Thu, 3 May 2012 16:55:30 -0700 Subject: [Tutor] python installation problem In-Reply-To: References: Message-ID: there are many pitfalls in installing Python on Macs. it definitely isn't straightforward because usually the one you install will conflict with the that Apple ships with Mac OS X. i would second the recommendation to use MacPorts, homebrew, finkCmdr, or similar tools. someone should do a fresh install, document the procedure, and make a blogpost out of it! :-) cheers, --wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." ? ? wesley chun : wescpy at gmail?: @wescpy/+wescpy ? ? Python training & consulting :?http://CyberwebConsulting.com ? ? "Core Python" books :?http://CorePython.com ? ? Python blog: http://wescpy.blogspot.com From breamoreboy at yahoo.co.uk Fri May 4 03:02:45 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 04 May 2012 02:02:45 +0100 Subject: [Tutor] Embed python in a website In-Reply-To: References: Message-ID: On 03/05/2012 23:56, Emile van Sebille wrote: > On 5/3/2012 2:28 PM Adrian said... >> >> I recently created a gui form using tkinter, is it possible to >> integrate this form to my website page? How do i integrate? >> > > pyjs aka pyjamas allows you to write once and run on both web and > desktop. I'd start there. > > Emile > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Sadly the ongoing status of pyjamas is uncertain see http://code.activestate.com/lists/python-list/620105/ -- Cheers. Mark Lawrence. From googcheng at gmail.com Fri May 4 05:38:39 2012 From: googcheng at gmail.com (goog cheng) Date: Fri, 4 May 2012 11:38:39 +0800 Subject: [Tutor] the regex boundary about chinese word Message-ID: Hi, I got this problem : #!python # -*- coding: utf-8 -*- import re p = re.compile(ur'\bc123\b') print '**',p.search('no class c123 at all').group() p = re.compile(ur'\b\u7a0b\u6770\b') print ur'\u7a0b\u6770' print '****',p.search(' ?? abc'.decode('utf8')) why the \b boundary can't match the word '??' -------------- next part -------------- An HTML attachment was scrubbed... URL: From spawgi at gmail.com Fri May 4 08:39:33 2012 From: spawgi at gmail.com (spawgi at gmail.com) Date: Fri, 4 May 2012 12:09:33 +0530 Subject: [Tutor] How to exit this loop in the interpreter In-Reply-To: References: Message-ID: Thanks Jerry! By the way, I know I can change the way the loops works and bypass this issue :) I just wanted to mention this behavior which I thought interesting and present some corner case (I have worked extensively in testing). And I agree, probably I should not have used color. Bad on my part. Cheers!! Sumod On Thu, May 3, 2012 at 7:48 PM, Jerry Hill wrote: > On Thu, May 3, 2012 at 9:57 AM, wrote: > > Hello all, > > > > I have encountered the following scenario. > > Here is the code - on IDLE on Windows XP. > > > >>>> while True: > > try: > > number = raw_input("enter number - ") > > print number * number > > except ValueError: > > print "invalid number" > > except: > > print "unspecified exception" > > else: > > print "other conditions" > > > > > > enter number - 3 > > unspecified exception > > > > What I noticed is that no matter, what input I give, I cannot exit this > > loop. I have tried control-C, control-D etc. all the keys. So how can I > exit > > from this loop? > > You can't, because you've painted yourself into a corner. The bare > "except:" line will catch any exception at all. Including the > KeyboardInterrupt exception that is raised when you hit control-c. If > you must catch unknown exceptions, but still want to allow the > KeyboardInterrupt exception from pressing control-c to exit your > program, then use "except Exception:" > instead of a bare "except:" statement. Since KeyboardInterrupt (and > SystemExit) are not subclasses of Exception, they won't be caught. > > KeyboardInterrupt and SystemExit are subclasses of a class called > BaseException, instead of Exception, for this exact purpose. See more > about python's exception hierarchy here: > http://docs.python.org/library/exceptions.html > > -- > Jerry > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri May 4 12:21:13 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 May 2012 12:21:13 +0200 Subject: [Tutor] the regex boundary about chinese word References: Message-ID: goog cheng wrote: > Hi, I got this problem : > > #!python > # -*- coding: utf-8 -*- > import re > > p = re.compile(ur'\bc123\b') > print '**',p.search('no class c123 at all').group() > > p = re.compile(ur'\b\u7a0b\u6770\b') > print ur'\u7a0b\u6770' > print '****',p.search(' ?? abc'.decode('utf8')) > > why the \b boundary can't match the word '??' You need to provide the UNICODE flag: >>> re.compile(ur"\b??\b").search(u" ?? abc") >>> re.compile(ur"\b??\b", re.UNICODE).search(u" ?? abc") <_sre.SRE_Match object at 0x7f0beb325f38> See http://docs.python.org/library/re.html """ Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string ... \w When the LOCALE and UNICODE flags are not specified, matches any alphanumeric character and the underscore; this is equivalent to the set [a- zA-Z0-9_]. With LOCALE, it will match the set [0-9_] plus whatever characters are defined as alphanumeric for the current locale. If UNICODE is set, this will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database. """ From breamoreboy at yahoo.co.uk Fri May 4 13:28:10 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 04 May 2012 12:28:10 +0100 Subject: [Tutor] Embed python in a website In-Reply-To: References: Message-ID: On 04/05/2012 02:02, Mark Lawrence wrote: > On 03/05/2012 23:56, Emile van Sebille wrote: >> On 5/3/2012 2:28 PM Adrian said... >>> >>> I recently created a gui form using tkinter, is it possible to >>> integrate this form to my website page? How do i integrate? >>> >> >> pyjs aka pyjamas allows you to write once and run on both web and >> desktop. I'd start there. >> >> Emile >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > Sadly the ongoing status of pyjamas is uncertain see > http://code.activestate.com/lists/python-list/620105/ A follow up to the above here http://www.velocityreviews.com/forums/t945930-pyjamas-pyjs.html -- Cheers. Mark Lawrence. From chnlion79 at gmail.com Fri May 4 15:29:36 2012 From: chnlion79 at gmail.com (Lion Chen) Date: Fri, 04 May 2012 21:29:36 +0800 Subject: [Tutor] why i < j is True, j < k is False Message-ID: <4FA3D9C0.6040701@gmail.com> Hi, All, here are the codes: class a: pass i = a () j = a () k = a () i < j returns True j < k returns False why? Lion Chen From sntshkmr60 at gmail.com Fri May 4 15:57:20 2012 From: sntshkmr60 at gmail.com (Santosh Kumar) Date: Fri, 4 May 2012 19:27:20 +0530 Subject: [Tutor] What does L at last stands for when 10 ** 30 Message-ID: I am doing: >>> power = 10 ** 30 >>> power and the output: >>> 10000...L # what does L represent interesting thing is L doesn't shows when I do a: print power From joel.goldstick at gmail.com Fri May 4 16:05:35 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 4 May 2012 10:05:35 -0400 Subject: [Tutor] why i < j is True, j < k is False In-Reply-To: <4FA3D9C0.6040701@gmail.com> References: <4FA3D9C0.6040701@gmail.com> Message-ID: On Fri, May 4, 2012 at 9:29 AM, Lion Chen wrote: > Hi, All, > here are the codes: > > class a: > pass > > > i = a () > j = a () > k = a () > > i < j returns True > > j < k returns False > > why? > > Lion Chen > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Did you look at what I, j, and k are? They are names of objects. When I ran your code my inequalities were different. What you are seeing is likely some comparison of the location of the objects over which you have no control >>> i = a() >>> j = a() >>> k = a() >>> i < j False >>> j < k True >>> i <__main__.a instance at 0xb76d0a2c> >>> j <__main__.a instance at 0xb76d096c> >>> k <__main__.a instance at 0xb76d09ec> >>> -- Joel Goldstick From joel.goldstick at gmail.com Fri May 4 16:07:22 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 4 May 2012 10:07:22 -0400 Subject: [Tutor] What does L at last stands for when 10 ** 30 In-Reply-To: References: Message-ID: On Fri, May 4, 2012 at 9:57 AM, Santosh Kumar wrote: > I am doing: >>>> power = 10 ** 30 >>>> power > > and the output: >>>> 10000...L ? ? ? ? ?# what does L represent > > interesting thing is L doesn't shows when I do a: print power > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Long integer. You can learn more here: http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex -- Joel Goldstick From chnlion79 at gmail.com Fri May 4 16:12:38 2012 From: chnlion79 at gmail.com (Lion Chen) Date: Fri, 04 May 2012 22:12:38 +0800 Subject: [Tutor] why i < j is True, j < k is False In-Reply-To: References: <4FA3D9C0.6040701@gmail.com> Message-ID: <4FA3E3D6.5070401@gmail.com> > On Fri, May 4, 2012 at 9:29 AM, Lion Chen wrote: >> Hi, All, >> here are the codes: >> >> class a: >> pass >> >> >> i = a () >> j = a () >> k = a () >> >> i< j returns True >> >> j< k returns False >> >> why? >> >> Lion Chen >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > Did you look at what I, j, and k are? They are names of objects. > When I ran your code my inequalities were different. > What you are seeing is likely some comparison of the location of the > objects over which you have no control >>>> i = a() >>>> j = a() >>>> k = a() >>>> i< j > False >>>> j< k > True >>>> i > <__main__.a instance at 0xb76d0a2c> >>>> j > <__main__.a instance at 0xb76d096c> >>>> k > <__main__.a instance at 0xb76d09ec> > but why have i got the same results every time i run the codes? even when i restart the python interpreter, seems like i, j, k have the fixed values. > > From d at davea.name Fri May 4 16:12:56 2012 From: d at davea.name (Dave Angel) Date: Fri, 04 May 2012 10:12:56 -0400 Subject: [Tutor] why i < j is True, j < k is False In-Reply-To: <4FA3D9C0.6040701@gmail.com> References: <4FA3D9C0.6040701@gmail.com> Message-ID: <4FA3E3E8.3090200@davea.name> On 05/04/2012 09:29 AM, Lion Chen wrote: > Hi, All, > here are the codes: > > class a: > pass > > > i = a () > j = a () > k = a () > > i < j returns True > > j < k returns False > > why? > > Lion Chen > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > i, j and k are three distinct instances of the class a (which should be capitalized for clarity). Since you don't supply any comparison operator special methods in your class, Python 2 simply compares their id values. So the ordering is entirely undefined, and each of us might get different results. I, for example, got true and true. In Python 3, you'd get the following error, which is an improvement, imho: TypeError: unorderable types: A() < A() -- DaveA From d at davea.name Fri May 4 16:16:28 2012 From: d at davea.name (Dave Angel) Date: Fri, 04 May 2012 10:16:28 -0400 Subject: [Tutor] What does L at last stands for when 10 ** 30 In-Reply-To: References: Message-ID: <4FA3E4BC.3090706@davea.name> On 05/04/2012 09:57 AM, Santosh Kumar wrote: > I am doing: >>>> power = 10 ** 30 >>>> power > and the output: >>>> 10000...L # what does L represent > interesting thing is L doesn't shows when I do a: print power > _______________________________________________ The L stands for "long". The value is too large for an int, so it's promoted to long (in python 3, no such distinction). As for why it's printed, that's because in the debugger, it's displaying the repr() of the result of your expression, while print displays the str() of the result. To see a similar effect, try a literal string in the debugger -- it displays the quote marks, which are not part of the string, but they are part of the repr(esentation). -- DaveA From chnlion79 at gmail.com Fri May 4 16:21:40 2012 From: chnlion79 at gmail.com (Lion Chen) Date: Fri, 04 May 2012 22:21:40 +0800 Subject: [Tutor] why i < j is True, j < k is False In-Reply-To: <4FA3E3E8.3090200@davea.name> References: <4FA3D9C0.6040701@gmail.com> <4FA3E3E8.3090200@davea.name> Message-ID: <4FA3E5F4.4070709@gmail.com> ? 2012?05?04? 22:12, Dave Angel ??: > On 05/04/2012 09:29 AM, Lion Chen wrote: >> Hi, All, >> here are the codes: >> >> class a: >> pass >> >> >> i = a () >> j = a () >> k = a () >> >> i< j returns True >> >> j< k returns False >> >> why? >> >> Lion Chen >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > i, j and k are three distinct instances of the class a (which should be > capitalized for clarity). > > Since you don't supply any comparison operator special methods in your > class, Python 2 simply compares their id values. So the ordering is > entirely undefined, and each of us might get different results. I, for > example, got true and true. > > In Python 3, you'd get the following error, which is an improvement, imho: > > TypeError: unorderable types: A()< A() > > > i see, thanks :) Lion Chen > From joel.goldstick at gmail.com Fri May 4 16:28:15 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 4 May 2012 10:28:15 -0400 Subject: [Tutor] why i < j is True, j < k is False In-Reply-To: <4FA3E3E8.3090200@davea.name> References: <4FA3D9C0.6040701@gmail.com> <4FA3E3E8.3090200@davea.name> Message-ID: On Fri, May 4, 2012 at 10:12 AM, Dave Angel wrote: > On 05/04/2012 09:29 AM, Lion Chen wrote: >> Hi, All, >> here are the codes: >> >> class a: >> pass >> >> >> i = a () >> j = a () >> k = a () >> >> i < j returns True >> >> j < k returns False >> >> why? >> >> Lion Chen >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > i, j and k are three distinct instances of the class a ?(which should be > capitalized for clarity). > > Since you don't supply any comparison operator special methods in your > class, Python 2 simply compares their id values. ?So the ordering is > entirely undefined, and each of us might get different results. I, for > example, got true and true. > > In Python 3, you'd get the following error, which is an improvement, imho: > > TypeError: unorderable types: A() < A() > > > > > -- > > DaveA > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor One more thing. The reason the L is printed in the python interactive shell is because it is showing the repr() of the variable. Whe -- Joel Goldstick From bjorn.madsen at operationsresearchgroup.com Sat May 5 00:07:30 2012 From: bjorn.madsen at operationsresearchgroup.com (Bjorn Madsen) Date: Fri, 4 May 2012 23:07:30 +0100 Subject: [Tutor] is it possible to create and amend classes during run-time? In-Reply-To: References: Message-ID: Sorry I didn't get back earlier. But in short: Thank you! Kind Regards, Bjorn On 3 May 2012 00:01, Alan Gauld wrote: > Does anyone know if it is possible during run-time to: >>> a) add attributes to classes, which will unknown at program start, but >>> "emerge" later whilst the program is running? >>> >> > Yes, but its not very useful since the rest of your code won't know how to > access those attributes. There are ways around that (getattr() etc) > but in general it's a bad design pattern that should be avoided. > > But Python is an interpreted language so anything you can do in a script > file can also be done at runtime. > > > b) add subclasses to class (also during runtime) >>> >> > I'm not sure what you mean, but I'm guessing you are asking if you can > subclass an existing class. That is create a new class, and again the > answer is yes. > > -- > Alan G > 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 > -- Bjorn Madsen *Researcher Complex Systems Research* Ph.: (+44) 0 7792 030 720 Ph.2: (+44) 0 1767 220 828 bjorn.madsen at operationsresearchgroup.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From chare at labr.net Sat May 5 12:50:35 2012 From: chare at labr.net (Chris Hare) Date: Sat, 5 May 2012 05:50:35 -0500 Subject: [Tutor] events and popup menus In-Reply-To: References: <2C6E567B-CEAA-4070-AEDC-8E508A988518@labr.net> Message-ID: <4219008B-92D2-4EB7-943E-01AAACBBC098@labr.net> Thanks Peter - I finally got back to working on this while my dog was having a panic attack from a thunderstorm about 430 AM. :-) She is asleep as my feet. Anyway, great example and it showed me exactly what i needed to do, AND what I was doing wrong. I appreciate your help! On May 3, 2012, at 5:30 AM, Peter Otten wrote: > Chris Hare wrote: > >> I have four images in a frame. I want to pop up a menu when the user >> right clicks on an image, and when they choose an option from the menu, >> execute the action. >> >> I can create the popup menu, and bind it to the image. However, what I >> can't figure out is how to detect in the popup menu code which image fired >> the event so I can do the right thing (like display a larger version of >> the image, etc.) >> >> # create a menu >> self.popup = Menu(self.pictureWindow, tearoff=0) >> self.popup.add_command(label="Change Picture", >> command=self.selectPicture) self.popup.add_command(label="Make Primary", >> command=self.selectPicture) self.popup.add_command(label="Large View", >> command=self.selectPicture) > > You should have a different callback for every menu item: > > self.popup.add_command(label="Change Picture", command=self.change_picture) > ... > self.popup.add_command(label="Large View", command=self.large_view) > > >> self.picture1.bind("", self.do_popup) >> >> def do_popup(self,event): >> # display the popup menu >> try: >> self.popup.tk_popup(event.x_root, event.y_root, 0) >> >> finally: >> # make sure to release the grab (Tk 8.0a1 only) >> self.popup.grab_release() >> >> Thanks for the advice! > > You can remember the widget from do_popup()'s event argument > > def do_popup(self, event): > self.current_picture = event.widget > ... > > and later refer to it in the menu callbacks > > def select_picture(self): > picture = self.current_picture > ... > > I got a bit distracted struggling with PIL, therefore my "self-contained > demo" got rather baroque. You may still find it useful: > > $ cat tk_popup_demo.py > import sys > import Tkinter as tk > import ImageTk > import Image > > current_label = None > > def do_popup(event): > global current_label > current_label = event.widget > try: > popup.tk_popup(event.x_root, event.y_root, 0) > finally: > popup.grab_release() > > def rotate_picture(): > image = current_label.photoimage.image.rotate(90) > photoimage = ImageTk.PhotoImage(image) > photoimage.image = image > current_label.photoimage = current_label["image"] = photoimage > > def flip_picture(): > print "flip picture" > > def load_image(filename, maxsize=(500, 500), padcolor="#f80"): > image = Image.open(filename) > image.thumbnail(maxsize) > if image.size != maxsize: > padded_image = Image.new(image.mode, maxsize, color=padcolor) > maxx, maxy = maxsize > x, y = image.size > padded_image.paste(image, ((maxx-x)//2, (maxy-y)//2)) > image = padded_image > assert image.size == maxsize > return image > > root = tk.Tk() > > picturefiles = sys.argv[1:4] > for i, filename in enumerate(picturefiles): > image = load_image(filename) > photoimage = ImageTk.PhotoImage(image) > photoimage.image = image > > label = tk.Label(root, image=photoimage) > label.photoimage = photoimage > label.grid(row=0, column=i) > label.bind("", do_popup) > > popup = tk.Menu(root, tearoff=0) > popup.add_command(label="Rotate", command=rotate_picture) > popup.add_command(label="Flip", command=flip_picture) > > root.mainloop() > > Invoke with a few picture names (all but the first three will be ignored): > > $ python tk_popup_demo.py *.jpg > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From sntshkmr60 at gmail.com Sat May 5 20:01:13 2012 From: sntshkmr60 at gmail.com (Santosh Kumar) Date: Sat, 5 May 2012 23:31:13 +0530 Subject: [Tutor] A simple "if" and "elif" problem Message-ID: I am reading the documentation and I'm in the section 4.1. Let me write it down here: >>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x = 0 ... print('Negative changed to zero') ... elif x == 0: ... print('Zero') ... elif x == 1: ... print('Single') ... else: ... print('More') ... More Now I want to add a filter in this script, I want when a user enter a string here it give a warning "Please enter a number like 0 or 2". From emile at fenx.com Sat May 5 20:08:14 2012 From: emile at fenx.com (Emile van Sebille) Date: Sat, 05 May 2012 11:08:14 -0700 Subject: [Tutor] A simple "if" and "elif" problem In-Reply-To: References: Message-ID: On 5/5/2012 11:01 AM Santosh Kumar said... > I am reading the documentation and I'm in the section 4.1. Let me > write it down here: You'll need to peek ahead to section 8 Errors and Exceptions. Try and see if that doesn't get you going. Emile > >>>> x = int(input("Please enter an integer: ")) > Please enter an integer: 42 >>>> if x< 0: > ... x = 0 > ... print('Negative changed to zero') > ... elif x == 0: > ... print('Zero') > ... elif x == 1: > ... print('Single') > ... else: > ... print('More') > ... > More > > Now I want to add a filter in this script, I want when a user enter a > string here it give a warning "Please enter a number like 0 or 2". > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From xgermx at gmail.com Sat May 5 20:36:51 2012 From: xgermx at gmail.com (xgermx) Date: Sat, 5 May 2012 13:36:51 -0500 Subject: [Tutor] A simple "if" and "elif" problem In-Reply-To: References: Message-ID: Python novice here. Caveat emptor. Since all python input is read in as a string, you could try checking to see if the value is a digit with the .isdigit string method. e.g. if userinput.isdigit(): #do stuff else #more stuff http://stackoverflow.com/questions/5424716/python-how-to-check-if-input-is-a-number-given-that-input-always-returns-stri http://docs.python.org/library/stdtypes.html On Sat, May 5, 2012 at 1:08 PM, Emile van Sebille wrote: > On 5/5/2012 11:01 AM Santosh Kumar said... > >> I am reading the documentation and I'm in the section 4.1. Let me >> write it down here: > > > You'll need to peek ahead to section 8 Errors and Exceptions. > > Try and see if that doesn't get you going. > > Emile > > > > >> >>>>> x = int(input("Please enter an integer: ")) >> >> Please enter an integer: 42 >>>>> >>>>> if x< ?0: >> >> ... ? ? ?x = 0 >> ... ? ? ?print('Negative changed to zero') >> ... elif x == 0: >> ... ? ? ?print('Zero') >> ... elif x == 1: >> ... ? ? ?print('Single') >> ... else: >> ... ? ? ?print('More') >> ... >> More >> >> Now I want to add a filter in this script, I want when a user enter a >> string here it give a warning "Please enter a number like 0 or 2". >> _______________________________________________ >> 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 Sat May 5 20:48:19 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 05 May 2012 19:48:19 +0100 Subject: [Tutor] A simple "if" and "elif" problem In-Reply-To: References: Message-ID: On 05/05/12 19:01, Santosh Kumar wrote: > >>>> x = int(input("Please enter an integer: ")) > Please enter an integer: 42 > Now I want to add a filter in this script, I want when a user enter a > string here it give a warning "Please enter a number like 0 or 2". What happens if the user does not enter a valid integer at the moment? You should get an error message? That error message will provide the name of a particular type of Error. Python lets you catch errors and handle them. You will find out how to do that later in your tutorial. Once you catch the error you will likely want to loop around and ask for more input. You will need a loop - probably a while loop - to do that. So in pseudo code you will wind up with something like: while True: try: read the input and convert to int break out of the loop except when there is an error: print a message and go round the loop again -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From benderjacob44 at gmail.com Sun May 6 15:02:47 2012 From: benderjacob44 at gmail.com (Jacob Bender) Date: Sun, 6 May 2012 09:02:47 -0400 Subject: [Tutor] Sorting the parts of a dictionary into a list Message-ID: Dear tutors, I'm trying to create a neural network program. Each neuron is in a dictionary and each of its connections and their strengths are in a nested dictionary. So {0:{1:4, 2:5}}, 1:{0:6}, 2:{1:2}} would mean that neuron 0 is connected to neuron 1 with a strength of 4. And it also means that neuron 1 is connected to neuron 0 with a strength of 6. The problem is that I'm working on a function that is supposed to add the total strengths of each neuron. So, for example, neuron 0's connections have a total strength of 9 (4+5). The other problem is getting all of the total strengths and ordering the neurons into a list. So, from the example, the list would be from [0,1,2] because zero has the greatest total strength of 9, then 1 with a total strength of 6 and so on. I've been working on this problem for at least 2 hours now and still haven't found anything close to a solution. Thank you and please help! -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun May 6 15:51:15 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 06 May 2012 15:51:15 +0200 Subject: [Tutor] Sorting the parts of a dictionary into a list References: Message-ID: Jacob Bender wrote: > Dear tutors, > > I'm trying to create a neural network program. Each neuron is in a > dictionary and each of its connections and their strengths are in a nested > dictionary. So {0:{1:4, 2:5}}, 1:{0:6}, 2:{1:2}} would mean that neuron 0 > is connected to neuron 1 with a strength of 4. And it also means that > neuron 1 is connected to neuron 0 with a strength of 6. > > The problem is that I'm working on a function that is supposed to add the > total strengths of each neuron. So, for example, neuron 0's connections > have a total strength of 9 (4+5). The other problem is getting all of the > total strengths and ordering the neurons into a list. So, from the > example, the list would be from [0,1,2] because zero has the greatest > total strength of 9, then 1 with a total strength of 6 and so on. I've > been working on this problem for at least 2 hours now and still haven't > found anything close to a solution. It is always a good idea to post the code you have -- if only to give as an idea of your abilities. > Thank you and please help! You need a function to calculate the total strength def total_strength(neuron): # calculate and return total strength You can then sort the dictionary keys: connections = {0:{1:4, 2:5}, 1:{0:6}, 2:{1:2}} neurons_by_strength = sorted(connections, key=total_strength) To give you an idea how the key function works: >>> sorted([3, -2, 1], key=abs) # abs() calculates the absolute value [1, -2, 3] Writing the body of the total_strength() function is not hard: look up the neuron in the connections dict and sum up the values of the inner dict. Come back here should these hints not be sufficient to get you going. Remember to provide some code next time ;) From scubacuda at gmail.com Mon May 7 03:52:05 2012 From: scubacuda at gmail.com (Rogelio) Date: Sun, 6 May 2012 18:52:05 -0700 Subject: [Tutor] error when using using subprocess.popen in Python wrapper script Message-ID: I am new to Python and am trying to figure out how to execute Linux commands via a Python wrapper. This works ********************** #this works okay import subprocess uname = "uname" uname_arg = "-a" subprocess.call([uname,uname_arg]) ********************** But this doesn't. *********************** #this doesn't work import subprocess #perl prog works in real life perl_prog = "perl perlprog.pl" perl_prog_h ="-h" #this is where it breaks subprocess.call([perl_prog, perl_prog_h]) ************************ I get the following error when I run the program python errorCheck.py Linux mybox.domain.com 2.6.18-238.9.1.el5 #1 SMP Tue Apr 12 18:10:13 EDT 2011 x86_64 x86_64 x86_64 GNU/Linux Traceback (most recent call last): File "errorCheck.py", line 16, in ? subprocess.call([perl_prog, perl_prog_h]) File "/usr/lib64/python2.4/subprocess.py", line 419, in call return Popen(*args, **kwargs).wait() File "/usr/lib64/python2.4/subprocess.py", line 550, in __init__ errread, errwrite) File "/usr/lib64/python2.4/subprocess.py", line 996, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory any suggestions? From martin at linux-ip.net Mon May 7 05:23:40 2012 From: martin at linux-ip.net (Martin A. Brown) Date: Sun, 6 May 2012 23:23:40 -0400 Subject: [Tutor] error when using using subprocess.popen in Python wrapper script In-Reply-To: References: Message-ID: Hello, : perl_prog = "perl perlprog.pl" : perl_prog_h ="-h" : #this is where it breaks : subprocess.call([perl_prog, perl_prog_h]) This is asking your Linux to search your $PATH and execute a program called: 'perl perlprog.pl' Rather than to execute a program called 'perl' and pass as the first argument 'perlprog.pl'. perl_bin = 'perl' perl_prog = '/path/to/perlprog.pl' perl_prog_h = '-h' subprocess.call([perl_bin, perl_prog, perl_prog_h]) Or, if I were in your shoes, I would do something a bit more like this: cmd = [ '/usr/bin/perl', '/path/to/perlprog.pl', '-h' ] subprocess.call(cmd) Probably the most interesting thing here for you to note in the long run is to learn what 'magically' happens in the shell when you run a command. Since you are using Linux, you may find strace useful to see what Python is passing to your system for execution: strace -e process python /path/to/your/python/script.py Enjoy, -Martin -- Martin A. Brown http://linux-ip.net/ From scubacuda at gmail.com Mon May 7 06:07:30 2012 From: scubacuda at gmail.com (Rogelio) Date: Sun, 6 May 2012 21:07:30 -0700 Subject: [Tutor] error when using using subprocess.popen in Python wrapper script In-Reply-To: References: Message-ID: On Sun, May 6, 2012 at 8:23 PM, Martin A. Brown wrote: > Or, if I were in your shoes, I would do something a bit more like > this: > > ?cmd = [ '/usr/bin/perl', '/path/to/perlprog.pl', '-h' ] > ?subprocess.call(cmd) Thank you, Martin. This was helpful. Installed Strace and found out that I mispelled something. :b I suspect that I'm having a problem with it reading a long string, but I'm not sure why. (Need to escape a char? Or perhaps something is timing out?) This works cmd = ['perl','/path/to/my/script.pl, '-h'] subprocess.call(cmd) But this does not cmd = ['perl','/path/to/my/script.pl, '-x arg1 -y arg2 -z arg3'] subprocess.call(cmd) strace gives me this output *************** MY COMMAND: strace -e process python myProg.py OUTPUT execve("/usr/bin/python", ["python", "myProg.py"], [/* 22 vars */]) = 0 arch_prctl(ARCH_SET_FS, 0x2b75cfb731e0) = 0 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x2b75cfb73270) = 15883 wait4(15883, +-------------------------------------------------------------------------------+ | (output from script file) ERROR: You must specify either a command to be executed or an a command file for execution [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 15883 --- SIGCHLD (Child exited) @ 0 (0) --- exit_group(0) = ? ************************************* From scubacuda at gmail.com Mon May 7 09:18:41 2012 From: scubacuda at gmail.com (Rogelio) Date: Mon, 7 May 2012 00:18:41 -0700 Subject: [Tutor] error when using using subprocess.popen in Python wrapper script In-Reply-To: References: Message-ID: If I want to write this command to a file, would this be the right format? ********************************* import subprocess (all my variables defined okay) perl_script=subprocess.call(['perl',perl_prog,ipfile,cmd,user,timeout,]) log=open('/tmp/pythonOutput.txt',w) log.write(subprocess.call(perl_script)) ********************************* The program runs (and outputs stuff on the screen okay), but when I "cat /tmp/pythonOutput.txt", nothing is there. (While I'm not waiting for the entire program to run across all the IP addresses, I would think that something would be go out into that log file.) From __peter__ at web.de Mon May 7 09:44:16 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 May 2012 09:44:16 +0200 Subject: [Tutor] error when using using subprocess.popen in Python wrapper script References: Message-ID: Rogelio wrote: > If I want to write this command to a file, would this be the right format? > > ********************************* > import subprocess > > (all my variables defined okay) > > perl_script=subprocess.call(['perl',perl_prog,ipfile,cmd,user,timeout,]) > > log=open('/tmp/pythonOutput.txt',w) > log.write(subprocess.call(perl_script)) > ********************************* > > The program runs (and outputs stuff on the screen okay), but when I > "cat /tmp/pythonOutput.txt", nothing is there. The documentation is fairly clear: """ subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False) Run the command described by args. Wait for command to complete, then return the returncode attribute. """ > (While I'm not waiting for the entire program to run across all the IP > addresses, I would think that something would be go out into that log > file.) No, you'll get an integer return code and ultimately a TypeError when you pass that to the file's write() method. Read the docs on Popen.communicate() http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate From paradox at pobox.com Mon May 7 15:43:31 2012 From: paradox at pobox.com (Thomas C. Hicks) Date: Mon, 7 May 2012 21:43:31 +0800 Subject: [Tutor] Displaying data in columns Message-ID: <20120507214331.047a57d9@midgel> I have some data that comes out of a database as a list of tuples of integers and strings, one tuple for each row in the ResultProxy from the select operation. The data looks something like this: [(56, 12, 8, u'2012-02', 10, 12, u'Guangxi Province', u'Guangxi', u'10', 8, u'TOT'), (57, 21, 1, u'2012-03', 36, 21, u'Sichuan EQ Region', u'Sichuan', u'2', 1, u'Basic Medical - Rural')] I would like to display some of the items in the tuples in columnar format with each column lining up on the left side (below should be three neat columns with location, training type, number trained and date): Guangxi Province TOT 10 2012-02 Sichuan EQ Region Basic Medical - Rural 36 2012-03 Surely there is a python module that helps with that, isn't there? I know I could write a function that reads the items, figures string lengths, adds padding white space and prints out the columns but am hoping there is a more elegant solution. I am not against reading documentation, just can't find the right module to read about. thomas From bgailer at gmail.com Mon May 7 16:21:07 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 07 May 2012 10:21:07 -0400 Subject: [Tutor] Displaying data in columns In-Reply-To: <20120507214331.047a57d9@midgel> References: <20120507214331.047a57d9@midgel> Message-ID: <4FA7DA53.2010705@gmail.com> On 5/7/2012 9:43 AM, Thomas C. Hicks wrote: > I have some data that comes out of a database as a list of tuples of > integers and strings, one tuple for each row in the ResultProxy from > the select operation. The data looks something like this: Where the data comes from is not relevant. Please don't clutter your questions with irrelevant facts. > [(56, 12, 8, u'2012-02', 10, 12, u'Guangxi Province', u'Guangxi', > u'10', 8, u'TOT'), (57, 21, 1, u'2012-03', 36, 21, > u'Sichuan EQ Region', u'Sichuan', u'2', 1, u'Basic Medical - > Rural')] > > I would like to display some of the items in the tuples in columnar > format with each column lining up on the left side (below should be > three neat columns with location, training type, number trained and > date): > > Guangxi Province TOT 10 2012-02 > Sichuan EQ Region Basic Medical - Rural 36 2012-03 > > Surely there is a python module that helps with that, isn't there? I > know I could write a function that reads the items, figures string > lengths, adds padding white space and prints out the columns but am > hoping there is a more elegant solution. I am not against reading > documentation, just can't find the right module to read about. the basic tool you'd use is string formatting. I prefer the original %. "%24s%24s%8s%7s" % -- Bob Gailer 919-636-4239 Chapel Hill NC From chare at labr.net Mon May 7 16:19:49 2012 From: chare at labr.net (Chris Hare) Date: Mon, 7 May 2012 09:19:49 -0500 Subject: [Tutor] looking for some advice Message-ID: Hello Everyone: Here is what I am trying to do: I have a window which has a row of buttons on it. Below the buttons is a label frame. Depending upon which button they push, I want to change the widgets in the label frame. I can add widgets now with no problem. Basically, I am trying to imitate a notebook like in Tkinter.ttk, without having to re-write a major chunk of the app to add such a widget. I know Tix has a notebook widget, but that would require people (read end users) to download and compile the Tix components. My questions are: 1. how do I remove all of the widgets from the label frame to add the new ones? 2. Am I better off just creating different label frames for each group of widgets and then just using grid_forget and grid_remember to hide or show them as I need them? 3. How else would you approach this problem? Yes - I guess I am looking for some design advice. This is creeping a little since my customer (my wife who is a horse breeder) would like to have some things done a little differently in her app. Thanks for your suggestions! Chris From emile at fenx.com Mon May 7 17:21:42 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 07 May 2012 08:21:42 -0700 Subject: [Tutor] Displaying data in columns In-Reply-To: <20120507214331.047a57d9@midgel> References: <20120507214331.047a57d9@midgel> Message-ID: On 5/7/2012 6:43 AM Thomas C. Hicks said... > I would like to display some of the items in the tuples in columnar > format with each column lining up on the left side > I am not against reading > documentation, just can't find the right module to read about. You'll want to read up on the string interpolation related docs. Start with http://docs.python.org/release/2.5.2/lib/typesseq-strings.html or the equivalent for your python version. Emile From cranky.frankie at gmail.com Mon May 7 19:16:28 2012 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Mon, 7 May 2012 13:16:28 -0400 Subject: [Tutor] Curious dictionary printing Message-ID: In 3.2.2 in IDLE I have this dictionary entry: Namath = {"first_name": "Joe", "last_name": "Namath", "phone": "212-222-7777",\ "email": "joe.namath at gmail.com", "stadium": "Shea Stadium"} when I print it: print(Namath) I get: {'phone': '212-222-7777', 'first_name': 'Joe', 'last_name': 'Namath', 'email': 'joe.namath at gmail.com', 'stadium': 'Shea Stadium'} Why is it out of order? -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?The problem with quotes on the Internet is that it is often difficult to verify their authenticity.? - Abraham Lincoln From wprins at gmail.com Mon May 7 19:56:20 2012 From: wprins at gmail.com (Walter Prins) Date: Mon, 7 May 2012 18:56:20 +0100 Subject: [Tutor] Curious dictionary printing In-Reply-To: References: Message-ID: Hi, On 7 May 2012 18:16, Cranky Frankie wrote: > In 3.2.2 in IDLE I have this dictionary entry: > > Namath = {"first_name": "Joe", "last_name": "Namath", "phone": " > 212-222-7777",\ > "email": "joe.namath at gmail.com", "stadium": "Shea Stadium"} > > Why is it out of order? Python dictionaries (unlike real physical language dictionaries), are not ordered, and should be thought of as "an unordered set of *key: value*pairs"[1] Walter [1] http://docs.python.org/tutorial/datastructures.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon May 7 20:02:33 2012 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 May 2012 20:02:33 +0200 Subject: [Tutor] looking for some advice References: Message-ID: Chris Hare wrote: > Hello Everyone: > > Here is what I am trying to do: > > I have a window which has a row of buttons on it. Below the buttons is a > label frame. Depending upon which button they push, I want to change the > widgets in the label frame. I can add widgets now with no problem. > > Basically, I am trying to imitate a notebook like in Tkinter.ttk, without > having to re-write a major chunk of the app to add such a widget. I know > Tix has a notebook widget, but that would require people (read end users) > to download and compile the Tix components. > > My questions are: > > 1. how do I remove all of the widgets from the label frame to add the new > ones? > 2. Am I better off just creating different label frames for each group of > widgets and then just using grid_forget and grid_remember to hide or show > them as I need them? > 3. How else would you approach this problem? > > Yes - I guess I am looking for some design advice. This is creeping a > little since my customer (my wife who is a horse breeder) would like to > have some things done a little differently in her app. > > Thanks for your suggestions! There is a tabbedpages.TabbedPageSet widget in idlelib. At first glance I don't see any dependencies, so maybe you can use that? From xancorreu at gmail.com Mon May 7 20:24:56 2012 From: xancorreu at gmail.com (xancorreu) Date: Mon, 07 May 2012 20:24:56 +0200 Subject: [Tutor] How can I have type "function" in my script? Message-ID: <4FA81378.6080300@gmail.com> Hi, I have this script: from types import * class Tag: def __init__(self, nom, tipus, valor): self.nom = nom self.tipus = tipus self.valor = valor def __str__(self): return "Nom: " + str(self.nom) + ", Tipus: " + str(self.tipus) + ", Valor: " + str(self.valor) def main(): a = Tag("descripci?", str, "primera tasca") b = Tag("unmes", str, lambda x: x+1) print(a) print(b) if __name__ == '__main__': main() All is ok, but when I substitute b = Tag("unmes", str, lambda x: x+1) for b = Tag("unmes", function, lambda x: x+1) I receive an error that function is not globally defined variable. How can I say that function is the types.function? (the type of lambda x: x+1) I use python3 Thanks in advance, Xan. From chare at labr.net Mon May 7 20:46:50 2012 From: chare at labr.net (Chris Hare) Date: Mon, 7 May 2012 13:46:50 -0500 Subject: [Tutor] looking for some advice In-Reply-To: References: Message-ID: Thanks Peter - I will give it a look On May 7, 2012, at 1:02 PM, Peter Otten wrote: > Chris Hare wrote: > >> Hello Everyone: >> >> Here is what I am trying to do: >> >> I have a window which has a row of buttons on it. Below the buttons is a >> label frame. Depending upon which button they push, I want to change the >> widgets in the label frame. I can add widgets now with no problem. >> >> Basically, I am trying to imitate a notebook like in Tkinter.ttk, without >> having to re-write a major chunk of the app to add such a widget. I know >> Tix has a notebook widget, but that would require people (read end users) >> to download and compile the Tix components. >> >> My questions are: >> >> 1. how do I remove all of the widgets from the label frame to add the new >> ones? >> 2. Am I better off just creating different label frames for each group of >> widgets and then just using grid_forget and grid_remember to hide or show >> them as I need them? >> 3. How else would you approach this problem? >> >> Yes - I guess I am looking for some design advice. This is creeping a >> little since my customer (my wife who is a horse breeder) would like to >> have some things done a little differently in her app. >> >> Thanks for your suggestions! > > There is a tabbedpages.TabbedPageSet widget in idlelib. At first glance I > don't see any dependencies, so maybe you can use that? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From glenbot at gmail.com Mon May 7 21:01:54 2012 From: glenbot at gmail.com (Glen Zangirolami) Date: Mon, 7 May 2012 14:01:54 -0500 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: <4FA81378.6080300@gmail.com> References: <4FA81378.6080300@gmail.com> Message-ID: Xan, it's "not defined" because you haven't defined a function called "function" or any variable called "function". Nom: descripci, Tipus: , Valor: primera tasca Nom: unmes, Tipus: , Valor: at 0x10df736e0> str comes back as because str is a built-in method and python and will always be in the namespace. See http://docs.python.org/library/functions.html#str On Mon, May 7, 2012 at 1:24 PM, xancorreu wrote: > Hi, > > I have this script: > > from types import * > > class Tag: > > def __init__(self, nom, tipus, valor): > self.nom = nom > self.tipus = tipus > self.valor = valor > > def __str__(self): > return "Nom: " + str(self.nom) + ", Tipus: " + str(self.tipus) + > ", Valor: " + str(self.valor) > > > def main(): > a = Tag("descripci?", str, "primera tasca") > b = Tag("unmes", str, lambda x: x+1) > print(a) > print(b) > > if __name__ == '__main__': > main() > > > All is ok, but when I substitute b = Tag("unmes", str, lambda x: x+1) for > b = Tag("unmes", function, lambda x: x+1) I receive an error that function > is not globally defined variable. How can I say that function is the > types.function? (the type of lambda x: x+1) > > I use python3 > > > Thanks in advance, > Xan. > ______________________________**_________________ > 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 d at davea.name Mon May 7 21:07:46 2012 From: d at davea.name (Dave Angel) Date: Mon, 07 May 2012 15:07:46 -0400 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: <4FA81378.6080300@gmail.com> References: <4FA81378.6080300@gmail.com> Message-ID: <4FA81D82.6060208@davea.name> On 05/07/2012 02:24 PM, xancorreu wrote: > Hi, > > I have this script: > > from types import * > Bad idea. Once you do that, you can silently overwrite globals in your own module with stuff that the current version of types happens to have in it. Besides, it then becomes very hard to read your program and figure out which names you really did want to import. If you're just getting one or two names, such as in your case, better just do import types > class Tag: > > def __init__(self, nom, tipus, valor): > self.nom = nom > self.tipus = tipus > self.valor = valor > > def __str__(self): > return "Nom: " + str(self.nom) + ", Tipus: " + > str(self.tipus) + ", Valor: " + str(self.valor) > > > def main(): > a = Tag("descripci?", str, "primera tasca") > b = Tag("unmes", str, lambda x: x+1) > print(a) > print(b) > > if __name__ == '__main__': > main() > > > All is ok, but when I substitute b = Tag("unmes", str, lambda x: x+1) > for b = Tag("unmes", function, lambda x: x+1) I receive an error that > function is not globally defined variable. How can I say that function > is the types.function? (the type of lambda x: x+1) > Where's the stack trace and the exact error message? types.function is undefined. The types module does not expose a name called 'function,' at least not in python 3.2 The type of a lambda is , so it's not clear what you really want. Why don't you show the program as you actually run it (perhaps with both versions of the b= assignment), and the output and stack trace you got. Then explain just what you'd hoped to get, as output. > I use python3 > > > Thanks in advance, > Xan. -- DaveA From joel.goldstick at gmail.com Mon May 7 21:11:55 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 7 May 2012 15:11:55 -0400 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: <4FA81D82.6060208@davea.name> References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> Message-ID: On Mon, May 7, 2012 at 3:07 PM, Dave Angel wrote: > On 05/07/2012 02:24 PM, xancorreu wrote: >> Hi, >> >> I have this script: >> >> from types import * >> > Bad idea. ?Once you do that, you can silently overwrite globals in your > own module with stuff that the current version of types happens to have > in it. ?Besides, it then becomes very hard to read your program and > figure out which names you really did want to import. > > If you're just getting one or two names, such as in your case, better > just do > ? ?import types > >> class Tag: can a class be defined this way in python 3.x? I thought it needs a parent class as a parameter? >> >> ? ? def __init__(self, nom, tipus, valor): >> ? ? ? ? self.nom = nom >> ? ? ? ? self.tipus = tipus >> ? ? ? ? self.valor = valor >> >> ? ? def __str__(self): >> ? ? ? ? return "Nom: " + str(self.nom) + ", Tipus: " + >> str(self.tipus) ?+ ", Valor: " + str(self.valor) >> >> >> def main(): >> ? ? a = Tag("descripci?", str, "primera tasca") >> ? ? b = Tag("unmes", str, lambda x: x+1) >> ? ? print(a) >> ? ? print(b) >> >> if __name__ == '__main__': >> ? ? ? ? main() >> >> >> All is ok, but when I substitute b = Tag("unmes", str, lambda x: x+1) >> for b = Tag("unmes", function, lambda x: x+1) I receive an error that >> function is not globally defined variable. How can I say that function >> is the types.function? (the type of lambda x: x+1) >> > Where's the stack trace and the exact error message? > > types.function is undefined. ?The types module does not expose a name > called 'function,' at least not in python 3.2 > > The type of a lambda is , so it's not clear what you > really want. > > Why don't you show the program as you actually run it (perhaps with both > versions of the b= assignment), and the output and stack trace you got. > Then explain just what you'd hoped to get, as output. > > >> I use python3 >> >> >> Thanks in advance, >> Xan. > > -- > > DaveA > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick From d at davea.name Mon May 7 21:16:57 2012 From: d at davea.name (Dave Angel) Date: Mon, 07 May 2012 15:16:57 -0400 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> Message-ID: <4FA81FA9.8030307@davea.name> On 05/07/2012 03:11 PM, Joel Goldstick wrote: > On Mon, May 7, 2012 at 3:07 PM, Dave Angel wrote: >> On 05/07/2012 02:24 PM, xancorreu wrote: >>> Hi, >>> >>> I have this script: >>> >>> from types import * >>> >> Bad idea. Once you do that, you can silently overwrite globals in your >> own module with stuff that the current version of types happens to have >> in it. Besides, it then becomes very hard to read your program and >> figure out which names you really did want to import. >> >> If you're just getting one or two names, such as in your case, better >> just do >> import types >> >>> class Tag: > > can a class be defined this way in python 3.x? I thought it needs a > parent class as a parameter? >>> That's legal in 3.x The difference between 2.x and 3.x is that if you omit the base class in 2.x, it generates an old-style class, while in 3.x it always uses new-style classes. -- DaveA From alan.gauld at btinternet.com Mon May 7 22:02:24 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 07 May 2012 21:02:24 +0100 Subject: [Tutor] Displaying data in columns In-Reply-To: <20120507214331.047a57d9@midgel> References: <20120507214331.047a57d9@midgel> Message-ID: On 07/05/12 14:43, Thomas C. Hicks wrote: > I would like to display some of the items in the tuples in columnar > format with each column lining up on the left side (below should be > three neat columns with location, training type, number trained and > date): You need to read up on string formatting. That allows you to specify the length of fields, whether they are left or right justified, any leading pad characters etc. This is not in a module but is a standard feature of Python. For anything more exotic you should look to a formatting language like HTML. Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon May 7 22:05:05 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 07 May 2012 21:05:05 +0100 Subject: [Tutor] looking for some advice In-Reply-To: References: Message-ID: On 07/05/12 15:19, Chris Hare wrote: > Basically, I am trying to imitate a notebook like in Tkinter.ttk, > I know Tix has a notebook widget, but that would require people > to download and compile the Tix components. You must be using a very old version of Python. Tix has been in the standard library since version 2.3 I think... The documentation for the Python version is not great but there is a lot on the Tcl version wjhich is fairly easy to translate. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From xancorreu at gmail.com Mon May 7 22:37:54 2012 From: xancorreu at gmail.com (xancorreu) Date: Mon, 07 May 2012 22:37:54 +0200 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: <4FA81D82.6060208@davea.name> References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> Message-ID: <4FA832A2.5000901@gmail.com> Al 07/05/12 21:07, En/na Dave Angel ha escrit: > On 05/07/2012 02:24 PM, xancorreu wrote: >> Hi, >> >> I have this script: >> >> from types import * >> > Bad idea. Once you do that, you can silently overwrite globals in your > own module with stuff that the current version of types happens to have > in it. Besides, it then becomes very hard to read your program and > figure out which names you really did want to import. > > If you're just getting one or two names, such as in your case, better > just do > import types > >> class Tag: >> >> def __init__(self, nom, tipus, valor): >> self.nom = nom >> self.tipus = tipus >> self.valor = valor >> >> def __str__(self): >> return "Nom: " + str(self.nom) + ", Tipus: " + >> str(self.tipus) + ", Valor: " + str(self.valor) >> >> >> def main(): >> a = Tag("descripci?", str, "primera tasca") >> b = Tag("unmes", str, lambda x: x+1) >> print(a) >> print(b) >> >> if __name__ == '__main__': >> main() >> >> >> All is ok, but when I substitute b = Tag("unmes", str, lambda x: x+1) >> for b = Tag("unmes", function, lambda x: x+1) I receive an error that >> function is not globally defined variable. How can I say that function >> is the types.function? (the type of lambda x: x+1) >> > Where's the stack trace and the exact error message? > > types.function is undefined. The types module does not expose a name > called 'function,' at least not in python 3.2 > > The type of a lambda is, so it's not clear what you > really want. > > Why don't you show the program as you actually run it (perhaps with both > versions of the b= assignment), and the output and stack trace you got. > Then explain just what you'd hoped to get, as output. > This is the code: class Tag: def __init__(self, nom, tipus, valor): self.nom = nom self.tipus = tipus self.valor = valor def __str__(self): return "Nom: " + str(self.nom) + ", Tipus: " + str(self.tipus) + ", Valor: " + str(self.valor) class Task: _nombre = 0 def __init__(self): self.tags = [] Task._nombre = Task._nombre + 1 self.num = Task._nombre def __str__(self): return "N?mero: " + str(self.num) + ", Tags: " + str(self.tags) def main(): a = Tag("descripci?", str, "primera tasca") b = Tag("unmes", str, lambda x: x+1) c = Tag("twice", type(lambda: x: x), lambda x: 2*x) # en comptes de str ha de ser lambda print(a) print(b) print(b.valor(2)) t = Task() print("Tasca 1:", t) t2 = Task() print("Tasca 2:", t2) if __name__ == '__main__': main() and it fails here: $ python3 tasques.py File "tasques.py", line 26 c = Tag("twice", type(lambda: x: x), lambda x: 2*x) ^ SyntaxError: invalid syntax Really, I want to specify "manually" the type of lambda, but it does not work. How to do that? Thanks, >> I use python3 >> >> >> Thanks in advance, >> Xan. From breamoreboy at yahoo.co.uk Mon May 7 22:57:15 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 07 May 2012 21:57:15 +0100 Subject: [Tutor] Curious dictionary printing In-Reply-To: References: Message-ID: On 07/05/2012 18:16, Cranky Frankie wrote: > In 3.2.2 in IDLE I have this dictionary entry: > > Namath = {"first_name": "Joe", "last_name": "Namath", "phone": "212-222-7777",\ > "email": "joe.namath at gmail.com", "stadium": "Shea Stadium"} > > when I print it: > > print(Namath) > > I get: > > {'phone': '212-222-7777', 'first_name': 'Joe', 'last_name': 'Namath', > 'email': 'joe.namath at gmail.com', 'stadium': 'Shea Stadium'} > > Why is it out of order? > Cos plain old dicts have no order, but this can be done with http://docs.python.org/library/collections.html#ordereddict-objects -- Cheers. Mark Lawrence. From d at davea.name Mon May 7 23:59:55 2012 From: d at davea.name (Dave Angel) Date: Mon, 07 May 2012 17:59:55 -0400 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: <4FA832A2.5000901@gmail.com> References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> <4FA832A2.5000901@gmail.com> Message-ID: <4FA845DB.7050807@davea.name> On 05/07/2012 04:37 PM, xancorreu wrote: > Al 07/05/12 21:07, En/na Dave Angel ha escrit: >> On 05/07/2012 02:24 PM, xancorreu wrote: >>> Hi, >>> >>> I have this script: >>> >>> from types import * >>> >> Bad idea. Once you do that, you can silently overwrite globals in your >> own module with stuff that the current version of types happens to have >> in it. Besides, it then becomes very hard to read your program and >> figure out which names you really did want to import. >> >> If you're just getting one or two names, such as in your case, better >> just do >> import types >> >>> class Tag: >>> >>> def __init__(self, nom, tipus, valor): >>> self.nom = nom >>> self.tipus = tipus >>> self.valor = valor >>> >>> def __str__(self): >>> return "Nom: " + str(self.nom) + ", Tipus: " + >>> str(self.tipus) + ", Valor: " + str(self.valor) >>> >>> >>> def main(): >>> a = Tag("descripci?", str, "primera tasca") >>> b = Tag("unmes", str, lambda x: x+1) >>> print(a) >>> print(b) >>> >>> if __name__ == '__main__': >>> main() >>> >>> >>> All is ok, but when I substitute b = Tag("unmes", str, lambda x: x+1) >>> for b = Tag("unmes", function, lambda x: x+1) I receive an error that >>> function is not globally defined variable. How can I say that function >>> is the types.function? (the type of lambda x: x+1) >>> >> Where's the stack trace and the exact error message? >> >> types.function is undefined. The types module does not expose a name >> called 'function,' at least not in python 3.2 >> >> The type of a lambda is, so it's not clear what you >> really want. >> >> Why don't you show the program as you actually run it (perhaps with both >> versions of the b= assignment), and the output and stack trace you got. >> Then explain just what you'd hoped to get, as output. >> > > This is the code: > > class Tag: > > def __init__(self, nom, tipus, valor): > self.nom = nom > self.tipus = tipus > self.valor = valor > > def __str__(self): > return "Nom: " + str(self.nom) + ", Tipus: " + str(self.tipus) > + ", Valor: " + str(self.valor) > > class Task: > _nombre = 0 > > def __init__(self): > self.tags = [] > Task._nombre = Task._nombre + 1 > self.num = Task._nombre > > > def __str__(self): > return "N?mero: " + str(self.num) + ", Tags: " + str(self.tags) > > def main(): > a = Tag("descripci?", str, "primera tasca") > b = Tag("unmes", str, lambda x: x+1) > c = Tag("twice", type(lambda: x: x), lambda x: 2*x) > # en comptes de str ha de ser lambda > print(a) > print(b) > print(b.valor(2)) > t = Task() > print("Tasca 1:", t) > t2 = Task() > print("Tasca 2:", t2) > > if __name__ == '__main__': > main() > > > and it fails here: > > $ python3 tasques.py > File "tasques.py", line 26 > c = Tag("twice", type(lambda: x: x), lambda x: 2*x) > ^ > SyntaxError: invalid syntax > > > Really, I want to specify "manually" the type of lambda, but it does not > work. How to do that? > > > Thanks, > >>> I use python3 >>> >>> >>> Thanks in advance, >>> Xan. > > def main(): a = Tag("descripci?", str, "primera tasca") print (a) b = Tag("unmes", str, lambda x: x+1) print(b) c = Tag("unmes", "function", lambda x: x+1) print(c) Does that help? -- DaveA From alan.gauld at btinternet.com Tue May 8 01:24:22 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 May 2012 00:24:22 +0100 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: <4FA832A2.5000901@gmail.com> References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> <4FA832A2.5000901@gmail.com> Message-ID: On 07/05/12 21:37, xancorreu wrote: > This is the code: OK, But it's not clear from that why you want the type. You are not doing anything meaningful with the type. > class Tag: > > def __init__(self, nom, tipus, valor): > self.nom = nom > self.tipus = tipus > self.valor = valor > > def __str__(self): > return "Nom: " + str(self.nom) + ", Tipus: " + str(self.tipus) + ", > Valor: " + str(self.valor) You store it then print the string version of it. Why not just pass a string name? > def main(): > a = Tag("descripci?", str, "primera tasca") > b = Tag("unmes", str, lambda x: x+1) > c = Tag("twice", type(lambda: x: x), lambda x: 2*x) > and it fails here: > > $ python3 tasques.py > File "tasques.py", line 26 > c = Tag("twice", type(lambda: x: x), lambda x: 2*x) > ^ > SyntaxError: invalid syntax As it says there is a syntax error. Look at your two lambda expressions, the second one has an extra : If you really want the type of a function just use one of the built in functions... or a very simple lambda: >>> type(pow) >>> type(lambda : 0) >>> But in most cases you don't need the type and the callable() function is more useful. >>> callable(pow) True >>> callable(lambda : 0) True >>> callable(7) False >>> HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bruno.braga at gmail.com Tue May 8 03:44:13 2012 From: bruno.braga at gmail.com (BRAGA, Bruno) Date: Tue, 8 May 2012 11:44:13 +1000 Subject: [Tutor] Console Application - Key Events Message-ID: Hi tutors, I would like to know if there is any "easy" way to handle events (such as mouse movements, keyboard keys pressed, etc) in console based python applications? More specifically, I am working on a screensaver for terminals ( http://termsaver.info), so I would like to simulate the same behaviour of a standard screensaver for the X windows, by: - running on background - starting some functionality (display a text, etc) if there is no event (mouse or keyboard) for more than N minutes - stopping the above if there is any movement detected Any thoughts on this would be highly appreciated. Thanks! -- *Braga, Bruno* www.brunobraga.net bruno.braga at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue May 8 04:31:54 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 07 May 2012 22:31:54 -0400 Subject: [Tutor] Curious dictionary printing In-Reply-To: References: Message-ID: <4FA8859A.4030503@gmail.com> On 5/7/2012 1:16 PM, Cranky Frankie wrote: > In 3.2.2 in IDLE I have this dictionary entry: > > Namath = {"first_name": "Joe", "last_name": "Namath", "phone": "212-222-7777",\ > "email": "joe.namath at gmail.com", "stadium": "Shea Stadium"} > > when I print it: > > print(Namath) > > I get: > > {'phone': '212-222-7777', 'first_name': 'Joe', 'last_name': 'Namath', > 'email': 'joe.namath at gmail.com', 'stadium': 'Shea Stadium'} > > Why is it out of order? May I recommend a different approach to such questions. When you get an unexpected (undesired) result try saying - "Oh I see - that's how Python does it!" I want something different. How can I get it? Then try reading the documentation. Asking why does it not do what I want is not IMHO the best way to win friends here. Taking this steps further - what does it mean to be "in order". To some it is the order in which items are added rather than some collating sequence. - Do you want order by key or by value? - how would you order {1 : 'cat', "a": 3, (2,3): True}? -- Bob Gailer 919-636-4239 Chapel Hill NC From scubacuda at gmail.com Tue May 8 05:09:55 2012 From: scubacuda at gmail.com (Rogelio) Date: Mon, 7 May 2012 20:09:55 -0700 Subject: [Tutor] IPcount = 0 when used with subprocess.call (use something to convert to integer?) Message-ID: I am wrapping a Python wrapper script to "wc -l" (count lines) of a list of IP addresses ******************************************* import subprocess IPcount = subprocess.call(['wc -l file.txt | awk \'{print $1}\''], shell=True) print "You have",IPcount,"IP addresses that are alive." ******************************************* I get the following output ******************************************* 46 You have 0 IP addresses that are alive. ******************************************* Why does IPcount not equal 46? Is this what the stout is for? From scubacuda at gmail.com Tue May 8 06:06:12 2012 From: scubacuda at gmail.com (Rogelio) Date: Mon, 7 May 2012 21:06:12 -0700 Subject: [Tutor] IPcount = 0 when used with subprocess.call (use something to convert to integer?) In-Reply-To: References: Message-ID: On Mon, May 7, 2012 at 8:09 PM, Rogelio wrote: > Why does IPcount not equal 46? ?Is this what the stout is for? FWIW, I think this seems to fix it and make IPcount an integer. import os IPcount = os.popen("wc -l file.txt | awk '{print $1}'").read() print "You have",IPcount,"IP addresses that are alive." From kushal.kumaran+python at gmail.com Tue May 8 06:28:17 2012 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Tue, 8 May 2012 09:58:17 +0530 Subject: [Tutor] IPcount = 0 when used with subprocess.call (use something to convert to integer?) In-Reply-To: References: Message-ID: On Tue, May 8, 2012 at 8:39 AM, Rogelio wrote: > I am wrapping a Python wrapper script to "wc -l" (count lines) of a > list of IP addresses > > ******************************************* > > import subprocess > IPcount = subprocess.call(['wc -l file.txt | awk \'{print $1}\''], shell=True) > print "You have",IPcount,"IP addresses that are alive." > > ******************************************* > > I get the following output > > ******************************************* > 46 > You have 0 IP addresses that are alive. > ******************************************* > > Why does IPcount not equal 46? ?Is this what the stout is for? You can do this: http://docs.python.org/py3k/library/subprocess.html#replacing-bin-sh-shell-backquote However, for this simple action of counting lines in a file, I recommend you do it directly in python: def count_lines(filename): with open(f, 'r') as in_stream: return len(in_stream.readlines()) The count_lines function takes a filename and returns the number of lines in that file. This way you avoid the problems with shell metacharacters when using shell=True, mentioned in the subprocess documentation: http://docs.python.org/py3k/library/subprocess.html#frequently-used-arguments -- regards, kushal From steve at pearwood.info Tue May 8 07:14:10 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 8 May 2012 15:14:10 +1000 Subject: [Tutor] IPcount = 0 when used with subprocess.call (use something to convert to integer?) In-Reply-To: References: Message-ID: <20120508051410.GA3797@ando> On Mon, May 07, 2012 at 08:09:55PM -0700, Rogelio wrote: > import subprocess > IPcount = subprocess.call(['wc -l file.txt | awk \'{print $1}\''], shell=True) > print "You have",IPcount,"IP addresses that are alive." > > I get the following output > > 46 > You have 0 IP addresses that are alive. > > Why does IPcount not equal 46? Is this what the stout is for? Yes. The output of the call gets written to stdout. The return result of the call is 0 if the call succeeded and some other integer if it failed. -- Steven From questions.anon at gmail.com Tue May 8 08:07:15 2012 From: questions.anon at gmail.com (questions anon) Date: Tue, 8 May 2012 16:07:15 +1000 Subject: [Tutor] summary stats grouped by month year Message-ID: I would like to calculate summary statistics of rainfall based on year and month. I have the data in a text file (although could put in any format if it helps) extending over approx 40 years: YEAR MONTH MeanRain 1972 Jan 12.7083199 1972 Feb 14.17007142 1972 Mar 14.5659302 1972 Apr 1.508517302 1972 May 2.780009889 1972 Jun 1.609619287 1972 Jul 0.138150181 1972 Aug 0.214346148 1972 Sep 1.322102228 I would like to be able to calculate the total rain annually: YEAR Annualrainfall 1972 400 1973 300 1974 350 .... 2011 400 and also the monthly mean rainfall for all years: YEAR MonthlyMeanRain Jan 13 Feb 15 Mar 8 ..... Dec 13 Is this something I can easily do? I have started by simply importing the text file but data is not represented as time so that is probably my first problem and then I am not sure how to group them by month/year. textfile=r"textfile.txt" f=np.genfromtxt(textfile,skip_header=1) Any feedback will be greatly appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Tue May 8 08:41:41 2012 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Mon, 7 May 2012 23:41:41 -0700 Subject: [Tutor] summary stats grouped by month year In-Reply-To: References: Message-ID: <089D679A-8E0F-4880-A82B-70F78D9AEE85@gmail.com> Hello anonymous questioner, first comment - you may want to look into hdf5 data structures http://www.hdfgroup.org/HDF5/ and the python tools to play with them pytables - http://www.pytables.org/moin h5py - http://code.google.com/p/h5py/ I have personally used pytables more - but not for any good reason. If you happen to have the Enthought python distribution - these come with the package, as well as an installation of hdf5 hdf5 is a very nice file format for storing large amounts of data (binary) with descriptive meta-data. Also, numpy plays very nice with hdf5. Given all your questions here, I suspect you would benefit from learning about these and learning to play with them. Now to your specific question. > I would like to calculate summary statistics of rainfall based on year and month. > I have the data in a text file (although could put in any format if it helps) extending over approx 40 years: > YEAR MONTH MeanRain > 1972 Jan 12.7083199 > 1972 Feb 14.17007142 > 1972 Mar 14.5659302 > 1972 Apr 1.508517302 > 1972 May 2.780009889 > 1972 Jun 1.609619287 > 1972 Jul 0.138150181 > 1972 Aug 0.214346148 > 1972 Sep 1.322102228 > > I would like to be able to calculate the total rain annually: > > YEAR Annualrainfall > 1972 400 > 1973 300 > 1974 350 > .... > 2011 400 > > and also the monthly mean rainfall for all years: > > YEAR MonthlyMeanRain > Jan 13 > Feb 15 > Mar 8 > ..... > Dec 13 > > > Is this something I can easily do? Yes - this should be very easy. Imagine importing all this data into a numpy array === import numpy as np data = open(your_data).readlines() years = [] for line in data: if line.split()[0] not in years: years.append(line.split()[0]) months = ['Jan','Feb',....,'Dec'] rain_fall = np.zeros([len(n_year),len(months)]) for y,year in enumerate(years): for m,month in enumerate(months): rain_fall[y,m] = float(data[ y * 12 + m].split()[2]) # to get average per year - average over months - axis=1 print np.mean(rain_fall,axis=1) # to get average per month - average over years - axis=0 print np.mean(rain_fall,axis=0) === now you should imagine doing this by setting up dictionaries, so that you can request an average for year 1972 or for month March. That is why I used the enumerate function before to walk the indices - so that you can imagine building the dictionary simultaneously. years = {'1972':0, '1973':1, ....} months = {'Jan':0,'Feb':1,...'Dec':11} then you can access and store the data to the array using these dictionaries. print rain_fall[int('%(1984)s' % years), int('%(March)s' % months)] Andre > I have started by simply importing the text file but data is not represented as time so that is probably my first problem and then I am not sure how to group them by month/year. > > textfile=r"textfile.txt" > f=np.genfromtxt(textfile,skip_header=1) > > Any feedback will be greatly appreciated. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From bruno.braga at gmail.com Tue May 8 08:49:33 2012 From: bruno.braga at gmail.com (BRAGA, Bruno) Date: Tue, 8 May 2012 16:49:33 +1000 Subject: [Tutor] Curious dictionary printing In-Reply-To: <4FA8859A.4030503@gmail.com> References: <4FA8859A.4030503@gmail.com> Message-ID: Put it simple, dictionaries do not sort. You can use the dict.keys() to get a list of the dictionary keys, then sort them... there are lots of talks on this, just google a bit, and you will find fancy ways to do key or value sorting. -- *Braga, Bruno* www.brunobraga.net bruno.braga at gmail.com On Tue, May 8, 2012 at 12:31 PM, bob gailer wrote: > On 5/7/2012 1:16 PM, Cranky Frankie wrote: > >> In 3.2.2 in IDLE I have this dictionary entry: >> >> Namath = {"first_name": "Joe", "last_name": "Namath", "phone": " >> 212-222-7777",\ >> "email": "joe.namath at gmail.com", "stadium": "Shea Stadium"} >> >> when I print it: >> >> print(Namath) >> >> I get: >> >> {'phone': '212-222-7777', 'first_name': 'Joe', 'last_name': 'Namath', >> 'email': 'joe.namath at gmail.com', 'stadium': 'Shea Stadium'} >> >> Why is it out of order? >> > > May I recommend a different approach to such questions. > > When you get an unexpected (undesired) result try saying - "Oh I see - > that's how Python does it!" > > I want something different. How can I get it? > > Then try reading the documentation. > > Asking why does it not do what I want is not IMHO the best way to win > friends here. > > Taking this steps further > - what does it mean to be "in order". To some it is the order in which > items are added rather than some collating sequence. > - Do you want order by key or by value? > - how would you order {1 : 'cat', "a": 3, (2,3): True}? > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > ______________________________**_________________ > 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 shantanoo at gmail.com Tue May 8 09:16:00 2012 From: shantanoo at gmail.com (=?UTF-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Tue, 8 May 2012 12:46:00 +0530 Subject: [Tutor] summary stats grouped by month year In-Reply-To: References: Message-ID: Python generally comes with support for sqlite3. you can store your date in to sqlite db and then try running sql query for finding of the details. select year, sum(MeanRain) where year='1972' group by year; select month, sum(MeanRain) where month='Jan' group by month; ** Not sure regarding the exact sql query. sum function and 'group by' is important. On Tue, May 8, 2012 at 11:37 AM, questions anon wrote: > I would like to calculate summary statistics of rainfall based on year and > month. > I have the data in a text file (although could put in any format if it > helps) extending over approx 40 years: > YEAR MONTH??? MeanRain > 1972 Jan??? 12.7083199 > 1972 Feb??? 14.17007142 > 1972 Mar??? 14.5659302 > 1972 Apr??? 1.508517302 > 1972 May??? 2.780009889 > 1972 Jun??? 1.609619287 > 1972 Jul??? 0.138150181 > 1972 Aug??? 0.214346148 > 1972 Sep??? 1.322102228 > > I would like to be able to calculate the total rain annually: > > YEAR?? Annualrainfall > 1972??? 400 > 1973??? 300 > 1974??? 350 > .... > 2011???? 400 > > and also the monthly mean rainfall for all years: > > YEAR? MonthlyMeanRain > Jan????? 13 > Feb????? 15 > Mar?????? 8 > ..... > Dec ????? 13 > > > Is this something I can easily do? > I have started by simply importing the text file but data is not represented > as time so that is probably my first problem and then I am not sure how to > group them by month/year. > > textfile=r"textfile.txt" > f=np.genfromtxt(textfile,skip_header=1) > > Any feedback will be greatly appreciated. > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From shantanoo at gmail.com Tue May 8 09:43:39 2012 From: shantanoo at gmail.com (=?UTF-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Tue, 8 May 2012 13:13:39 +0530 Subject: [Tutor] summary stats grouped by month year In-Reply-To: References: Message-ID: On Tue, May 8, 2012 at 12:46 PM, ????? wrote: > Python generally comes with support for sqlite3. > > you can store your date in to sqlite db and then try running sql query > for finding of the details. data not date. > > select year, sum(MeanRain) where year='1972' group by year; > select month, sum(MeanRain) where month='Jan' group by month; > > ** Not sure regarding the exact sql query. sum function and 'group by' > is important. > > On Tue, May 8, 2012 at 11:37 AM, questions anon > wrote: >> I would like to calculate summary statistics of rainfall based on year and >> month. >> I have the data in a text file (although could put in any format if it >> helps) extending over approx 40 years: >> YEAR MONTH??? MeanRain >> 1972 Jan??? 12.7083199 >> 1972 Feb??? 14.17007142 >> 1972 Mar??? 14.5659302 >> 1972 Apr??? 1.508517302 >> 1972 May??? 2.780009889 >> 1972 Jun??? 1.609619287 >> 1972 Jul??? 0.138150181 >> 1972 Aug??? 0.214346148 >> 1972 Sep??? 1.322102228 >> >> I would like to be able to calculate the total rain annually: >> >> YEAR?? Annualrainfall >> 1972??? 400 >> 1973??? 300 >> 1974??? 350 >> .... >> 2011???? 400 >> >> and also the monthly mean rainfall for all years: >> >> YEAR? MonthlyMeanRain >> Jan????? 13 >> Feb????? 15 >> Mar?????? 8 >> ..... >> Dec ????? 13 >> >> >> Is this something I can easily do? >> I have started by simply importing the text file but data is not represented >> as time so that is probably my first problem and then I am not sure how to >> group them by month/year. >> >> textfile=r"textfile.txt" >> f=np.genfromtxt(textfile,skip_header=1) >> >> Any feedback will be greatly appreciated. >> >> >> _______________________________________________ >> 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 Tue May 8 09:59:40 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 May 2012 08:59:40 +0100 Subject: [Tutor] Console Application - Key Events In-Reply-To: References: Message-ID: On 08/05/12 02:44, BRAGA, Bruno wrote: > I would like to know if there is any "easy" way to handle events (such > as mouse movements, keyboard keys pressed, etc) in console based python > applications? You need to be more specific about what you mean. Consoles don't have mice. Keyboard events are easily handled (see my tutorial on event driven apps for more info and examples) You may be confusing the concept of a console running inside a window of a GUI system. In that case the window receives events and the window manager can handle them. But the python application running inside that terminal emulator is completely unaware of them. There are also event driven frameworks for consoles that can capture events (Borland had one such for DOS), but it is the framework not Python that is aware of these things. > More specifically, I am working on a screensaver for terminals > (http://termsaver.info), so I would like to simulate the same behaviour > of a standard screensaver for the X windows, by: What is this screensaver going to do? Display an alternative screen full of text? Go blank? > * running on background > * starting some functionality (display a text, etc) if there is no > event (mouse or keyboard) for more than N minutes > * stopping the above if there is any movement detected It is possible to do some of that in a multi process environment by running an application in the background, but you would need some kind of cooperative behaviour from the foreground app I suspect. Which limits applicability. But the biggest problem you face is just that consoles generally do not have any kind of event awareness. Mice etc just don't exist. They are not event based. And where the terminal emulator is event aware (eg xterm on Linux) the events are not passed on to the app except in very limited circumstances - eg pasting from a mouse selection - and that is usually just a case of injecting the selected text into stdin. And that is deliberate since the apps need to be able to work in real dumb terminals (VT100 etc) or even teletypes. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From xancorreu at gmail.com Tue May 8 12:23:46 2012 From: xancorreu at gmail.com (xancorreu) Date: Tue, 08 May 2012 12:23:46 +0200 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> <4FA832A2.5000901@gmail.com> Message-ID: <4FA8F432.1010904@gmail.com> Al 08/05/12 01:24, En/na Alan Gauld ha escrit: > On 07/05/12 21:37, xancorreu wrote: > >> This is the code: > > OK, But it's not clear from that why you want the type. > You are not doing anything meaningful with the type. > >> class Tag: >> >> def __init__(self, nom, tipus, valor): >> self.nom = nom >> self.tipus = tipus >> self.valor = valor >> >> def __str__(self): >> return "Nom: " + str(self.nom) + ", Tipus: " + str(self.tipus) + ", >> Valor: " + str(self.valor) > > > You store it then print the string version of it. > Why not just pass a string name? > >> def main(): >> a = Tag("descripci?", str, "primera tasca") >> b = Tag("unmes", str, lambda x: x+1) >> c = Tag("twice", type(lambda: x: x), lambda x: 2*x) > >> and it fails here: >> >> $ python3 tasques.py >> File "tasques.py", line 26 >> c = Tag("twice", type(lambda: x: x), lambda x: 2*x) >> ^ >> SyntaxError: invalid syntax > > > As it says there is a syntax error. Look at your two lambda > expressions, the second one has an extra : Thanks a lot, It works with c = Tag("twice", type(lambda x: x), lambda x: 2*x) but I want to specify the type of (lambda x: x) **manually** as I do with str in b Thanks From cranky.frankie at gmail.com Tue May 8 13:27:48 2012 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 8 May 2012 07:27:48 -0400 Subject: [Tutor] Curious dictionary printing In-Reply-To: <4FA8859A.4030503@gmail.com> References: <4FA8859A.4030503@gmail.com> Message-ID: On Mon, May 7, 2012 at 10:31 PM, bob gailer wrote: > Asking why does it not do what I want is not IMHO the best way to win > friends here. Good morning to you to, Bob. I see now that dictionaries in Python act like relational databases in that there is no inherent ordering. At first, when I simply wanted to print one entry and it came out in what looked like a random order, this didn't occur to me. A normal "dictionary" is in fact ordered. Sorry for the disturbance. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?The problem with quotes on the Internet is that it is often difficult to verify their authenticity.? - Abraham Lincoln From d at davea.name Tue May 8 13:58:47 2012 From: d at davea.name (Dave Angel) Date: Tue, 08 May 2012 07:58:47 -0400 Subject: [Tutor] Curious dictionary printing In-Reply-To: References: <4FA8859A.4030503@gmail.com> Message-ID: <4FA90A77.8010602@davea.name> On 05/08/2012 07:27 AM, Cranky Frankie wrote: > On Mon, May 7, 2012 at 10:31 PM, bob gailer wrote: > >> Asking why does it not do what I want is not IMHO the best way to win >> friends here. > Good morning to you to, Bob. > > I see now that dictionaries in Python act like relational databases in > that there is no inherent ordering. At first, when I simply wanted to > print one entry and it came out in what looked like a random order, > this didn't occur to me. A normal "dictionary" is in fact ordered. > > Sorry for the disturbance. > I wouldn't relate it to a "normal dictionary," but to other programming constructs. A dictionary is a mapping between key and value, where once a key/value pair has been stored, it may be retrieved by supplying the key. There are two common implementations in various programming languages and environments. In C++, for example, the std::map is ordered, and does a binary search for each lookup. Thus the lookup is O(log n). Boost adds a unordered_map (it may be in the C++ standard by now, but I haven't checked). So it has a lookup time of O(1), which is faster. Sometimes an ordered map is more useful than the other, but an unordered map is generally faster (especially for large maps), and works with unorderable keys. Since Python chose to include only one native to the language, I think it made the better choice, especially since it uses it heavily for its own namespace lookups. -- DaveA From scubacuda at gmail.com Tue May 8 16:18:33 2012 From: scubacuda at gmail.com (Rogelio) Date: Tue, 8 May 2012 07:18:33 -0700 Subject: [Tutor] using subprocess to export files in bash Message-ID: While reading the subprocess documentation, I found a great example on how to call commands with a PIPE http://docs.python.org/library/subprocess.html ************************** output=`dmesg | grep hda` # becomes p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] **************************** How do I do this and output to a file? e.g. output = "dmesg | grep hda > log.txt' From glenbot at gmail.com Tue May 8 16:20:46 2012 From: glenbot at gmail.com (Glen Zangirolami) Date: Tue, 8 May 2012 09:20:46 -0500 Subject: [Tutor] Curious dictionary printing In-Reply-To: References: <4FA8859A.4030503@gmail.com> Message-ID: Frankie, Dictionaries do not sort in python because it's much faster to leave it unordered and most of the time it isn't necessary. If you really need ordered dictionaries you can use http://pypi.python.org/pypi/ordereddict for Python <2.7. If you are using python 2.7+ then you can import it from collections. See http://docs.python.org/library/collections.html#collections.OrderedDict Hope this helps. Glen On Tue, May 8, 2012 at 6:27 AM, Cranky Frankie wrote: > On Mon, May 7, 2012 at 10:31 PM, bob gailer wrote: > > > Asking why does it not do what I want is not IMHO the best way to win > > friends here. > > Good morning to you to, Bob. > > I see now that dictionaries in Python act like relational databases in > that there is no inherent ordering. At first, when I simply wanted to > print one entry and it came out in what looked like a random order, > this didn't occur to me. A normal "dictionary" is in fact ordered. > > Sorry for the disturbance. > > -- > Frank L. "Cranky Frankie" Palmeri > Risible Riding Raconteur & Writer > ?The problem with quotes on the Internet is that > it is often difficult to verify their authenticity.? > - Abraham Lincoln > _______________________________________________ > 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 bruno.braga at gmail.com Tue May 8 16:23:43 2012 From: bruno.braga at gmail.com (BRAGA, Bruno) Date: Wed, 9 May 2012 00:23:43 +1000 Subject: [Tutor] using subprocess to export files in bash In-Reply-To: References: Message-ID: No idea why you would want to do that (looks more complicated in python than in bash, right?)... but: f = open("log.txt", "w") f.write(output) f.close() -- *Braga, Bruno* www.brunobraga.net bruno.braga at gmail.com On Wed, May 9, 2012 at 12:18 AM, Rogelio wrote: > While reading the subprocess documentation, I found a great example on > how to call commands with a PIPE > > http://docs.python.org/library/subprocess.html > > ************************** > output=`dmesg | grep hda` > # becomes > p1 = Popen(["dmesg"], stdout=PIPE) > p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) > p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. > output = p2.communicate()[0] > > **************************** > > How do I do this and output to a file? > > e.g. > > output = "dmesg | grep hda > log.txt' > _______________________________________________ > 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 ramit.prasad at jpmorgan.com Tue May 8 18:17:25 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 8 May 2012 16:17:25 +0000 Subject: [Tutor] IPcount = 0 when used with subprocess.call (use something to convert to integer?) In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4740930AED3@SCACMX008.exchad.jpmchase.net> > def count_lines(filename): > with open(f, 'r') as in_stream: > return len(in_stream.readlines()) > > The count_lines function takes a filename and returns the number of > lines in that file. This way you avoid the problems with shell > metacharacters when using shell=True, mentioned in the subprocess > documentation: > http://docs.python.org/py3k/library/subprocess.html#frequently-used- > arguments > Or for large files where you do not want to read the entire file to memory at the same time (assuming Python 2.x; not sure if 3.x stops the variable leakage I use here) def count_lines(filename): with open(f, 'r') as in_stream: idx = 0 for idx, line in enumerate(in_stream, 1): pass return idx Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Tue May 8 18:11:38 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 8 May 2012 16:11:38 +0000 Subject: [Tutor] Displaying data in columns In-Reply-To: References: <20120507214331.047a57d9@midgel> Message-ID: <5B80DD153D7D744689F57F4FB69AF4740930AEA7@SCACMX008.exchad.jpmchase.net> > > I would like to display some of the items in the tuples in columnar > > format with each column lining up on the left side (below should be > > three neat columns with location, training type, number trained and > > date): > > You need to read up on string formatting. That allows you to specify the > length of fields, whether they are left or right justified, any leading > pad characters etc. This is not in a module but is a standard feature of > Python. > > > For anything more exotic you should look to a formatting language > like HTML. > > You have already gotten links for string interpolation. There is the link for string formatting. http://docs.python.org/library/string.html#format-string-syntax Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Tue May 8 19:36:30 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 May 2012 18:36:30 +0100 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: <4FA8F432.1010904@gmail.com> References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> <4FA832A2.5000901@gmail.com> <4FA8F432.1010904@gmail.com> Message-ID: On 08/05/12 11:23, xancorreu wrote: > It works with > > c = Tag("twice", type(lambda x: x), lambda x: 2*x) > > but I want to specify the type of (lambda x: x) **manually** as I do > with str in b Unfortunately we don't always get what we want. You have to use type for functions. You can use a very simple function, but you need to use type()... type(lambda : 0) is about as simple as you can do it with lambda... However, you still haven't said why you want the type. It's very unusual in Python to need explicit type information. If we knew what you were trying to do with it we might be able to offer a more pythonic way to go about it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue May 8 19:41:42 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 May 2012 18:41:42 +0100 Subject: [Tutor] using subprocess to export files in bash In-Reply-To: References: Message-ID: On 08/05/12 15:18, Rogelio wrote: > While reading the subprocess documentation, I found a great example on > how to call commands with a PIPE > > http://docs.python.org/library/subprocess.html > > ************************** > output=`dmesg | grep hda` > # becomes > p1 = Popen(["dmesg"], stdout=PIPE) > p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) > p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. > output = p2.communicate()[0] > > **************************** > > How do I do this and output to a file? Have you tried defining stdout in the second command to be a file? log = open('log.txt','w') p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=log) ... log.close() I haven't tried but I think that should work... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From david at pythontoo.com Tue May 8 20:06:03 2012 From: david at pythontoo.com (David Abbott) Date: Tue, 8 May 2012 14:06:03 -0400 Subject: [Tutor] using subprocess to export files in bash In-Reply-To: References: Message-ID: On Tue, May 8, 2012 at 1:41 PM, Alan Gauld wrote: > On 08/05/12 15:18, Rogelio wrote: >> >> While reading the subprocess documentation, I found a great example on >> how to call commands with a PIPE >> >> http://docs.python.org/library/subprocess.html >> >> ************************** >> output=`dmesg | grep hda` >> # becomes >> p1 = Popen(["dmesg"], stdout=PIPE) >> p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) >> p1.stdout.close() ?# Allow p1 to receive a SIGPIPE if p2 exits. >> output = p2.communicate()[0] >> >> **************************** >> >> How do I do this and output to a file? > > > Have you tried defining stdout in the second command to be a file? > > log = open('log.txt','w') > p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=log) > ... > log.close() > > I haven't tried but I think that should work... > > -- > Alan G > 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 I have used this before; def uptime_report(): """Generate uptime""" p = subprocess.Popen("uptime > /tmp/uptime.txt", shell=True, stdout=subprocess.PIPE) return p.stdout.readlines() That was from python 2.6 From xancorreu at gmail.com Tue May 8 20:31:41 2012 From: xancorreu at gmail.com (xancorreu) Date: Tue, 08 May 2012 20:31:41 +0200 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> <4FA832A2.5000901@gmail.com> <4FA8F432.1010904@gmail.com> Message-ID: <4FA9668D.3020908@gmail.com> Al 08/05/12 19:36, En/na Alan Gauld ha escrit: > On 08/05/12 11:23, xancorreu wrote: > >> It works with >> >> c = Tag("twice", type(lambda x: x), lambda x: 2*x) >> >> but I want to specify the type of (lambda x: x) **manually** as I do >> with str in b > > > Unfortunately we don't always get what we want. > You have to use type for functions. > > You can use a very simple function, but you need to use type()... > > type(lambda : 0) > > is about as simple as you can do it with lambda... A much pain for me. I think there should be a type.function avaliable in python, like str, int, etc. exists. I think as python is O-O language and have (or at least the page says that) higher-order function, I should could type: isinstance(2, function) like I do isinstance(2, int) Do you understand my reasoning? > > However, you still haven't said why you want the type. It's very > unusual in Python to need explicit type information. If we knew what > you were trying to do with it we might be able to offer a more > pythonic way to go about it. > > Yes, I know that the pythonic way is to not define types in variables. The variables are free while there is no assign to these. I need type because I want to implement Tag as triple of name, type and value. I want to differentiate between a tag with type str and value "today" and a tag with tag with type data and value "today". That's all. Thanks for the answer. Xan. From emile at fenx.com Tue May 8 20:42:32 2012 From: emile at fenx.com (Emile van Sebille) Date: Tue, 08 May 2012 11:42:32 -0700 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: <4FA9668D.3020908@gmail.com> References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> <4FA832A2.5000901@gmail.com> <4FA8F432.1010904@gmail.com> <4FA9668D.3020908@gmail.com> Message-ID: On 5/8/2012 11:31 AM xancorreu said... > isinstance(2, function) > > like I do > > isinstance(2, int) > > > > Do you understand my reasoning? Nope, but here ya go: Python 2.6.4rc2 (r264rc2:75497, Oct 20 2009, 02:55:11) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from types import * >>> dir() ['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', '__doc__', '__name__', '__package__'] >>> def test():pass ... >>> >>> function=FunctionType >>> print isinstance(test,function) >>> From wprins at gmail.com Tue May 8 21:11:01 2012 From: wprins at gmail.com (Walter Prins) Date: Tue, 8 May 2012 20:11:01 +0100 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: <4FA9668D.3020908@gmail.com> References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> <4FA832A2.5000901@gmail.com> <4FA8F432.1010904@gmail.com> <4FA9668D.3020908@gmail.com> Message-ID: On 8 May 2012 19:31, xancorreu wrote: > A much pain for me. I think there should be a type.function avaliable in > python, like str, int, etc. exists. I think as python is O-O language and > have (or at least the page says that) higher-order function, I should could > type: > Just define 'function' as being the type of (a) function. Any function will do. This will fix your problem eg: def main(): function = type(main) a = Tag("descripci?", str, "primera tasca") b = Tag("unmes", function, lambda x: x+1) print(a) print(b) I used "main" but you can use whatever you like. It sounds to me however as though your type system may be (at least partially) independent of the real (python) type of whatever you're storing. If so, I'd actualy suggest you explicitly define your own type system and tag your objects accordingly. (E.g. create your own variant of the 'types' module and use those types as appropriate.) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.charonis at gmail.com Tue May 8 22:00:17 2012 From: s.charonis at gmail.com (Spyros Charonis) Date: Tue, 8 May 2012 21:00:17 +0100 Subject: [Tutor] List Indexing Issue Message-ID: Hello python community, I'm having a small issue with list indexing. I am extracting certain information from a PDB (protein information) file and need certain fields of the file to be copied into a list. The entries look like this: ATOM 1512 N VAL A 222 8.544 -7.133 25.697 1.00 48.89 N ATOM 1513 CA VAL A 222 8.251 -6.190 24.619 1.00 48.64 C ATOM 1514 C VAL A 222 9.528 -5.762 23.898 1.00 48.32 C I am using the following syntax to parse these lines into a list: charged_res_coord = [] # store x,y,z of extracted charged resiudes for line in pdb: if line.startswith('ATOM'): atom_coord.append(line) for i in range(len(atom_coord)): for item in charged_res: if item in atom_coord[i]: charged_res_coord.append(atom_coord[i].split()[1:9]) The problem begins with entries such as the following. ROW1) ATOM 1572 NH2 ARG A 228 7.890 -13.328 16.363 1.00 59.63 N ROW2) ATOM 1617 N GLU A1005 11.906 -2.722 7.994 1.00 44.02 N Here, the code that I use to extract the third spatial coordinate (the last of the three consecutive non-integer values) produces a problem: because 'A1005' (second row) is considered as a single list entry, while 'A' and '228' (first row) are two list entries, when I use a loop to index the 7th element it extracts '16.363' (entry I want) for first row and 1.00 (not entry I want) for the second row. >>> charged_res_coord[1] ['1572', 'NH2', 'ARG', 'A', '228', '7.890', '-13.328', '16.363'] >>> charged_res_coord[10] ['1617', 'N', 'GLU', 'A1005', '11.906', '-2.722', '7.994', '1.00'] The loop I use goes like this: for i in range(len(lys_charged_group)): lys_charged_group[i][7] = float(lys_charged_group[i][7]) The [7] is the problem - in lines that are like ROW1 the code extracts the correct value, but in lines that are like ROW2 the code extracts the wrong value. Unfortunately, the different formats of rows are interspersed so I don't know if I can solve this using text processing routines? Would I have to use regular expressions? Many thanks for your help! Spyros -------------- next part -------------- An HTML attachment was scrubbed... URL: From xancorreu at gmail.com Tue May 8 22:29:20 2012 From: xancorreu at gmail.com (xancorreu) Date: Tue, 08 May 2012 22:29:20 +0200 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> <4FA832A2.5000901@gmail.com> <4FA8F432.1010904@gmail.com> <4FA9668D.3020908@gmail.com> Message-ID: <4FA98220.8000804@gmail.com> Al 08/05/12 20:42, En/na Emile van Sebille ha escrit: > On 5/8/2012 11:31 AM xancorreu said... >> isinstance(2, function) >> >> like I do >> >> isinstance(2, int) >> >> >> >> Do you understand my reasoning? > > Nope, but here ya go: > > Python 2.6.4rc2 (r264rc2:75497, Oct 20 2009, 02:55:11) > [GCC 4.4.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> from types import * > >>> dir() > ['BooleanType', 'BufferType', 'BuiltinFunctionType', > 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', > 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', > 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', > 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', > 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', > 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', > 'SliceType', 'StringType', 'StringTypes', 'TracebackType', > 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', > 'XRangeType', '__builtins__', '__doc__', '__name__', '__package__'] > >>> def test():pass > ... > >>> > >>> function=FunctionType > >>> print isinstance(test,function) > >>> > > A BIG thank you. Thanks, From joel.goldstick at gmail.com Tue May 8 22:33:03 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 8 May 2012 16:33:03 -0400 Subject: [Tutor] List Indexing Issue In-Reply-To: References: Message-ID: On Tue, May 8, 2012 at 4:00 PM, Spyros Charonis wrote: > Hello python community, > > I'm having a small issue with list indexing. I am extracting certain > information from a PDB (protein information) file and need certain fields of > the file to be copied into a list. The entries look like this: > > ATOM ? 1512 ?N ? VAL A 222 ? ? ? 8.544 ?-7.133 ?25.697 ?1.00 48.89 > N > ATOM ? 1513 ?CA ?VAL A 222 ? ? ? 8.251 ?-6.190 ?24.619 ?1.00 48.64 > C > ATOM ? 1514 ?C ? VAL A 222 ? ? ? 9.528 ?-5.762 ?23.898 ?1.00 48.32 > C > > I am using the following syntax to parse these lines into a list: > > charged_res_coord = [] # store x,y,z of extracted charged resiudes > for line in pdb: > if line.startswith('ATOM'): > atom_coord.append(line) > > for i in range(len(atom_coord)): > for item in charged_res: > if item in atom_coord[i]: > charged_res_coord.append(atom_coord[i].split()[1:9]) > > > The problem begins with entries such as the following. > > ROW1) ? ATOM ? 1572 ?NH2 ARG A 228 ? ? ? 7.890 -13.328 ?16.363 ?1.00 59.63 > ? ? ? ? N > > ROW2) ? ATOM ? 1617 ?N ? GLU A1005 ? ? ?11.906 ?-2.722 ? 7.994 ?1.00 44.02 > ? ? ? ? N > > Here, the code that I use to extract the third spatial coordinate (the last > of the three consecutive non-integer values) produces a problem: > > because 'A1005' (second row) is considered as a single list entry, while 'A' > and '228' (first row) are two list entries, when I > use a loop to index the 7th element it extracts '16.363' (entry I want) for > first row and 1.00 (not entry I want) for the second row. > >>>> charged_res_coord[1] > ['1572', 'NH2', 'ARG', 'A', '228', '7.890', '-13.328', '16.363'] > >>>> charged_res_coord[10] > ['1617', 'N', 'GLU', 'A1005', '11.906', '-2.722', '7.994', '1.00'] > > > The loop I use goes like this: > > for i in range(len(lys_charged_group)): > lys_charged_group[i][7] = float(lys_charged_group[i][7]) > > The [7] is the problem - in lines that are like ROW1 the code extracts the > correct value, > but in lines that are like ROW2 the code extracts the wrong value. > Unfortunately, the different formats of rows are interspersed > so I don't know if I can solve this using text processing routines? Would I > have to use regular expressions? > > Many thanks for your help! > > Spyros > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I think regular expressions get overused. They're great, but they can get hard to understand. Python has good built in string functions. For your case you might want to look at this: replace( str, old, new[, maxsplit]) Return a copy of string str with all occurrences of substring old replaced by new. If the optional argument maxsplit is given, the first maxsplit occurrences are replaced. You could Replace " A " with " A" which would then leave all your 4th items like Annnn. If you don't want the A in your results do row[3][1:] to get everything after the A Not a full solution, but check out the built in string capabilities of python. There is a lot there -- Joel Goldstick From benderjacob44 at gmail.com Tue May 8 23:23:03 2012 From: benderjacob44 at gmail.com (Jacob Bender) Date: Tue, 8 May 2012 17:23:03 -0400 Subject: [Tutor] Sorting the Parts of a Dictionary into a List Message-ID: Dear Tutors, My original email was this: "Dear tutors, I'm trying to create a neural network program. Each neuron is in a dictionary and each of its connections and their strengths are in a nested dictionary. So {0:{1:4, 2:5}}, 1:{0:6}, 2:{1:2}} would mean that neuron 0 is connected to neuron 1 with a strength of 4. And it also means that neuron 1 is connected to neuron 0 with a strength of 6. The problem is that I'm working on a function that is supposed to add the total strengths of each neuron. So, for example, neuron 0's connections have a total strength of 9 (4+5). The other problem is getting all of the total strengths and ordering the neurons into a list. So, from the example, the list would be from [0,1,2] because zero has the greatest total strength of 9, then 1 with a total strength of 6 and so on. I've been working on this problem for at least 2 hours now and still haven't found anything close to a solution." And here's my source code: class neuron(object): def __init__(self): self.neurons = {} self.neuron_total = 0 def create_neurons(self, number): for i in range(number): self.neuron_total += 1 self.neurons[self.neuron_total] = {} def connect_neurons(self,connecter,connectee): try: self.neurons[connecter][connectee] += 1 except(KeyError): try: self.neurons[connecter][connectee] = 1 except(KeyError): self.neurons[connecter] = {connectee:1} def ping(self,neuron,choice): if choice == True: #If the neuron pinged needs to choose only one neuron most_connected = 0 for connections in self.neurons[neuron]: if max(str(self.neurons[neuron][connections])) > most_connected: most_connected = connections else: pass return most_connected else: for neuron in self.neurons: for connections in self.neurons[choice]: return connections def total(self, neuron): total = 0 for connection in self.neurons[neuron]: total = total+self.neurons[neuron][connection] def smartest(self): #Return the neurons in order from smartest to dumbest in list form. for neuron in self.neurons: sorted(neuron, key=self.total(neuron)) The total function works when it returns the strength of a neuron, but I don't think the "sorted" function is the best because, with its current configuration, it returns a type error. I have been doing python for several years now. I don't know EVERYTHING there is to know, but I am able to do most tasks without error. Please help me get the neurons into an order in a list as described in my original email. Also, I do thank you for your original replies! -- Thank you, Jacob -------------- next part -------------- An HTML attachment was scrubbed... URL: From benderjacob44 at gmail.com Tue May 8 23:27:29 2012 From: benderjacob44 at gmail.com (Jacob Bender) Date: Tue, 8 May 2012 17:27:29 -0400 Subject: [Tutor] Sorting a dictionary into a list cont'd Message-ID: Oh, and here's the error my program returns when it runs: Traceback (most recent call last): File "/home/jacob/Dropbox/Shared_With_Chris_And_Logan/Jake's Programs/Yet_To_Work_On/Synaptic/synaptic.py", line 57, in neuron.smartest() File "/home/jacob/Dropbox/Shared_With_Chris_And_Logan/Jake's Programs/Yet_To_Work_On/Synaptic/synaptic.py", line 50, in smartest sorted(neuron, key=self.total(neuron)) TypeError: 'int' object is not iterable -- Thank you, Jacob -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue May 8 23:32:41 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 8 May 2012 21:32:41 +0000 Subject: [Tutor] Sorting a dictionary into a list cont'd In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4740930B850@SCACMX008.exchad.jpmchase.net> > Oh, and here's the error my program returns when it runs: > > Traceback (most recent call last): > File "/home/jacob/Dropbox/Shared_With_Chris_And_Logan/Jake's > Programs/Yet_To_Work_On/Synaptic/synaptic.py", line 57, in > neuron.smartest() > File "/home/jacob/Dropbox/Shared_With_Chris_And_Logan/Jake's > Programs/Yet_To_Work_On/Synaptic/synaptic.py", line 50, in smartest > sorted(neuron, key=self.total(neuron)) Try changing the above line to sorted(neuron, key=self.total) where self.total should a function taking one element from the list neuron. > TypeError: 'int' object is not iterable Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From dwbarne at gmail.com Tue May 8 23:53:25 2012 From: dwbarne at gmail.com (Daniel Barnette) Date: Tue, 8 May 2012 15:53:25 -0600 Subject: [Tutor] PYLOTDB open source MySQL database management and analysis tool now available Message-ID: Many readers have asked whether there's Python GUI software for creating, managing, and analyzing MySQL databases. I have just released such software as completely open source. Source code is available on GitHub as follows: 1. Install Git on your machine from github.com 2. Initialize the target directory with "git init" 3. Download the software using "git pull git://github.com/dwbarne/PYLOTDB" 4. Read README_first.rtf file using Microsoft Word and follow directions. PYLOTDB consists of two codes, PylotDB and Co-PylotDB. The software allows users to access either local or remote MySQL servers and easily display table data in a GUI format. In PylotDB, data can be filtered, and table columns are indexed with radiobuttons and checkboxes so data can be easily selected for plotting or statistical analysis. Plotting capability includes X-Y, semi-log, log-log, Kiviat (radar charts), scatter, and scatter with polynomial curve fits of the data. Entire databases, selected databases, or selected tables in selected databases can be backed up and restored as desired. Interfaces are provided for individual entry edits and additions. PylotDB's companion software Co-PylotDB is used to send data files to a user-selected database table. If data files are in YAML format, PylotDB can automatically extract each entry in the file, expand the database table with new fields with names taken from the YAML entries, and insert the data in those fields for plotting and analysis. This is a tremendous time saver for analysts. This allows the cycle of "data capture to storage to analysis" to be completed in a matter of minutes. A powerful feature of PylotDB is the storage buffer where selected data from any table on any server can be stored and mathematically combined to generate new data not currently in any accessed table. The new data can then be plotted along with other data from the currently displayed table. This allows the user to generate desired data on the fly without the necessity of modifying any of the stored tables. PYLOTDB's dependencies include matplotlib, numpy, MySQLdb, Python MegaWidgets (Pmw), and YAML. All of these dependencies are included in the download for Windows machines only. They can easily be found on the web for Mac or Linux machines. Sample databases are also included to help users get up to speed quickly. We are using this software in my company for analyzing results from our computer performance modeling analysis, but it can be used for any type of analysis where database storage and analysis is desired. Hope this proves helpful for your readers. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed May 9 00:06:44 2012 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 8 May 2012 23:06:44 +0100 (BST) Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: <4FA9668D.3020908@gmail.com> References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> <4FA832A2.5000901@gmail.com> <4FA8F432.1010904@gmail.com> <4FA9668D.3020908@gmail.com> Message-ID: <1336514804.81053.YahooMailNeo@web87706.mail.ir2.yahoo.com> > > type(lambda : 0) >> > >> > is about as simple as you can do it with lambda... >> >> ...I think there should be a type.function avaliable in python, like str, int, etc. exists.? But there are many different function like objects just? as there are many different types of number. ?Python does? not have a type.number either. Instead of > isinstance(2, function)you can do: callable(2) which will check if 2 is any kind of callable object? - function, method, class etc. That is usually much more useful that getting the type. isinstance() does not of course return the type it tells? you if the object is an instance of the class or any? of its its subclasses: >>> class C: pass ...? >>> class B(C):pass ...? >>> c = C() >>> b = B() >>> isinstance(c,C) True >>> isinstance(b,C) True >>> isinstance(b,B) True >>> isinstance(c,B) False >>>? callable works the same way in that it tests whether you? can call the name. Which is usually all you care about. > Yes, I know that the pythonic way is to not define types in variables.? >> The variables are free while there is no assign to these. I need type because I want to implement? >> Tag as triple of name, type and value. I want to differentiate between a tag with type str and? >> value "today" and a tag with tag with type data and value "today". But why? Doing so will greatly reduce the flexibility of your? class. Far better to build?Tag such that it works with any? object type. Why would you need to know the type? There are a very few scenarios where the type is genuinely? important (serialisation of data is one case) but in many? cases you just don't need to know. Alan G -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed May 9 00:14:05 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 May 2012 23:14:05 +0100 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> <4FA832A2.5000901@gmail.com> <4FA8F432.1010904@gmail.com> <4FA9668D.3020908@gmail.com> Message-ID: On 08/05/12 19:42, Emile van Sebille wrote: > >>> from types import * > >>> dir() > ['BooleanType', 'BufferType', 'BuiltinFunctionType', > 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', > 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', > 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', > 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', > 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', > 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', > 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', > 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', > '__builtins__', '__doc__', '__name__', '__package__'] > >>> def test():pass > ... > >>> > >>> function=FunctionType > >>> print isinstance(test,function) Wow, thanks for that. I knew about all the different function types in there but hadn't realised that FunctionType was the grandaddy of them all... although I should probably have guessed there would be a parent class. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Wed May 9 00:23:55 2012 From: d at davea.name (Dave Angel) Date: Tue, 08 May 2012 18:23:55 -0400 Subject: [Tutor] Sorting the Parts of a Dictionary into a List In-Reply-To: References: Message-ID: <4FA99CFB.2090907@davea.name> On 05/08/2012 05:23 PM, Jacob Bender wrote: > > > > def smartest(self): #Return the neurons in order from smartest to > dumbest in list form. > for neuron in self.neurons: > sorted(neuron, key=self.total(neuron)) > > The total function works when it returns the strength of a neuron, but I > don't think the "sorted" function is the best because, with its current > configuration, it returns a type error. I have been doing python for > several years now. I don't know EVERYTHING there is to know, but I am able > to do most tasks without error. Please help me get the neurons into an > order in a list as described in my original email. Also, I do thank you for > your original replies! > > You put your error traceback in a separate thread. Please use reply(-all) to keep the related messages in one place. Without trying to really understand the rest of the code, this last function is messed up in many ways. So I'll suggest something that makes it plausible, but not necessarily what the rest of the code wants. if you're going to sort something with sort() or sorted(), you don't do that inside a loop. You sort the list directly, in a single operation. And if you want to return something you need a return statement. If you're passing a key function into the sorted() function, you want to pass the function object, not the result of calling it once (ie. omit the parentheses). So if you want to sort the neuron items in the neurons list, you'd do something like: def smartest(self): return sorted(neurons, key=self.total) -- DaveA From emile at fenx.com Wed May 9 00:28:49 2012 From: emile at fenx.com (Emile van Sebille) Date: Tue, 08 May 2012 15:28:49 -0700 Subject: [Tutor] How can I have type "function" in my script? In-Reply-To: References: <4FA81378.6080300@gmail.com> <4FA81D82.6060208@davea.name> <4FA832A2.5000901@gmail.com> <4FA8F432.1010904@gmail.com> <4FA9668D.3020908@gmail.com> Message-ID: On 5/8/2012 3:14 PM Alan Gauld said... > On 08/05/12 19:42, Emile van Sebille wrote: > >> >>> from types import * >> >>> def test():pass >> ... >> >>> function=FunctionType >> >>> print isinstance(test,function) > > Wow, thanks for that. I knew about all the different function types in > there but hadn't realised that FunctionType was the grandaddy of them > all... although I should probably have guessed there would be a parent > class. Yes -- but not quite the grandaddy... :) >>> class Test: ... def testm(self):pass ... >>> T=Test.testm >>> print isinstance(T,function) False >>> print isinstance(T,MethodType) True >>> your point elsewhere re callable is likely more relevant to the OP but who knows... Emile From scubacuda at gmail.com Wed May 9 01:37:53 2012 From: scubacuda at gmail.com (Rogelio) Date: Tue, 8 May 2012 16:37:53 -0700 Subject: [Tutor] using subprocess to export files in bash In-Reply-To: References: Message-ID: On Tue, May 8, 2012 at 11:06 AM, David Abbott wrote: > I have used this before; > > def uptime_report(): > ? ?"""Generate uptime""" > ? ?p = subprocess.Popen("uptime > /tmp/uptime.txt", > ? ? ? ? ? ?shell=True, stdout=subprocess.PIPE) > ? ?return p.stdout.readlines() > > That was from python 2.6 Looks like a lot of my problem is that my CentOS box had Python 2.4 defaulted. Looks like Popen isn't working right, even with the most simple examples. (will look at this first before I bug everyone with this problem anymore) Thanks for all your help, guys... From bruno.braga at gmail.com Wed May 9 02:27:30 2012 From: bruno.braga at gmail.com (BRAGA, Bruno) Date: Wed, 9 May 2012 10:27:30 +1000 Subject: [Tutor] Console Application - Key Events In-Reply-To: References: Message-ID: Yeah, what you say makes sense... I was hoping that there was a nice way of doing it, but I will just have to stick with "running the command yourself". I thought there could be a solution, maybe based on Ncurses, or even on the "read" command, but they can not get the keys pressed if the application is on background... and to do it on the foreground with the terminal on is crazy... Thanks anyway, it was very helpful! -- *Braga, Bruno* www.brunobraga.net bruno.braga at gmail.com On Tue, May 8, 2012 at 5:59 PM, Alan Gauld wrote: > On 08/05/12 02:44, BRAGA, Bruno wrote: > >> I would like to know if there is any "easy" way to handle events (such >> as mouse movements, keyboard keys pressed, etc) in console based python >> applications? >> > > You need to be more specific about what you mean. > Consoles don't have mice. Keyboard events are easily > handled (see my tutorial on event driven apps for > more info and examples) > > You may be confusing the concept of a console running > inside a window of a GUI system. In that case the > window receives events and the window manager can > handle them. But the python application running > inside that terminal emulator is completely unaware > of them. > > There are also event driven frameworks for consoles > that can capture events (Borland had one such for DOS), > but it is the framework not Python that is aware of > these things. > > > More specifically, I am working on a screensaver for terminals >> (http://termsaver.info), so I would like to simulate the same behaviour >> of a standard screensaver for the X windows, by: >> > > What is this screensaver going to do? Display an alternative > screen full of text? Go blank? > > * running on background >> * starting some functionality (display a text, etc) if there is no >> >> event (mouse or keyboard) for more than N minutes >> * stopping the above if there is any movement detected >> > > It is possible to do some of that in a multi process environment > by running an application in the background, but you would need some kind > of cooperative behaviour from the foreground app I suspect. > Which limits applicability. > > But the biggest problem you face is just that consoles generally > do not have any kind of event awareness. Mice etc just don't exist. > They are not event based. And where the terminal emulator is > event aware (eg xterm on Linux) the events are not passed on > to the app except in very limited circumstances - eg pasting > from a mouse selection - and that is usually just a case of > injecting the selected text into stdin. And that is deliberate since the > apps need to be able to work in real dumb terminals (VT100 etc) > or even teletypes. > > -- > Alan G > 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 questions.anon at gmail.com Wed May 9 02:48:15 2012 From: questions.anon at gmail.com (questions anon) Date: Wed, 9 May 2012 10:48:15 +1000 Subject: [Tutor] summary stats grouped by month year In-Reply-To: <089D679A-8E0F-4880-A82B-70F78D9AEE85@gmail.com> References: <089D679A-8E0F-4880-A82B-70F78D9AEE85@gmail.com> Message-ID: Excellent, thank you so much. I don't understand all the steps at this stage so I will need some time to go through it carefully but it works perfectly. Thanks again! On Tue, May 8, 2012 at 4:41 PM, Andre' Walker-Loud wrote: > Hello anonymous questioner, > > first comment - you may want to look into hdf5 data structures > > http://www.hdfgroup.org/HDF5/ > > and the python tools to play with them > > pytables - http://www.pytables.org/moin > h5py - http://code.google.com/p/h5py/ > > I have personally used pytables more - but not for any good reason. If > you happen to have the Enthought python distribution - these come with the > package, as well as an installation of hdf5 > > hdf5 is a very nice file format for storing large amounts of data (binary) > with descriptive meta-data. Also, numpy plays very nice with hdf5. Given > all your questions here, I suspect you would benefit from learning about > these and learning to play with them. > > Now to your specific question. > > > I would like to calculate summary statistics of rainfall based on year > and month. > > I have the data in a text file (although could put in any format if it > helps) extending over approx 40 years: > > YEAR MONTH MeanRain > > 1972 Jan 12.7083199 > > 1972 Feb 14.17007142 > > 1972 Mar 14.5659302 > > 1972 Apr 1.508517302 > > 1972 May 2.780009889 > > 1972 Jun 1.609619287 > > 1972 Jul 0.138150181 > > 1972 Aug 0.214346148 > > 1972 Sep 1.322102228 > > > > I would like to be able to calculate the total rain annually: > > > > YEAR Annualrainfall > > 1972 400 > > 1973 300 > > 1974 350 > > .... > > 2011 400 > > > > and also the monthly mean rainfall for all years: > > > > YEAR MonthlyMeanRain > > Jan 13 > > Feb 15 > > Mar 8 > > ..... > > Dec 13 > > > > > > Is this something I can easily do? > > Yes - this should be very easy. Imagine importing all this data into a > numpy array > > === > import numpy as np > > data = open(your_data).readlines() > years = [] > for line in data: > if line.split()[0] not in years: > years.append(line.split()[0]) > months = ['Jan','Feb',....,'Dec'] > > rain_fall = np.zeros([len(n_year),len(months)]) > for y,year in enumerate(years): > for m,month in enumerate(months): > rain_fall[y,m] = float(data[ y * 12 + m].split()[2]) > > # to get average per year - average over months - axis=1 > print np.mean(rain_fall,axis=1) > > # to get average per month - average over years - axis=0 > print np.mean(rain_fall,axis=0) > > === > > now you should imagine doing this by setting up dictionaries, so that you > can request an average for year 1972 or for month March. That is why I > used the enumerate function before to walk the indices - so that you can > imagine building the dictionary simultaneously. > > years = {'1972':0, '1973':1, ....} > months = {'Jan':0,'Feb':1,...'Dec':11} > > then you can access and store the data to the array using these > dictionaries. > > print rain_fall[int('%(1984)s' % years), int('%(March)s' % months)] > > > Andre > > > > > > > I have started by simply importing the text file but data is not > represented as time so that is probably my first problem and then I am not > sure how to group them by month/year. > > > > textfile=r"textfile.txt" > > f=np.genfromtxt(textfile,skip_header=1) > > > > Any feedback will be greatly appreciated. > > > > _______________________________________________ > > 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 brian.van.den.broek at gmail.com Wed May 9 02:48:18 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Wed, 9 May 2012 02:48:18 +0200 Subject: [Tutor] Sorting the Parts of a Dictionary into a List In-Reply-To: References: Message-ID: On 8 May 2012 23:23, Jacob Bender wrote: > Dear Tutors, > > My original email was this: > > "Dear tutors, > > I'm trying to create a neural network program. Each neuron is in a > dictionary and each of its connections and their strengths are in a nested > dictionary. So {0:{1:4, 2:5}}, 1:{0:6}, 2:{1:2}} would mean that neuron 0 > is connected to neuron 1 with a strength of 4. And it also means that > neuron 1 is connected to neuron 0 with a strength of 6. > > The problem is that I'm working on a function that is supposed to add the > total strengths of each neuron. So, for example, neuron 0's connections > have a total strength of 9 (4+5). The other problem is getting all of the > total strengths and ordering the neurons into a list. So, from the example, > the list would be from [0,1,2] because zero has the greatest total strength > of 9, then 1 with a total strength of 6 and so on. I've been working on > this problem for at least 2 hours now and still haven't found anything > close to a solution." > > And here's my source code: > The total function works when it returns the strength of a neuron, but I > don't think the "sorted" function is the best because, with its current > configuration, it returns a type error. I have been doing python for several > years now. I don't know EVERYTHING there is to know, but I am able to do > most tasks without error. Please help me get the neurons into an order in a > list as described in my original email. Also, I do thank you for your > original replies! > > -- > Thank you, > Jacob Hi Jacob, While I agree with those who suggested you send some code, I didn't look at it too closely. Only close enough to be fairly sure I wasn't doing everything for you by suggesting you consider the following approach :-) >>> neurons = {0:{1:4, 2:5}, 1:{0:6, 2:1}, 2:{0:3, 1:1}} >>> weights = {} >>> for neuron in neurons: total_weight = 0 conections = neurons[neuron] for conection in conections: total_weight += conections[conection] weights[neuron] = total_weight >>> for neuron in sorted(weights): print neuron, weights[neuron] 0 9 1 7 2 4 >>> HTH, Brian vdB From walksloud at gmail.com Wed May 9 03:16:03 2012 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Tue, 8 May 2012 18:16:03 -0700 Subject: [Tutor] summary stats grouped by month year In-Reply-To: References: <089D679A-8E0F-4880-A82B-70F78D9AEE85@gmail.com> Message-ID: dear anonymous questioner, > Excellent, thank you so much. I don't understand all the steps at this stage so I will need some time to go through it carefully but it works perfectly. > Thanks again! words of caution - you will notice that the way I constructed the data file - I assumed what the input file would look like (they come chronologically and all data are present - no missing years or months). While this might be safe for a data file you constructed, and one that is short enough to read - this is generally a very bad habit - hence my encouraging you to figure out how to make dictionaries. Imagine how you would read a file that you got from a colleague, which was so long you can not look by eye and see that it is intact, or perhaps you know that in 1983, the month of June is missing as well as some other holes in the data. And perhaps your colleague decided, since those data are missing, just don't write the data to the file, so instead of having 1983 May 2.780009889 1983 June nan 1983 July 0.138150181 you have 1983 May 2.780009889 1983 July 0.138150181 now the little loop I showed you will fail to place the data in the correct place in your numpy array, and you will get all your averaging and other analysis wrong. Instead - you can create dictionaries for the years and months. Then when you read in the data, you can grab this info to correctly place it in the right spot # years and months are your dictionaries years = {'1972':0,'1973':1,....} months = {'Jan':0,'Feb':1,...,'Dec':11} data = open(your_data).readlines() for line in data: year,month,dat = line.split() y = int(('%('+year+')s') % years) m = int(('%('+month+')s') % months) rain_fall[y,m] = float(dat) [also - if someone knows how to use the dictionaries more appropriately here - please chime in] then you also have to think about what to do with the empty data sets. The initialization rain_fall = np.zeros([n_years,n_months]) will have placed zeros everywhere - and if the data is missing - it won't get re-written. So that will make your analysis bogus also - so you have to walk through and replace the zeros with something else, like 'nan'. And then you could think about replacing missing data by averages - eg. replace a missing June entry by the average over all the non-zero June data. I was just hoping to give you a working example that you could use to make a functioning well thought out example that can handle the exceptions which will arise (like missing data, or a data file with a string where a float should be etc') Have fun! Andre On May 8, 2012, at 5:48 PM, questions anon wrote: > On Tue, May 8, 2012 at 4:41 PM, Andre' Walker-Loud wrote: > Hello anonymous questioner, > > first comment - you may want to look into hdf5 data structures > > http://www.hdfgroup.org/HDF5/ > > and the python tools to play with them > > pytables - http://www.pytables.org/moin > h5py - http://code.google.com/p/h5py/ > > I have personally used pytables more - but not for any good reason. If you happen to have the Enthought python distribution - these come with the package, as well as an installation of hdf5 > > hdf5 is a very nice file format for storing large amounts of data (binary) with descriptive meta-data. Also, numpy plays very nice with hdf5. Given all your questions here, I suspect you would benefit from learning about these and learning to play with them. > > Now to your specific question. > > > I would like to calculate summary statistics of rainfall based on year and month. > > I have the data in a text file (although could put in any format if it helps) extending over approx 40 years: > > YEAR MONTH MeanRain > > 1972 Jan 12.7083199 > > 1972 Feb 14.17007142 > > 1972 Mar 14.5659302 > > 1972 Apr 1.508517302 > > 1972 May 2.780009889 > > 1972 Jun 1.609619287 > > 1972 Jul 0.138150181 > > 1972 Aug 0.214346148 > > 1972 Sep 1.322102228 > > > > I would like to be able to calculate the total rain annually: > > > > YEAR Annualrainfall > > 1972 400 > > 1973 300 > > 1974 350 > > .... > > 2011 400 > > > > and also the monthly mean rainfall for all years: > > > > YEAR MonthlyMeanRain > > Jan 13 > > Feb 15 > > Mar 8 > > ..... > > Dec 13 > > > > > > Is this something I can easily do? > > Yes - this should be very easy. Imagine importing all this data into a numpy array > > === > import numpy as np > > data = open(your_data).readlines() > years = [] > for line in data: > if line.split()[0] not in years: > years.append(line.split()[0]) > months = ['Jan','Feb',....,'Dec'] > > rain_fall = np.zeros([len(n_year),len(months)]) > for y,year in enumerate(years): > for m,month in enumerate(months): > rain_fall[y,m] = float(data[ y * 12 + m].split()[2]) > > # to get average per year - average over months - axis=1 > print np.mean(rain_fall,axis=1) > > # to get average per month - average over years - axis=0 > print np.mean(rain_fall,axis=0) > > === > > now you should imagine doing this by setting up dictionaries, so that you can request an average for year 1972 or for month March. That is why I used the enumerate function before to walk the indices - so that you can imagine building the dictionary simultaneously. > > years = {'1972':0, '1973':1, ....} > months = {'Jan':0,'Feb':1,...'Dec':11} > > then you can access and store the data to the array using these dictionaries. > > print rain_fall[int('%(1984)s' % years), int('%(March)s' % months)] > > > Andre > > > > > > > I have started by simply importing the text file but data is not represented as time so that is probably my first problem and then I am not sure how to group them by month/year. > > > > textfile=r"textfile.txt" > > f=np.genfromtxt(textfile,skip_header=1) > > > > Any feedback will be greatly appreciated. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > From malaclypse2 at gmail.com Wed May 9 03:19:30 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 8 May 2012 21:19:30 -0400 Subject: [Tutor] List Indexing Issue In-Reply-To: References: Message-ID: On Tue, May 8, 2012 at 4:00 PM, Spyros Charonis wrote: > Hello python community, > > I'm having a small issue with list indexing. I am extracting certain > information from a PDB (protein information) file and need certain fields of > the file to be copied into a list. The entries look like this: > > ATOM ? 1512 ?N ? VAL A 222 ? ? ? 8.544 ?-7.133 ?25.697 ?1.00 48.89 > N > ATOM ? 1513 ?CA ?VAL A 222 ? ? ? 8.251 ?-6.190 ?24.619 ?1.00 48.64 > C > ATOM ? 1514 ?C ? VAL A 222 ? ? ? 9.528 ?-5.762 ?23.898 ?1.00 48.32 > C > > I am using the following syntax to parse these lines into a list: ... > charged_res_coord.append(atom_coord[i].split()[1:9]) You're using split, assuming that there will be blank spaces between your fields. That's not true, though. PDB is a fixed length record format, according to the documentation I found here: http://www.wwpdb.org/docs.html If you just have a couple of items to pull out, you can just slice the string at the appropriate places. Based on those docs, you could pull the x, y, and z coordinates out like this: x_coord = atom_line[30:38] y_coord = atom_line[38:46] z_coord = atom_line[46:54] If you need to pull more of the data out, or you may want to reuse this code in the future, it might be worth actually parsing the record into all its parts. For a fixed length record, I usually do something like this: pdbdata = """ ATOM 1512 N VAL A 222 8.544 -7.133 25.697 1.00 48.89 N ATOM 1513 CA VAL A 222 8.251 -6.190 24.619 1.00 48.64 C ATOM 1514 C VAL A 222 9.528 -5.762 23.898 1.00 48.32 C ATOM 1617 N GLU A1005 11.906 -2.722 7.994 1.00 44.02 N """.splitlines() atom_field_spec = [ slice(0,6), slice(6,11), slice(12,16), slice(16,18), slice(17,20), slice(21,22), slice(22,26), slice(26,27), slice(30,38), slice(38,46), slice(46,54), slice(54,60), slice(60,66), slice(76,78), slice(78,80), ] for line in pdbdata: if line.startswith('ATOM'): data = [line[field_spec] for field_spec in atom_field_spec] print(data) You can build all kind of fancy data structures on top of that if you want to. You could use that extracted data to build a namedtuple for convenient access to the data by names instead of indexes into a list, or to create instances of a custom class with whatever functionality you need. -- Jerry From questions.anon at gmail.com Wed May 9 06:32:44 2012 From: questions.anon at gmail.com (questions anon) Date: Wed, 9 May 2012 14:32:44 +1000 Subject: [Tutor] summary stats grouped by month year In-Reply-To: References: <089D679A-8E0F-4880-A82B-70F78D9AEE85@gmail.com> Message-ID: excellent thank you for the warning, I will look into dictionaries alot more carefully now. I have some simple questions that I would like to ask straight away but will try and figure a few things out on my own first. Thanks again!! On Wed, May 9, 2012 at 11:16 AM, Andre' Walker-Loud wrote: > dear anonymous questioner, > > > Excellent, thank you so much. I don't understand all the steps at this > stage so I will need some time to go through it carefully but it works > perfectly. > > Thanks again! > > words of caution - you will notice that the way I constructed the data > file - I assumed what the input file would look like (they come > chronologically and all data are present - no missing years or months). > While this might be safe for a data file you constructed, and one that is > short enough to read - this is generally a very bad habit - hence my > encouraging you to figure out how to make dictionaries. > > Imagine how you would read a file that you got from a colleague, which was > so long you can not look by eye and see that it is intact, or perhaps you > know that in 1983, the month of June is missing as well as some other holes > in the data. And perhaps your colleague decided, since those data are > missing, just don't write the data to the file, so instead of having > > 1983 May 2.780009889 > 1983 June nan > 1983 July 0.138150181 > > you have > > 1983 May 2.780009889 > 1983 July 0.138150181 > > now the little loop I showed you will fail to place the data in the > correct place in your numpy array, and you will get all your averaging and > other analysis wrong. > > > Instead - you can create dictionaries for the years and months. Then when > you read in the data, you can grab this info to correctly place it in the > right spot > > # years and months are your dictionaries > years = {'1972':0,'1973':1,....} > months = {'Jan':0,'Feb':1,...,'Dec':11} > data = open(your_data).readlines() > for line in data: > year,month,dat = line.split() > y = int(('%('+year+')s') % years) > m = int(('%('+month+')s') % months) > rain_fall[y,m] = float(dat) > > [also - if someone knows how to use the dictionaries more appropriately > here - please chime in] > > then you also have to think about what to do with the empty data sets. > The initialization > > rain_fall = np.zeros([n_years,n_months]) > > will have placed zeros everywhere - and if the data is missing - it won't > get re-written. So that will make your analysis bogus also - so you have > to walk through and replace the zeros with something else, like 'nan'. And > then you could think about replacing missing data by averages - eg. replace > a missing June entry by the average over all the non-zero June data. > > > I was just hoping to give you a working example that you could use to make > a functioning well thought out example that can handle the exceptions which > will arise (like missing data, or a data file with a string where a float > should be etc') > > > Have fun! > > Andre > > > > > On May 8, 2012, at 5:48 PM, questions anon wrote: > > > On Tue, May 8, 2012 at 4:41 PM, Andre' Walker-Loud > wrote: > > Hello anonymous questioner, > > > > first comment - you may want to look into hdf5 data structures > > > > http://www.hdfgroup.org/HDF5/ > > > > and the python tools to play with them > > > > pytables - http://www.pytables.org/moin > > h5py - http://code.google.com/p/h5py/ > > > > I have personally used pytables more - but not for any good reason. If > you happen to have the Enthought python distribution - these come with the > package, as well as an installation of hdf5 > > > > hdf5 is a very nice file format for storing large amounts of data > (binary) with descriptive meta-data. Also, numpy plays very nice with > hdf5. Given all your questions here, I suspect you would benefit from > learning about these and learning to play with them. > > > > Now to your specific question. > > > > > I would like to calculate summary statistics of rainfall based on year > and month. > > > I have the data in a text file (although could put in any format if it > helps) extending over approx 40 years: > > > YEAR MONTH MeanRain > > > 1972 Jan 12.7083199 > > > 1972 Feb 14.17007142 > > > 1972 Mar 14.5659302 > > > 1972 Apr 1.508517302 > > > 1972 May 2.780009889 > > > 1972 Jun 1.609619287 > > > 1972 Jul 0.138150181 > > > 1972 Aug 0.214346148 > > > 1972 Sep 1.322102228 > > > > > > I would like to be able to calculate the total rain annually: > > > > > > YEAR Annualrainfall > > > 1972 400 > > > 1973 300 > > > 1974 350 > > > .... > > > 2011 400 > > > > > > and also the monthly mean rainfall for all years: > > > > > > YEAR MonthlyMeanRain > > > Jan 13 > > > Feb 15 > > > Mar 8 > > > ..... > > > Dec 13 > > > > > > > > > Is this something I can easily do? > > > > Yes - this should be very easy. Imagine importing all this data into a > numpy array > > > > === > > import numpy as np > > > > data = open(your_data).readlines() > > years = [] > > for line in data: > > if line.split()[0] not in years: > > years.append(line.split()[0]) > > months = ['Jan','Feb',....,'Dec'] > > > > rain_fall = np.zeros([len(n_year),len(months)]) > > for y,year in enumerate(years): > > for m,month in enumerate(months): > > rain_fall[y,m] = float(data[ y * 12 + m].split()[2]) > > > > # to get average per year - average over months - axis=1 > > print np.mean(rain_fall,axis=1) > > > > # to get average per month - average over years - axis=0 > > print np.mean(rain_fall,axis=0) > > > > === > > > > now you should imagine doing this by setting up dictionaries, so that > you can request an average for year 1972 or for month March. That is why I > used the enumerate function before to walk the indices - so that you can > imagine building the dictionary simultaneously. > > > > years = {'1972':0, '1973':1, ....} > > months = {'Jan':0,'Feb':1,...'Dec':11} > > > > then you can access and store the data to the array using these > dictionaries. > > > > print rain_fall[int('%(1984)s' % years), int('%(March)s' % months)] > > > > > > Andre > > > > > > > > > > > > > I have started by simply importing the text file but data is not > represented as time so that is probably my first problem and then I am not > sure how to group them by month/year. > > > > > > textfile=r"textfile.txt" > > > f=np.genfromtxt(textfile,skip_header=1) > > > > > > Any feedback will be greatly appreciated. > > > > > > _______________________________________________ > > > 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 aduarte at itqb.unl.pt Wed May 9 16:00:34 2012 From: aduarte at itqb.unl.pt (Afonso Duarte) Date: Wed, 9 May 2012 15:00:34 +0100 Subject: [Tutor] Script to search in string of values from file A in file B Message-ID: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> Dear All, I'm new to Python and started to use it to search text strings in big (>500Mb) txt files. I have a list on text file (e.g. A.txt) that I want to use as a key to search another file (e.g. B.txt), organized in the following way: A.txt: Aaa Bbb Ccc Ddd . . . B.txt Bbb 1234 Xxx 234 I want to use A.txt to search in B.txt and have as output the original search entry (e.g. Bbb) followed by the line that follows it in the B.txt (e.g. Bbb / 1234). I wrote the following script: object = open(B.txt', 'r') lista = open(A.txt', 'r') searches = lista.readlines() for line in object.readlines(): for word in searches: if word in line: print line+'\n' But from here I only get the searching entry and not the line afterwards, I tried to google it but I got lost and didn't manage to do it. Any ideas ? I guess that this is basic scripting but I just started . Best Afonso -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.braga at gmail.com Wed May 9 16:22:19 2012 From: bruno.braga at gmail.com (BRAGA, Bruno) Date: Thu, 10 May 2012 00:22:19 +1000 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> Message-ID: On Thursday, May 10, 2012, Afonso Duarte wrote: > Dear All, > > > > I?m new to Python and started to use it to search text strings in big (>500Mb) txt files. > > I have a list on text file (e.g. A.txt) that I want to use as a key to search another file (e.g. B.txt), organized in the following way: > > > > A.txt: > > > > Aaa > > Bbb > > Ccc > > Ddd > > . > > . > > . > > > > B.txt > > > > Bbb > > 1234 > > Xxx > > 234 > > > > > > I want to use A.txt to search in B.txt and have as output the original search entry (e.g. Bbb) followed by the line that follows it in the B.txt (e.g. Bbb / 1234). > > I wrote the following script: > > > > > > object = open(B.txt', 'r') > > lista = open(A.txt', 'r') > > searches = lista.readlines() > > for line in object.readlines(): > > for word in searches: > > if word in line: > > print line+'\n' > > > > > > > > But from here I only get the searching entry and not the line afterwards, I tried to google it but I got lost and didn?t manage to do it. > > Any ideas ? I guess that this is basic scripting but I just started . Not sure I understood the question... But: - are you trying to "grep" the text file? (simpler than programming in python, IMO) - if you have multiple matches of any of the keys from A file in a sungle line of B file, the script above will print it multiple times - you need not add new line (\n) in the print statement, unless you want it to print a blank line between results Based on the example you gave, the matching Bbb value in B and A are the same, so actually line is being printed, but it is just the same as word... > > > > Best > > > > Afonso -- Sent from Gmail Mobile -------------- next part -------------- An HTML attachment was scrubbed... URL: From aduarte at itqb.unl.pt Wed May 9 16:26:51 2012 From: aduarte at itqb.unl.pt (aduarte) Date: Wed, 09 May 2012 15:26:51 +0100 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> Message-ID: On 2012-05-09 15:22, BRAGA, Bruno wrote: > On Thursday, May 10, 2012, Afonso Duarte > wrote: >> Dear All, >> >> ? >> >> I?m new to Python and started to use it to search text strings in > big (>500Mb) txt files. > > >> I have a list on text file (e.g. A.txt) that I want to use as a key > to search another file (e.g. B.txt), organized in the following way: >> >> ? >> >> A.txt: >> >> ? >> >> Aaa > > >> Bbb >> >> Ccc >> >> Ddd >> >> . >> >> . >> >> . >> >> ? >> >> B.txt >> >> ? >> >> Bbb >> >> 1234 >> > > Xxx >> >> 234 >> >> ? >> >> ? >> >> I want to use A.txt to search in B.txt and have as output the > original search entry (e.g. Bbb) followed by the line that follows it > in the B.txt (e.g.? Bbb / 1234). > > >> I wrote the following script: >> >> ? >> >> ? >> >> object = open(B.txt', 'r') >> >> lista = open(A.txt', 'r') >> >> searches = lista.readlines() > > >> for line in object.readlines(): >> >> ???? for word in searches: >> >> ????????? if word in line: >> >> ???????????????print line+'n' >> >> ? >> >> ? > > >> ? >> >> But from here I only get the searching entry and not the line > afterwards, I tried to google it but I got lost and didn?t manage to > do it. >> >> Any ideas ? I guess that this is basic scripting but I just started > . > > Not sure I understood the question... But: > - are you trying to "grep" the text file? (simpler than programming > in python, IMO) > - if you have multiple matches of any of the keys from A file in a > sungle line of B file, the script above will print it multiple times true, I did not mention, but the entries in file A.txt only appear once in b.txt. > - you need not add new line (n) in the print statement, unless you > want it to print a blank line between results true > > Based on the example you gave, the matching Bbb value in B and A are > the same, so actually line is being printed, but it is just the same > as word... exactly! but what I want is that plus the value that proceeds that line in the B.txt i.e. Bbb 1234 Best Afonso > >> >> ? >> >> Best >> >> ? >> >> Afonso From d at davea.name Wed May 9 16:52:23 2012 From: d at davea.name (Dave Angel) Date: Wed, 09 May 2012 10:52:23 -0400 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> Message-ID: <4FAA84A7.1010306@davea.name> On 05/09/2012 10:00 AM, Afonso Duarte wrote: > Dear All, > > > > I'm new to Python and started to use it to search text strings in big > (>500Mb) txt files. > > I have a list on text file (e.g. A.txt) that I want to use as a key to > search another file (e.g. B.txt), organized in the following way: > > > > A.txt: > > > > Aaa > > Bbb > > Ccc > > Ddd > > . > > . > > . > > > > B.txt > > > > Bbb > > 1234 > > Xxx > > 234 > > > > > > I want to use A.txt to search in B.txt and have as output the original > search entry (e.g. Bbb) followed by the line that follows it in the B.txt > (e.g. Bbb / 1234). > > I wrote the following script: > > > > > > object = open(B.txt', 'r') > > lista = open(A.txt', 'r') > > searches = lista.readlines() > > for line in object.readlines(): > > for word in searches: > > if word in line: > > print line+'\n' > > > > > > > > But from here I only get the searching entry and not the line afterwards, I > tried to google it but I got lost and didn't manage to do it. > > Any ideas ? I guess that this is basic scripting but I just started . > > > > Best > > > > Afonso > > Please post your messages as plain-text. The double-spacing I get is very annoying. There's a lot you don't say, which is implied in your code. Are the lines in file B.txt really alternating: key1 data for key1 key2 data for key2 ... Are the key lines in file B.txt exact messages, or do they just "contain" the key somewhere in the line? Your code assumes the latter, but the whole thing could be much simpler if it were always an exact match. Are the keys in A.txt unique? If so, you could store them in a set, and make lookup basically instantaneous. I think the real question you had was how to access the line following the key, once you matched the key. Something like this should do it (untested) lines = iter( object ) for key in lines: linedata = lines.next() if key in mydictionary: print key, "-->", linedata Main caveat I can see is the file had better have an even number of lines. -- DaveA // From aduarte at itqb.unl.pt Wed May 9 17:04:25 2012 From: aduarte at itqb.unl.pt (Afonso Duarte) Date: Wed, 9 May 2012 16:04:25 +0100 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: <4FAA84A7.1010306@davea.name> References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> <4FAA84A7.1010306@davea.name> Message-ID: <005a01cd2df5$05e0fa00$11a2ee00$@unl.pt> -----Original Message----- From: Dave Angel [mailto:d at davea.name] Sent: woensdag 9 mei 2012 15:52 To: Afonso Duarte Cc: tutor at python.org Subject: Re: [Tutor] Script to search in string of values from file A in file B On 05/09/2012 10:00 AM, Afonso Duarte wrote: > Dear All, > I'm new to Python and started to use it to search text strings in big > (>500Mb) txt files. > I have a list on text file (e.g. A.txt) that I want to use as a key to > search another file (e.g. B.txt), organized in the following way: > > A.txt: > > Aaa > Bbb > Ccc > Ddd > . > . > . > > > > B.txt > Bbb > 1234 > Xxx > 234 > > I want to use A.txt to search in B.txt and have as output the original > search entry (e.g. Bbb) followed by the line that follows it in the > B.txt (e.g. Bbb / 1234). > I wrote the following script: > > > > > > object = open(B.txt', 'r') > lista = open(A.txt', 'r') > searches = lista.readlines() > for line in object.readlines(): > for word in searches: > if word in line: > print line+'\n' > > > But from here I only get the searching entry and not the line > afterwards, I tried to google it but I got lost and didn't manage to do it. > Any ideas ? I guess that this is basic scripting but I just started . > > Best > > Afonso > > >Please post your messages as plain-text. The double-spacing I get is >very annoying. Sorry for that my outlook mess-it-up >There's a lot you don't say, which is implied in your code. >Are the lines in file B.txt really alternating: > >key1 >data for key1 >key2 >data for key2 >... Sure, that's why I describe them in the email like that and didn't say that they weren't >Are the key lines in file B.txt exact messages, or do they just >"contain" the key somewhere in the line? > Your code assumes the latter, >but the whole thing could be much simpler if it were always an exact match. The entry in B has text before and after (the size of that text changes from entry to entry. >Are the keys in A.txt unique? If so, you could store them in a set, and make lookup basically >instantaneous. That indeed I didn't refer, the entries from A are unique in B >I think the real question you had was how to access the line following the key, once you matched the key. True that is my real question (as the code above works just for the title line, I basically want to print the next line of the B.txt for each entry) >Something like this should do it (untested) > >lines = iter( object ) >for key in lines: > linedata = lines.next() > if key in mydictionary: > print key, "-->", linedata >Main caveat I can see is the file had better have an even number of lines. That changes from file to file, and its unlikely i have all even number. Thanks Afonso -- DaveA // From d at davea.name Wed May 9 17:16:47 2012 From: d at davea.name (Dave Angel) Date: Wed, 09 May 2012 11:16:47 -0400 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: <005a01cd2df5$05e0fa00$11a2ee00$@unl.pt> References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> <4FAA84A7.1010306@davea.name> <005a01cd2df5$05e0fa00$11a2ee00$@unl.pt> Message-ID: <4FAA8A5F.4010506@davea.name> On 05/09/2012 11:04 AM, Afonso Duarte wrote: > > > -----Original Message----- > From: Dave Angel [mailto:d at davea.name] > >> >> Please post your messages as plain-text. The double-spacing I get is >> very annoying. > > Sorry for that my outlook mess-it-up I'm sure there's a setting to say use plain-text. In Thunderbird, i tell it that any message to forums is to be plain-text. > >> There's a lot you don't say, which is implied in your code. >> Are the lines in file B.txt really alternating: >> >> key1 >> data for key1 >> key2 >> data for key2 >> ... > > Sure, that's why I describe them in the email like that and didn't say that > they weren't > >> Are the key lines in file B.txt exact messages, or do they just >> "contain" the key somewhere in the line? >> Your code assumes the latter, >> but the whole thing could be much simpler if it were always an exact match. > > The entry in B has text before and after (the size of that text changes from > entry to entry. In other words, the line pairs are not like your sample, but more like: trash key1 more trash Useful associated data for the previous key trash2 key2 more trash Useful associated ata for the previous key > > >> Are the keys in A.txt unique? If so, you could store them in a set, and > make lookup basically >instantaneous. > > That indeed I didn't refer, the entries from A are unique in B Not what I asked. Are the keys in A.txt ever present more than once in A.txt ? But then again, if the key line can contain garbage before and/or after the key, then the set idea is moot anyway. > > >> I think the real question you had was how to access the line following the > key, once you matched the key. > > True that is my real question (as the code above works just for the title > line, I basically want to print the next line of the B.txt for each entry) > >> Something like this should do it (untested) >> >> lines = iter( object ) >> for key in lines: >> linedata = lines.next() >> if key in mydictionary: >> print key, "-->", linedata > > >> Main caveat I can see is the file had better have an even number of lines. > > > That changes from file to file, and its unlikely i have all even number. In that case, what do you use for data of the last key? If you really have to handle the case where there is a final key with no data, then you'll have to detect that case, and make up the data separately. That could be done with a try block, but this is probably clearer: rawlines = object.readlines() if len(rawlines) %2 != 0: rawlines += "" #add an extra line lines = iter(rawlines) for keyline in lines: linedata = lines.next() for word in searches: if word in keyline: print word, "-->", linedata > > Thanks > > > Afonso > > -- DaveA From d at davea.name Wed May 9 17:38:44 2012 From: d at davea.name (Dave Angel) Date: Wed, 09 May 2012 11:38:44 -0400 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: <4FAA8A5F.4010506@davea.name> References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> <4FAA84A7.1010306@davea.name> <005a01cd2df5$05e0fa00$11a2ee00$@unl.pt> <4FAA8A5F.4010506@davea.name> Message-ID: <4FAA8F84.7080303@davea.name> > > > If you really have to handle the case where there is a final key with no > data, then you'll have to detect that case, and make up the data > separately. That could be done with a try block, but this is probably > clearer: > > rawlines = object.readlines() > if len(rawlines) %2 != 0: > rawlines += "" #add an extra line Oops, that should have been rawlines.append("") or maybe rawlines.append("\n") > lines = iter(rawlines) > > for keyline in lines: > linedata = lines.next() > for word in searches: > if word in keyline: > print word, "-->", linedata > > -- DaveA From breamoreboy at yahoo.co.uk Wed May 9 18:36:46 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 09 May 2012 17:36:46 +0100 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> Message-ID: On 09/05/2012 15:00, Afonso Duarte wrote: > object = open(B.txt', 'r') > You'll already received some sound advice, so I'd just like to point out that your object will override the built-in object, apologies if somebody has already said this and I've missed it. > > Afonso > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Cheers. Mark Lawrence. From joel.goldstick at gmail.com Wed May 9 21:26:40 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 9 May 2012 15:26:40 -0400 Subject: [Tutor] odd behavior when renaming a file Message-ID: import os def pre_process(): if os.path.isfile('revelex.csv'): os.rename('revelex.csv', 'revelex.tmp') print "Renamed ok" else: print "Exiting, no revelex.csv file available" exit() out_file = open('revelex.csv', 'w') # etc. if __name__ == '__main__': pre_process() When I run the code above it works file if run from the file. But when I import it and run it from another file it renames the file but then prints "Exiting, no revelex.csv file available" -- Joel Goldstick From aduarte at itqb.unl.pt Wed May 9 21:28:47 2012 From: aduarte at itqb.unl.pt (aduarte) Date: Wed, 09 May 2012 20:28:47 +0100 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: <4FAA8A5F.4010506@davea.name> References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> <4FAA84A7.1010306@davea.name> <005a01cd2df5$05e0fa00$11a2ee00$@unl.pt> <4FAA8A5F.4010506@davea.name> Message-ID: Dear All, Sorry it seems that I got the wrong mailing list to subscribe ... I got the idea that this list was open to newbies ... by the answers I got I see that I was wrong " In that case, what do you use for data of the last key? If you really have to handle the case where there is a final key with no data, then you'll have to detect that case, and make up the data separately. That could be done with a try block, but this is probably clearer: rawlines = object.readlines() if len(rawlines) %2 != 0: rawlines += "" #add an extra line lines = iter(rawlines) for keyline in lines: linedata = lines.next() for word in searches: if word in keyline: print word, "-->", linedata " after chatting in other mailing lists about other languages I realized that this mailing list is not in my league for python ... Interestingly I did got a strange advice from this list: try awk ... of Perl for the job, as Python is kind of tricky to print the next line that you selected (yes that was my question and I still don't understand how ppl advise me to insert new lines in 500Mb files and so on to do it...) Once again sorry about the time. Cheers Afonso On 2012-05-09 16:16, Dave Angel wrote: > On 05/09/2012 11:04 AM, Afonso Duarte wrote: >> >> >> -----Original Message----- >> From: Dave Angel [mailto:d at davea.name] >> >>> >>> Please post your messages as plain-text. The double-spacing I get >>> is >>> very annoying. >> >> Sorry for that my outlook mess-it-up > > I'm sure there's a setting to say use plain-text. In Thunderbird, i > tell it that any message to forums is to be plain-text. > >> >>> There's a lot you don't say, which is implied in your code. >>> Are the lines in file B.txt really alternating: >>> >>> key1 >>> data for key1 >>> key2 >>> data for key2 >>> ... >> >> Sure, that's why I describe them in the email like that and didn't >> say that >> they weren't >> >>> Are the key lines in file B.txt exact messages, or do they just >>> "contain" the key somewhere in the line? >>> Your code assumes the latter, >>> but the whole thing could be much simpler if it were always an >>> exact match. >> >> The entry in B has text before and after (the size of that text >> changes from >> entry to entry. > > In other words, the line pairs are not like your sample, but more > like: > > trash key1 more trash > Useful associated data for the previous key > trash2 key2 more trash > Useful associated ata for the previous key > > >> >> >>> Are the keys in A.txt unique? If so, you could store them in a >>> set, and >> make lookup basically >instantaneous. >> >> That indeed I didn't refer, the entries from A are unique in B > > Not what I asked. Are the keys in A.txt ever present more than once > in > A.txt ? But then again, if the key line can contain garbage before > and/or after the key, then the set idea is moot anyway. > >> >> >>> I think the real question you had was how to access the line >>> following the >> key, once you matched the key. >> >> True that is my real question (as the code above works just for the >> title >> line, I basically want to print the next line of the B.txt for each >> entry) >> >>> Something like this should do it (untested) >>> >>> lines = iter( object ) >>> for key in lines: >>> linedata = lines.next() >>> if key in mydictionary: >>> print key, "-->", linedata >> >> >>> Main caveat I can see is the file had better have an even number of >>> lines. >> >> >> That changes from file to file, and its unlikely i have all even >> number. > > In that case, what do you use for data of the last key? > > > If you really have to handle the case where there is a final key with > no > data, then you'll have to detect that case, and make up the data > separately. That could be done with a try block, but this is > probably > clearer: > > rawlines = object.readlines() > if len(rawlines) %2 != 0: > rawlines += "" #add an extra line > lines = iter(rawlines) > > for keyline in lines: > linedata = lines.next() > for word in searches: > if word in keyline: > print word, "-->", linedata > > >> >> Thanks >> >> >> Afonso >> >> From joel.goldstick at gmail.com Wed May 9 21:40:44 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 9 May 2012 15:40:44 -0400 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> Message-ID: On Wed, May 9, 2012 at 10:00 AM, Afonso Duarte wrote: > Dear All, > > > > I?m new to Python and started to use it to search text strings in big > (>500Mb) txt files. > > I have a list on text file (e.g. A.txt) that I want to use as a key to > search another file (e.g. B.txt), organized in the following way: > > > > A.txt: > > > > Aaa > > Bbb > > Ccc > > Ddd > > . > > . > > . > > > > B.txt > > > > Bbb > > 1234 > > Xxx > > 234 > > > > > > I want to use A.txt to search in B.txt and have as output the original > search entry (e.g. Bbb) followed by the line that follows it in the B.txt > (e.g.? Bbb / 1234). > > I wrote the following script: > > > > > > object = open(B.txt', 'r') > > lista = open(A.txt', 'r') > > searches = lista.readlines() > > for line in object.readlines(): > ???? for word in searches: > ????????? if word in line:> > ???????????????print line+'\n' > > > Don't give up on this group so quickly. You will get lots of help here. As to your problem: Do you know about enumerate? Learn about it here: http://docs.python.org/library/functions.html#enumerate if you change your code above to: for index, word in enumerate line: print line, word[index+1] I think you will get what you are looking for > > > > > But from here I only get the searching entry and not the line afterwards, I > tried to google it but I got lost and didn?t manage to do it. > > Any ideas ? I guess that this is basic scripting but I just started . > > > > Best > > > > Afonso > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick From joel.goldstick at gmail.com Wed May 9 21:47:04 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 9 May 2012 15:47:04 -0400 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> Message-ID: On Wed, May 9, 2012 at 3:40 PM, Joel Goldstick wrote: > On Wed, May 9, 2012 at 10:00 AM, Afonso Duarte wrote: >> Dear All, >> >> >> >> I?m new to Python and started to use it to search text strings in big >> (>500Mb) txt files. >> >> I have a list on text file (e.g. A.txt) that I want to use as a key to >> search another file (e.g. B.txt), organized in the following way: >> >> >> >> A.txt: >> >> >> >> Aaa >> >> Bbb >> >> Ccc >> >> Ddd >> >> . >> >> . >> >> . >> >> >> >> B.txt >> >> >> >> Bbb >> >> 1234 >> >> Xxx >> >> 234 >> >> >> >> >> >> I want to use A.txt to search in B.txt and have as output the original >> search entry (e.g. Bbb) followed by the line that follows it in the B.txt >> (e.g.? Bbb / 1234). >> >> I wrote the following script: >> >> >> >> >> >> object = open(B.txt', 'r') >> >> lista = open(A.txt', 'r') >> >> searches = lista.readlines() >> >> for line in object.readlines(): >> ???? for word in searches: >> ????????? if word in line:> >> ???????????????print line+'\n' >> >> >> > > Don't give up on this group so quickly. ?You will get lots of help here. > > As to your problem: ?Do you know about enumerate? ?Learn about it > here: http://docs.python.org/library/functions.html#enumerate > > if you change your code above to: > ? for index, word in enumerate line: > ? ? ? print line, word[index+1] > > I think you will get what you are looking for My mistake : I meant this: my_lines = object.readlines() # note, not a good thing to name something object. Its a class for index, line in enumerate(my_lines): for word in searches: if word in line: print line print my_lines[index+1] Sorry for the crazy earlier post >> >> But from here I only get the searching entry and not the line afterwards, I >> tried to google it but I got lost and didn?t manage to do it. >> >> Any ideas ? I guess that this is basic scripting but I just started . >> >> >> >> Best >> >> >> >> Afonso >> >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Joel Goldstick -- Joel Goldstick From wprins at gmail.com Wed May 9 21:55:30 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 9 May 2012 20:55:30 +0100 Subject: [Tutor] odd behavior when renaming a file In-Reply-To: References: Message-ID: Hi, On 9 May 2012 20:26, Joel Goldstick wrote: > import os > def pre_process(): > if os.path.isfile('revelex.csv'): > os.rename('revelex.csv', 'revelex.tmp') > print "Renamed ok" > else: > print "Exiting, no revelex.csv file available" > exit() > out_file = open('revelex.csv', 'w') > # etc. > > if __name__ == '__main__': > pre_process() > > > When I run the code above it works file if run from the file. But > when I import it and run it from another file it renames the file but > then prints "Exiting, no revelex.csv file available" > Can you post where/how you call this from another file? Anyway, it sounds like the pre_process() routine is being called twice, somehow. On the first call the file is renamed. Then on the second call, of course the file is not there anymore (as it's been renamed) and thus it prints the "Exiting" message. Best, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed May 9 22:18:30 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 9 May 2012 21:18:30 +0100 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> Message-ID: Hi Alfonso, I see you've had some responses yet -- I've not read them all, and am just posting the following suggestion you might want to look at: # read lines with "keys" into a list selected_keys=open('A.txt', 'r').readlines() # read all data records into another list records=open('B.txt', 'r').readlines() # Now use a list comprehension to return the required entries, the i+1th entries for all i indexes in the records # list that corresponds to a key in the keys list: selected_values = [(records[i], records[i+1]) for i, row in enumerate(records) if row in selected_keys] # The above returns both the key and the value, in a tuple, if you just want the value rows only then the above becomes: #selected_values = [records[i+1] for i, row in enumerate(records) if row in selected_keys] # Finally print the result. print selected_values You'll note I read both files into memory, even though you say your files are largish. I don't consider 500MB to be very large in this day and age of 4+GB PC's, which is why I've basically ignored the "large" issue. If this is not true in your case then you'll have to post back. Good luck, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed May 9 23:21:37 2012 From: __peter__ at web.de (Peter Otten) Date: Wed, 09 May 2012 23:21:37 +0200 Subject: [Tutor] odd behavior when renaming a file References: Message-ID: Joel Goldstick wrote: > import os > def pre_process(): > if os.path.isfile('revelex.csv'): > os.rename('revelex.csv', 'revelex.tmp') > print "Renamed ok" > else: > print "Exiting, no revelex.csv file available" > exit() > out_file = open('revelex.csv', 'w') > # etc. > > if __name__ == '__main__': > pre_process() > > > When I run the code above it works file if run from the file. But > when I import it and run it from another file it renames the file but > then prints "Exiting, no revelex.csv file available" Add print os.getcwd() to your code, you are probably in the wrong directory. From alan.gauld at btinternet.com Thu May 10 01:26:26 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 May 2012 00:26:26 +0100 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> <4FAA84A7.1010306@davea.name> <005a01cd2df5$05e0fa00$11a2ee00$@unl.pt> <4FAA8A5F.4010506@davea.name> Message-ID: On 09/05/12 20:28, aduarte wrote: > Sorry it seems that I got the wrong mailing list to subscribe ... > I got the idea that this list was open to newbies ... by the answers I > got I see that I was wrong I'm not sure what you mean. The answers you got seem to have provided the answers to your questions. What more were you expecting? > after chatting in other mailing lists about other languages I realized > that this mailing list is not in my league for python ... Which league is that? You said you were a beginner so you got answers appropriate to a beginner. If you said you were an experienced data processing professional looking for a smart/efficient way to process large files using Python you would likely have gotten different answers. If the answers were too advanced then by all means ask for clarification. We can only guess your level based on what you post. > Interestingly I did got a strange advice from this list: try awk ... of > Perl for the job, as Python is kind of tricky to print the next line I didn't see that suggestion and I disagree with it. Python is just as capable of processing files as awk or Perl as I hope the other answers have demonstrated. But where another tool is more appropriate there is no harm in suggesting it. Just because this is a Python list doesn't mean the answer needs to be Python. > that you selected (yes that was my question and I still don't understand > how ppl advise me to insert new lines in 500Mb files and so on to do it...) Again I'm not sure that anyone is actually suggesting you insert new lines into your file. It's certainly not the general advice being given. But this is a list for beginners and the people giving the advice range from complete novices themselves to working pro's. The answers reflect that diversity. In your case the majority of the answers have come from experienced programmers giving you sound advice and probing your requirements to ensure that all your use cases are covered. The only slightly radical suggestion I can see is to read the files into memory - and on a modern PC that's not too radical for a 500M file even though I'd probably not do it myself... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From aduarte at itqb.unl.pt Thu May 10 10:20:37 2012 From: aduarte at itqb.unl.pt (Afonso Duarte) Date: Thu, 10 May 2012 09:20:37 +0100 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> Message-ID: <000c01cd2e85$c77a6df0$566f49d0$@unl.pt> Dear All, Thanks Joel and Walter, both solutions worked nicely and produced the desired final objective! Short answer to Alan Gauld, far from me to start answering all your points, but I guess I should answer to the most pertinent ones: >> I'm not sure what you mean. >>The answers you got seem to have provided the answers to your questions. The answers that solved the problem were only given after I sent the email you answered ... the replies before that (sure you can still see them online) are aimed (I am assuming) at a more advanced level of Python not for a new guy, moreover once those were given and once i started asking how actually that could ever work I got answers arguing that the answer was given... >>What more were you expecting? The excellent answers I got late yesterday and that indeed represent the majority of good answers I saw in this mailing list... >> Which league is that? The "league of ppl" that actually uses mailing lists in a daily basis (both for asking and answering questions) in different fields, i.e. I am used to mailing list talks and rarely have a problem of miscommunication ... surprisingly for me in this one I got that. Btw just to make it clear again I am a Python beginner (as I said before) working with big files... otherwise I wouldn?t be here asking such questions. >>In your case the majority of the answers have come from >>experienced programmers giving you sound advice and >>probing your requirements to ensure that all your use >>cases are covered. I do agree entirely, that is why I subscribed to this mailing list and not to another! And at the end I did got my answer (but again only after getting emails saying that it was more than explained when it wasn't). Thanks again for the nice solutions and sorry for the side discussion on how to write/answer to mailing lists Cheers Afonso -----Original Message----- From: Joel Goldstick [mailto:joel.goldstick at gmail.com] Sent: woensdag 9 mei 2012 20:47 To: Afonso Duarte Cc: tutor at python.org Subject: Re: [Tutor] Script to search in string of values from file A in file B On Wed, May 9, 2012 at 3:40 PM, Joel Goldstick wrote: > On Wed, May 9, 2012 at 10:00 AM, Afonso Duarte wrote: >> Dear All, >> >> >> >> I?m new to Python and started to use it to search text strings in big >> (>500Mb) txt files. >> >> I have a list on text file (e.g. A.txt) that I want to use as a key >> to search another file (e.g. B.txt), organized in the following way: >> >> >> >> A.txt: >> >> >> >> Aaa >> >> Bbb >> >> Ccc >> >> Ddd >> >> . >> >> . >> >> . >> >> >> >> B.txt >> >> >> >> Bbb >> >> 1234 >> >> Xxx >> >> 234 >> >> >> >> >> >> I want to use A.txt to search in B.txt and have as output the >> original search entry (e.g. Bbb) followed by the line that follows it >> in the B.txt (e.g. Bbb / 1234). >> >> I wrote the following script: >> >> >> >> >> >> object = open(B.txt', 'r') >> >> lista = open(A.txt', 'r') >> >> searches = lista.readlines() >> >> for line in object.readlines(): >> for word in searches: >> if word in line:> >> print line+'\n' >> >> >> > > Don't give up on this group so quickly. You will get lots of help here. > > As to your problem: Do you know about enumerate? Learn about it > here: http://docs.python.org/library/functions.html#enumerate > > if you change your code above to: > for index, word in enumerate line: > print line, word[index+1] > > I think you will get what you are looking for My mistake : I meant this: my_lines = object.readlines() # note, not a good thing to name something object. Its a class for index, line in enumerate(my_lines): for word in searches: if word in line: print line print my_lines[index+1] Sorry for the crazy earlier post >> >> But from here I only get the searching entry and not the line >> afterwards, I tried to google it but I got lost and didn?t manage to do it. >> >> Any ideas ? I guess that this is basic scripting but I just started . >> >> >> >> Best >> >> >> >> Afonso >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Joel Goldstick -- Joel Goldstick From d at davea.name Thu May 10 12:32:31 2012 From: d at davea.name (Dave Angel) Date: Thu, 10 May 2012 06:32:31 -0400 Subject: [Tutor] Script to search in string of values from file A in file B In-Reply-To: <000c01cd2e85$c77a6df0$566f49d0$@unl.pt> References: <003c01cd2dec$1ae094f0$50a1bed0$@unl.pt> <000c01cd2e85$c77a6df0$566f49d0$@unl.pt> Message-ID: <4FAB993F.5080500@davea.name> On 05/10/2012 04:20 AM, Afonso Duarte wrote: > Dear All, > > Thanks Joel and Walter, both solutions worked nicely and produced the desired final objective! > > Short answer to Alan Gauld, far from me to start answering all your points, but I guess I should answer to the most pertinent ones: > >>> I'm not sure what you mean. >>> The answers you got seem to have provided the answers to your questions. > The answers that solved the problem were only given after I sent the email you answered ... the replies before that (sure you can still see them online) are aimed (I am assuming) at a more advanced level of Python not for a new guy, moreover once those were given and once i started asking how actually that could ever work I got answers arguing that the answer was given... > I must have missed several of those messages you're referring to. I've reviewed all of them, and haven't seen any that argued "the answer was given." The only thing I see like that is Mark Lawrence's mail that simply pointed out the shadowing of the 'object' class. Doesn't sound too argumentative to me. Since your frustrated post was sent in reply to mine, I have to assume that something about mine didn't work for you. The "advanced concepts" were iter() and next(), both very useful Python constructs. If you didn't understand them, why not ask about them? next() is there precisely to solve problems of this type. Using that approach gives you two named variables, one for the even numbered lines, and one for the odd ones. Or perhaps you were frustrated by my comment about having an even number of lines in the B.txt file. Your response was that you can't be sure of that. Well, every sample code in this thread had the same limitation; they'd blow up if you gave them an odd number of lines. Or perhaps you were annoyed that my fix for that involved reading the whole file into memory. Well, so did every other sample, including your original one. it did NOT involve writing anything to the file on disk, nor was it slow to append a line to the end of an in-memory list. And if Walter's assumption about the keyline is correct, then my first solution didn't involve reading the whole B.txt into memory at once. Were you frustrated that I asked questions about the files? Clearly, both Walter and Joel had different conclusions about the file format than I. For example, Joel's solution will find a key if it happens to appear somewhere inside the data line for a different key. And Walter's makes the assumption that the keyline contains exactly the key, and not other text as you had told me. Both of them assume that there will not be a match on the last line of the B.txt file. Clearly I messed up somewhere, but I don't see it. -- DaveA From alan.gauld at btinternet.com Thu May 10 18:56:39 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 May 2012 17:56:39 +0100 Subject: [Tutor] odd behavior when renaming a file In-Reply-To: References: Message-ID: On 09/05/12 20:26, Joel Goldstick wrote: > import os > def pre_process(): > if os.path.isfile('revelex.csv'): > os.rename('revelex.csv', 'revelex.tmp') > print "Renamed ok" > else: > print "Exiting, no revelex.csv file available" > exit() > out_file = open('revelex.csv', 'w') > # etc. > When I run the code above it works file if run from the file. But > when I import it and run it from another file it renames the file but > then prints "Exiting, no revelex.csv file available" I don;t know the reason but are you sure you want to open the file that you have just renamed? def pre_process(): if os.path.isfile('revelex.csv'): os.rename('revelex.csv', 'revelex.tmp') ... out_file = open('revelex.csv', 'w') # etc. I would expect the open() to fail... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From joel.goldstick at gmail.com Thu May 10 18:59:56 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 10 May 2012 12:59:56 -0400 Subject: [Tutor] odd behavior when renaming a file In-Reply-To: References: Message-ID: On Wed, May 9, 2012 at 5:21 PM, Peter Otten <__peter__ at web.de> wrote: > Joel Goldstick wrote: > >> import os >> def pre_process(): >> ? ? if os.path.isfile('revelex.csv'): >> ? ? ? ? os.rename('revelex.csv', 'revelex.tmp') >> ? ? ? ? print "Renamed ok" >> ? ? else: >> ? ? ? ? print "Exiting, no revelex.csv file available" >> ? ? ? ? exit() >> ? ? out_file = open('revelex.csv', 'w') >> ? ? # etc. >> >> if __name__ == '__main__': >> ? ? pre_process() >> >> >> When I run the code above it works file if run from the file. ?But >> when I import it and run it from another file it renames the file but >> then prints "Exiting, no revelex.csv file available" > > Add > > print os.getcwd() > > to your code, you are probably in the wrong directory. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Thanks for the hint. I am in the right directory, but I failed to notice that I renamed the file before I entered my function. Funny how a night of sleep can make dumb mistakes pop out. -- Joel Goldstick From d at davea.name Thu May 10 22:18:47 2012 From: d at davea.name (Dave Angel) Date: Thu, 10 May 2012 16:18:47 -0400 Subject: [Tutor] odd behavior when renaming a file In-Reply-To: References: Message-ID: <4FAC22A7.3030002@davea.name> On 05/10/2012 12:56 PM, Alan Gauld wrote: > On 09/05/12 20:26, Joel Goldstick wrote: >> import os >> def pre_process(): >> if os.path.isfile('revelex.csv'): >> os.rename('revelex.csv', 'revelex.tmp') >> print "Renamed ok" >> else: >> print "Exiting, no revelex.csv file available" >> exit() >> out_file = open('revelex.csv', 'w') >> # etc. > >> When I run the code above it works file if run from the file. But >> when I import it and run it from another file it renames the file but >> then prints "Exiting, no revelex.csv file available" > > I don;t know the reason but are you sure you want to open the file > that you have just renamed? > > def pre_process(): > if os.path.isfile('revelex.csv'): > os.rename('revelex.csv', 'revelex.tmp') > ... > out_file = open('revelex.csv', 'w') > # etc. > > I would expect the open() to fail... > But he's opening it for WRITE, so it gets created just fine. -- DaveA From joel.goldstick at gmail.com Thu May 10 23:02:08 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 10 May 2012 17:02:08 -0400 Subject: [Tutor] odd behavior when renaming a file In-Reply-To: <4FAC22A7.3030002@davea.name> References: <4FAC22A7.3030002@davea.name> Message-ID: On Thu, May 10, 2012 at 4:18 PM, Dave Angel wrote: > On 05/10/2012 12:56 PM, Alan Gauld wrote: >> On 09/05/12 20:26, Joel Goldstick wrote: >>> import os >>> def pre_process(): >>> ? ? ?if os.path.isfile('revelex.csv'): >>> ? ? ? ? ?os.rename('revelex.csv', 'revelex.tmp') >>> ? ? ? ? ?print "Renamed ok" >>> ? ? ?else: >>> ? ? ? ? ?print "Exiting, no revelex.csv file available" >>> ? ? ? ? ?exit() >>> ? ? ?out_file = open('revelex.csv', 'w') >>> ? ? ?# etc. >> >>> When I run the code above it works file if run from the file. ?But >>> when I import it and run it from another file it renames the file but >>> then prints "Exiting, no revelex.csv file available" >> >> I don;t know the reason but are you sure you want to open the file >> that you have just renamed? >> >> def pre_process(): >> ? ? ? if os.path.isfile('revelex.csv'): >> ? ? ? ? ? os.rename('revelex.csv', 'revelex.tmp') >> ... >> ? ? ? out_file = open('revelex.csv', 'w') >> ? ? ? # etc. >> >> I would expect the open() to fail... >> > > But he's opening it for WRITE, so it gets created just fine. > > > > -- > > DaveA > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I have to process a csv file from a business partner. Oddly (?) they don't quote text fields, and the Title field sometimes contains commas. So I wrote some code to count the commas in each line and if there were too many, I removed the extras and wrote the cleaned up file to the original filename for the rest of what I have to with that data -- Joel Goldstick From alan.gauld at btinternet.com Thu May 10 23:05:57 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 10 May 2012 22:05:57 +0100 Subject: [Tutor] odd behavior when renaming a file In-Reply-To: <4FAC22A7.3030002@davea.name> References: <4FAC22A7.3030002@davea.name> Message-ID: On 10/05/12 21:18, Dave Angel wrote: >> out_file = open('revelex.csv', 'w') >> # etc. >> >> I would expect the open() to fail... > > But he's opening it for WRITE, so it gets created just fine. Ah yes, I didn't spot that. :-) Too busy looking for a possible cause of a missing file message... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Thu May 10 23:05:13 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 10 May 2012 21:05:13 +0000 Subject: [Tutor] odd behavior when renaming a file In-Reply-To: References: <4FAC22A7.3030002@davea.name> Message-ID: <5B80DD153D7D744689F57F4FB69AF4740930ED04@SCACMX008.exchad.jpmchase.net> > I have to process a csv file from a business partner. Oddly (?) they > don't quote text fields, and the Title field sometimes contains > commas. So I wrote some code to count the commas in each line and if > there were too many, I removed the extras and wrote the cleaned up > file to the original filename for the rest of what I have to with that > data That is terrible (of them). How do you determine which comma is the "extra"? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From joel.goldstick at gmail.com Thu May 10 23:47:00 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 10 May 2012 17:47:00 -0400 Subject: [Tutor] odd behavior when renaming a file In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4740930ED04@SCACMX008.exchad.jpmchase.net> References: <4FAC22A7.3030002@davea.name> <5B80DD153D7D744689F57F4FB69AF4740930ED04@SCACMX008.exchad.jpmchase.net> Message-ID: On Thu, May 10, 2012 at 5:05 PM, Prasad, Ramit wrote: >> I have to process a csv file from a business partner. ?Oddly (?) they >> don't quote text fields, and the Title field sometimes contains >> commas. ?So I wrote some code to count the commas in each line and if >> there were too many, I removed the extras and wrote the cleaned up >> file to the original filename for the rest of what I have to with that >> data > > That is terrible (of them). How do you determine which comma is the "extra"? Yes, it is kinda disheartening, but I don't know if they distribute this file to others, and changing it might have ramifications. I take the line and split it on commas. Then get the length of the list. If its greater than 8, I append the item in the list that is after the Title field (I don't have the code with me -- i think its the 6th item) to the field that is the beginning of the title. Then I remove (pop) that field. Lather, rinse, repeat until there are 8 elements in the list. Then I join the list back with commas and write to the output file. > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > -- > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick From swordangel at gmail.com Fri May 11 05:41:45 2012 From: swordangel at gmail.com (Kal Sze) Date: Fri, 11 May 2012 11:41:45 +0800 Subject: [Tutor] Prescriptive vs descriptive docstring Message-ID: Hello, PEP 257 says that docstrings should be written in a prescriptive way (i.e. using the imperative mood) instead of a descriptive way (indicative mood). This seems like a rather odd recommendation. Since the docstring is supposed to tell the programmer *how* to use a function/method, I've always thought that a description in the indicative mood is appropriate. What's the point in saying it like a command? Who are you "commanding" when what you really want is to learn what the function/method does? In Javadoc and XML doc (Java's and .NET's equivalent to docstrings), the de-facto convention is to use the indicative mood (as can be seen in the whole standard java class library and .net class library). Is this difference somehow a corollary of the difference in programming paradigms? Was there a discussion in doc-sig at python.org about the reason(s) to use the imperative mood instead of the indicative mood, which then led to the recommendation in PEP 257? Best Regards, Kal -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri May 11 09:23:32 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 May 2012 08:23:32 +0100 Subject: [Tutor] Prescriptive vs descriptive docstring In-Reply-To: References: Message-ID: On 11/05/12 04:41, Kal Sze wrote: > PEP 257 says that docstrings should be written in a prescriptive way > (i.e. using the imperative mood) instead of a descriptive way > (indicative mood). This seems like a rather odd recommendation. Since > the docstring is supposed to tell the programmer *how* to use a > function/method, This might be down to interpretation of the terms. To me it means the docstring should tell, or instruct, the user how to use the function. It should not describe what the function does or how it does it (the internal logic). > command? Who are you "commanding" when what you really want is to learn > what the function/method does? It's commanding (or instructing) the user on how to use the function. You don't need to know what its doing internally, only how to use it. It tells me that if I push these things in, it will give me that thing back. But that's just how I interpret it. Somebody else may have a more definitive explanation. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bjorn.h.madsen at googlemail.com Fri May 11 20:42:06 2012 From: bjorn.h.madsen at googlemail.com (Bjorn Madsen) Date: Fri, 11 May 2012 19:42:06 +0100 Subject: [Tutor] pip errors for numpy, scipy matplotlib Message-ID: Hi, when attempting to use pip to install numpy, scipy matplotlib I get a mile of errors. There is simply too much information printed - so it must be a systematic error (http://paste.ubuntu.com/982180/). What am I missing/doing wrong? Kind Regards, Bjorn -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Fri May 11 20:52:42 2012 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 11 May 2012 14:52:42 -0400 Subject: [Tutor] pip errors for numpy, scipy matplotlib In-Reply-To: References: Message-ID: On Fri, May 11, 2012 at 2:42 PM, Bjorn Madsen wrote: > Hi, > when attempting to use pip to install numpy, scipy matplotlib I get a mile > of errors. There is simply too much information printed - so it must be a > systematic error?(http://paste.ubuntu.com/982180/).?What am I missing/doing > wrong? The error messages sound like you're missing a bunch of the thing required to build the packages you're trying to compile. It looks like libraries called Atlas and Blas, plus a fortran compiler, from the errors you posted. Are you using ubuntu? You didn't say, but I see you're using a ubuntu pastebin. Are you wedded to compiling and installing with pip? It's a whole lot easier to just use the packaging system included with ubuntu when you can. In this case you should be able to do `sudo apt-get install python-numpy` to install numpy. If you do want to compile and build via pip, I would start by doing `sudo apt-get build-dep python-numpy` to get all the required prerequisites installed, then retry installing via pip. -- Jerry From steve at pearwood.info Sat May 12 04:21:11 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 May 2012 12:21:11 +1000 Subject: [Tutor] Prescriptive vs descriptive docstring In-Reply-To: References: Message-ID: <4FADC917.5040803@pearwood.info> Kal Sze wrote: > Hello, > > PEP 257 says that docstrings should be written in a prescriptive way (i.e. > using the imperative mood) instead of a descriptive way (indicative mood). PEP 257: http://www.python.org/dev/peps/pep-0257/ For those who don't know English grammatical terms, here are some examples. Imperative mood: - "Return the number of widgets in a set." - "Control access to the phlebotinum." - "Set the printer on fire." Indicative mood: - "[This function] returns the number of widgets in a set." - "[This class] controls access to the phlebotinum." - "[This method] sets the printer on fire." > This seems like a rather odd recommendation. Since the docstring is > supposed to tell the programmer *how* to use a function/method, I've always > thought that a description in the indicative mood is appropriate. What's > the point in saying it like a command? Who are you "commanding" when what > you really want is to learn what the function/method does? "You" is the person writing the doc string, that is, the person writing the code (or someone working on her behalf). So the imperative mood is commanding the computer: "Method, you will set the printer on fire." If I had to guess a reason why this convention exists, it would be that some people don't like implying the subject of the imperative mood, or think it is ungrammatical to say "Sets the printer on fire" without stating who or what sets the printer on fire. But it gets tiresome very, very quickly to preface every doc string with "This function...", "This method..." etc. But as I said, that's a guess. > In Javadoc and XML doc (Java's and .NET's equivalent to docstrings), the > de-facto convention is to use the indicative mood (as can be seen in the > whole standard java class library and .net class library). > > Is this difference somehow a corollary of the difference in programming > paradigms? I doubt it. I suspect it was just somebody's personal preference. Personally, I don't pay too much attention to PEP 257. Some attention, but I don't follow it slavishly. And neither does the standard library -- for example, the decimal module has a mix of imperative and indicative mood in the doc strings. In any case, unless you are writing for the Python standard library, nobody can force you to follow PEP 257. It may be *recommended*, but you are free to ignore it, and take the consequences. > Was there a discussion in doc-sig at python.org about the reason(s) to use the > imperative mood instead of the indicative mood, which then led to the > recommendation in PEP 257? You would be better off asking on doc-sig@ or python-dev at python.org. -- Steven From steve at pearwood.info Sat May 12 05:21:39 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 May 2012 13:21:39 +1000 Subject: [Tutor] Sorting the Parts of a Dictionary into a List In-Reply-To: References: Message-ID: <4FADD743.7060903@pearwood.info> Jacob Bender wrote: > The total function works when it returns the strength of a neuron, but I > don't think the "sorted" function is the best because, with its current > configuration, it returns a type error. I have been doing python for > several years now. I don't know EVERYTHING there is to know, but I am able > to do most tasks without error. Please help me get the neurons into an > order in a list as described in my original email. Also, I do thank you for > your original replies! Jacob, please read this article, for some excellent advice about asking for help: http://sscce.org/ This will help us to help you. -- Steven From allen.fowler at yahoo.com Sat May 12 12:29:23 2012 From: allen.fowler at yahoo.com (allen.fowler at yahoo.com) Date: Sat, 12 May 2012 03:29:23 -0700 (PDT) Subject: [Tutor] (no subject) Message-ID: <1336818563.32925.YahooMailNeo@web114007.mail.gq1.yahoo.com> http://laespecialeu.com/gdfgdsf/lightbox/thjfle.html?bnd=fhttd.gve&dd=rd.fhr&sw=xrsq -------------- next part -------------- An HTML attachment was scrubbed... URL: From locci.carlo.1985 at gmail.com Sat May 12 22:43:58 2012 From: locci.carlo.1985 at gmail.com (carlo locci) Date: Sat, 12 May 2012 22:43:58 +0200 Subject: [Tutor] threading mind set Message-ID: Hello All, I've started to study python a couple of month ago(and I truly love it :)), however I'm having some problems understanding how to modify a sequential script and make it multithreaded (I think it's because I'm not used to think in that way), as well as when it's best to use it(some say that because of the GIL I won't get any real benefit from threading my script). It's my understanding that threading a program in python can be useful when we've got some I/O involved, so here is my case, I wrote a quite simple script that reads the first column from a csv file and insert every row of the value into a tuple, then I created a function which gets me the size of a given path/folder and I made it loop so that it'll print the the folder dimension of each path is in the tuple previously created. Here's the code: * def read():* * import csv* * with open('C:\\test\\VDB.csv', 'rb') as somefile:* * read = csv.reader(somefile)* * l = []* * for row in read:* * l += row* * return l* * * *def DirGetSize(cartella):* * import os* * cartella_size = 0* * for (path, dirs, files) in os.walk(cartella):* * for x in files:* * filename = os.path.join(path, x)* * cartella_size += os.path.getsize(filename)* * return cartella_size* * * *import os.path* *for x in read():* * if not os.path.exists(x):* * print ' DOES NOT EXIST ON', x* * else:* * S = DirGetSize(x)* * print 'the file size of', x, 'is',S* * * The script works quite well(at least does what I want), but my real question is will I gain any better performance, in terms of speed, out of it, if I multithread it? The csv file contains a list of server/path/folder therefore I though that If I would multitread it I's gonna became much faster since it will perform the *DirGetSize,* function almost concurrently, although I'm quite confused by the subject, so I'm not really sure. I would really appreciate anyone who would make me understand when it's useful to implement a multreaded script and when it's not and why :),(Maybe I'm asking to much), as well as any good resources where I can study from. Thank you in advance to anyone who will reply me as well as thank you for having such a mailinglist(I discovered it when I had watched a google I/O conference on youtube). Thank you guys. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tokyo.rook at gmail.com Sun May 13 00:34:28 2012 From: tokyo.rook at gmail.com (Keitaro Kaoru) Date: Sat, 12 May 2012 18:34:28 -0400 Subject: [Tutor] (no subject) Message-ID: hey i keep having a problem with adding commands.. i get this error message Traceback (most recent call last): File "bot.py", line 23, in import modules.core, modules.ai, modules.dict, modules.fun, modules.kc, modules.games, modules.lulz2, modules.modding, modules.meta, modules.mpd, modules.post, modules.poll, modules.util, modules.yt File "/home/digest/digest/modules/core.py", line 170 def pm(mgr, room, user, msg, args): ^ SyntaxError: invalid syntax worked fine before i edited a command in front of it... -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun May 13 01:29:58 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 13 May 2012 09:29:58 +1000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4FAEF276.40405@pearwood.info> Keitaro Kaoru wrote: > hey i keep having a problem with adding commands.. i get this error message > > Traceback (most recent call last): > File "bot.py", line 23, in > import modules.core, modules.ai, modules.dict, modules.fun, modules.kc, > modules.games, modules.lulz2, modules.modding, modules.meta, modules.mpd, > modules.post, modules.poll, modules.util, modules.yt > File "/home/digest/digest/modules/core.py", line 170 > def pm(mgr, room, user, msg, args): > ^ > SyntaxError: invalid syntax > > worked fine before i edited a command in front of it... Hint: when you change something, and things break, check the thing you changed. In this case, I would expect that you haven't closed a set of brackets: you're probably missing a ) ] or }, most likely a ). The parser sometimes can't detect missing close-brackets until the line *following* the error. -- Steven From steve at pearwood.info Sun May 13 02:22:04 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 13 May 2012 10:22:04 +1000 Subject: [Tutor] threading mind set In-Reply-To: References: Message-ID: <4FAEFEAC.8000403@pearwood.info> carlo locci wrote: > Hello All, > I've started to study python a couple of month ago(and I truly love it :)), > however I'm having some problems understanding how to modify a sequential > script and make it multithreaded (I think it's because I'm not used to > think in that way), No, that's because multithreading and parallel processing is hard. > as well as when it's best to use it(some say that > because of the GIL I won't get any real benefit from threading my script). That depends on what your script does. In a nutshell, if your program is limited by CPU processing, then using threads in Python won't help. (There are other things you can do instead, such as launching new Python processes.) If your program is limited by disk or network I/O, then there is a possibility you can speed it up with threads. > It's my understanding that threading a program in python can be useful when > we've got some I/O involved, To see the benefit of threads, it's not enough to have "some" I/O, you need *lots* of I/O. Threads have some overhead. Unless you save at least as much time as just starting and managing the threads consumes, you won't see any speed up. In my experience, for what little it's worth [emphasis on "little"], unless you can keep at least four threads busy doing separate I/O, it probably isn't worth the time and effort. And it's probably not worth it for trivial scripts -- who cares if you speed your script up from 0.2 seconds to 0.1 seconds? But as a learning exercise, sure, go ahead and convert your script to threads. One experiment is worth a dozen opinions. You can learn more about threading from here: http://www.doughellmann.com/PyMOTW/threading/ By the way, in future, please don't decorate your code with stars: > * def read():* > * import csv* > * with open('C:\\test\\VDB.csv', 'rb') as somefile:* [...] We should be able to copy and paste your code and have it run immediately, not have to spend time editing it by hand to turn it back into valid Python code that doesn't give a SyntaxError on every line. See also this: http://sscce.org/ -- Steven From bgailer at gmail.com Sun May 13 04:28:12 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 12 May 2012 22:28:12 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4FAF1C3C.2060307@gmail.com> On 5/12/2012 6:34 PM, Keitaro Kaoru wrote: > hey i keep having a problem with adding commands.. i get this error > message > > Traceback (most recent call last): > File "bot.py", line 23, in > import modules.core, modules.ai , modules.dict, > modules.fun, modules.kc, modules.games, modules.lulz2, > modules.modding, modules.meta, modules.mpd, modules.post, > modules.poll, modules.util, modules.yt > File "/home/digest/digest/modules/core.py", line 170 > def pm(mgr, room, user, msg, args): > ^ > SyntaxError: invalid syntax > Thanks for posting the traceback. All we need is to see more of the program (especially the lines before the one you posted. It is always a good idea to post more of the code regardless of the problem. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun May 13 04:29:08 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 12 May 2012 22:29:08 -0400 Subject: [Tutor] syntax error In-Reply-To: References: Message-ID: <4FAF1C74.8070008@gmail.com> oh - and always provide a specific meaningful subject -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Sun May 13 04:45:23 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 12 May 2012 22:45:23 -0400 Subject: [Tutor] threading mind set In-Reply-To: <4FAEFEAC.8000403@pearwood.info> References: <4FAEFEAC.8000403@pearwood.info> Message-ID: <4FAF2043.3080500@gmail.com> On 5/12/2012 8:22 PM, Steven D'Aprano wrote: > By the way, in future, please don't decorate your code with stars: I think you got stars because the code was posted in HTML and bolded. Plain text readers add the * to show emphasis. When i copied and pasted the code it came out fine. carlo: in future please post plain text rather than HTML. -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Sun May 13 04:47:00 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 12 May 2012 22:47:00 -0400 Subject: [Tutor] threading mind set In-Reply-To: References: Message-ID: <4FAF20A4.8080906@gmail.com> def read(): couple of observations 1 - it is customary to put all import statements at the beginning of the file. 2 - it is customary to begin variable and function names with a lower case letter. 3 - it is better to avoid using built-in function names common method names (e.g. read). def read(): import csv with open('C:\\test\\VDB.csv', 'rb') as somefile: read = csv.reader(somefile) l = [] for row in read: l += row return l def DirGetSize(cartella): import os cartella_size = 0 for (path, dirs, files) in os.walk(cartella): for x in files: filename = os.path.join(path, x) cartella_size += os.path.getsize(filename) return cartella_size import os.path for x in read(): if not os.path.exists(x): print ' DOES NOT EXIST ON', x else: S = DirGetSize(x) print 'the file size of', x, 'is',S -- Bob Gailer 919-636-4239 Chapel Hill NC From jeanpierreda at gmail.com Sun May 13 05:19:15 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 12 May 2012 23:19:15 -0400 Subject: [Tutor] syntax error In-Reply-To: <4FAF1C74.8070008@gmail.com> References: <4FAF1C74.8070008@gmail.com> Message-ID: On Sat, May 12, 2012 at 10:29 PM, bob gailer wrote: > oh - and always provide a specific meaningful subject My client has no idea what thread this post came from. Is it supposed to? -- Devin From jeanpierreda at gmail.com Sun May 13 05:31:23 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 12 May 2012 23:31:23 -0400 Subject: [Tutor] Auto-response for your message to the "Tutor" mailing list In-Reply-To: References: Message-ID: This is the third time I've received a message "for those of you new to the Tutor list". When does it stop? -- Devin On Sat, May 12, 2012 at 11:19 PM, wrote: > Your message for tutor at python.org, the Python programming tutor list, > has been received and is being delivered. ?This automated response is > sent to those of you new to the Tutor list, to point out a few > resources that can help with answering your own questions, or improve > the chances of getting a useful answer from the other subscribers. > > If your question is something akin to: > > ? ?"I've just heard about Python, and it sounds great! ?Where can I > ? ? find out more on how to program with Python?" > > ?or: > > ? ? "What's Python?" > > please read section 1 below. > > On the other hand, if your question is: > > ? ?"I've heard that Python is good for hacking -- I want to know > more!" > > ?or > > ? ?"Can you teach me how to break into a computer with Python?" > > please read section 2 at the bottom of this email. > > Section 1: ---------- > > The most comprehensive overview of python.org help resources is at > > ?http://www.python.org/Help.html > > The Python FAQ is available at > > ?http://www.python.org/doc/FAQ.html > > and it has answers to many questions that people ask, possibly > including your question. ?Another wealth of information and experience > can be found via the python.org searches, at > > ?http://www.python.org/search/ > > There you'll find comprehensive, easy-to-use searches over the > python.org web site and the Python newsgroup, comp.lang.python. > > Python has an online tutorial, available freely from > > ?http://www.python.org/doc/current/tutorial/index.html > > Finally, when you do send email to the Tutor list, be as clear as you > can about the problem, including, when relevant, details like: > > ?- Precise error messages, including complete tracebacks > ?- The hardware platform (available in the Python sys module as > sys.platform) > ?- The python version (sys.version) > ?- The python search path (sys.path) > > In general, be specific about what was going on connected with the > problem or what specific concept you're having difficulties with. ?The > better the info you provide, the more likely the helpers will be able > to glean the answer... > > There's a HOWTO that shows how to ask "smart" questions to technical > folks: > > http://catb.org/~esr/faqs/smart-questions.html > > Although it is provocative, it does have some good points, and is an > interesting read. > > > Note that no one is paid to read the tutor list or provide answers, > and most readers often have other work that demands their attention. > Well-posed requests for help are usually answered fairly promptly, but > occasionally a request slips by, so if you do not get a response with > one or two working days (it's usually quicker than that), please feel > free to send a followup, asking whether anyone is working on your > question. > > Anyway, your message is being delivered to the Tutor list as this one > is being sent. ?However, if your question was about as detailed as > "Teach me how to program in Python", do not count on an answer -- this > email contains all the information you need to start. ?Come back with > a more precise question, and we'll be glad to help. > > > Thanks! > > Section 2: ---------- > > We periodically get requests which ask about hacking or cracking or > breaking into computers. ?If you haven't yet, go read Eric Raymond's > article "How To Become a Hacker" at > ?http://catb.org/esr/faqs/hacker-howto.html > > If, after you've read that, you want help learning how to hack the way > Eric defines the word, then come back to us (and read Section 1 > above). ?If you want help learning how to crack, go look elsewhere -- > we're not interested in helping you do that. From steve at pearwood.info Sun May 13 08:21:11 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 13 May 2012 16:21:11 +1000 Subject: [Tutor] Auto-response for your message to the "Tutor" mailing list In-Reply-To: References: Message-ID: <4FAF52D7.60500@pearwood.info> Devin Jeanpierre wrote: > This is the third time I've received a message "for those of you new > to the Tutor list". When does it stop? The problem isn't getting it to stop. The problem is getting it to not start up again. I too occasionally get these "Welcome" messages, about once every twenty or thirty posts. (Estimated.) -- Steven From steve at pearwood.info Sun May 13 09:10:49 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 13 May 2012 17:10:49 +1000 Subject: [Tutor] threading mind set In-Reply-To: <4FAF2043.3080500@gmail.com> References: <4FAEFEAC.8000403@pearwood.info> <4FAF2043.3080500@gmail.com> Message-ID: <4FAF5E79.2020408@pearwood.info> bob gailer wrote: > On 5/12/2012 8:22 PM, Steven D'Aprano wrote: >> By the way, in future, please don't decorate your code with stars: > I think you got stars because the code was posted in HTML and bolded. > Plain text readers add the * to show emphasis. I think you have it the other way around: if you add asterisks around text, some plain text readers hide the * and bold the text. At least, I've never seen anything which does it the other way around. (Possibly until now.) In any case, I'm using Thunderbird, and it does NOT show stars around text unless they are already there. When I look at the raw email source, I can see the asterisks there. Perhaps Carlo's mail client is trying to be helpful, and failing miserably. While converting HTML tags into simple markup is a nice thing to do for plain text, it plays havoc with code. -- Steven From alan.gauld at btinternet.com Sun May 13 10:17:18 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 May 2012 09:17:18 +0100 Subject: [Tutor] Auto-response for your message to the "Tutor" mailing list In-Reply-To: <4FAF52D7.60500@pearwood.info> References: <4FAF52D7.60500@pearwood.info> Message-ID: On 13/05/12 07:21, Steven D'Aprano wrote: > Devin Jeanpierre wrote: >> This is the third time I've received a message "for those of you new >> to the Tutor list". When does it stop? I think these come when the listserver gets a message from a mailbox it doesn't recognise. It puts the mails in the moderation queue and sends the message(it used to send one to the moderators too but seems to have stopped doing that! :-( So if you are not subscribed to the list, or are subscribed but using a different mail address then you get one of these messages. I think.... But the settings of the sever are cloaked in mystery! :-) And that reminds me that I haven't checked the mod queue for over a week - oops! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun May 13 11:44:27 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 13 May 2012 19:44:27 +1000 Subject: [Tutor] syntax error In-Reply-To: References: <4FAF1C74.8070008@gmail.com> Message-ID: <4FAF827B.4040209@pearwood.info> Devin Jeanpierre wrote: > On Sat, May 12, 2012 at 10:29 PM, bob gailer wrote: >> oh - and always provide a specific meaningful subject > > My client has no idea what thread this post came from. > > Is it supposed to? What's your client? I'm using Thunderbird, and it too doesn't have any idea. I see that Bob's email does have an In-Reply-To header: In-Reply-To: and if I look at the email which started this thread, Keitaro Kaoru's email with no subject line, I see it has the same message ID: Message-ID: so my guess is that Thunderbird is just stupid. -- Steven From d at davea.name Sun May 13 12:05:43 2012 From: d at davea.name (Dave Angel) Date: Sun, 13 May 2012 06:05:43 -0400 Subject: [Tutor] Auto-response for your message to the "Tutor" mailing list In-Reply-To: References: <4FAF52D7.60500@pearwood.info> Message-ID: <4FAF8777.5000200@davea.name> On 05/13/2012 04:17 AM, Alan Gauld wrote: > On 13/05/12 07:21, Steven D'Aprano wrote: >> Devin Jeanpierre wrote: >>> This is the third time I've received a message "for those of you new >>> to the Tutor list". When does it stop? > > I think these come when the listserver gets a message from a mailbox > it doesn't recognise. It puts the mails in the moderation queue and > sends the message(it used to send one to the moderators too but seems > to have stopped doing that! :-( > > So if you are not subscribed to the list, or are subscribed but using > a different mail address then you get one of these messages. > > I think.... But the settings of the sever are cloaked in mystery! :-) > > And that reminds me that I haven't checked the mod queue for over a > week - oops! > I also seem to get one of these when I haven't posted for a couple of weeks. I never tried to calibrate it, but that's what it seems to be. Perhaps it's keeping a cache of recent posters, and once I'm flushed from the cache, it considers me new. This is different from the case where I post from a different address. In that case, I get a mail saying that only subscribers can post. Or something like that. -- DaveA From d at davea.name Sun May 13 12:09:38 2012 From: d at davea.name (Dave Angel) Date: Sun, 13 May 2012 06:09:38 -0400 Subject: [Tutor] syntax error In-Reply-To: <4FAF827B.4040209@pearwood.info> References: <4FAF1C74.8070008@gmail.com> <4FAF827B.4040209@pearwood.info> Message-ID: <4FAF8862.5070708@davea.name> On 05/13/2012 05:44 AM, Steven D'Aprano wrote: > Devin Jeanpierre wrote: >> On Sat, May 12, 2012 at 10:29 PM, bob gailer wrote: >>> oh - and always provide a specific meaningful subject >> >> My client has no idea what thread this post came from. >> >> Is it supposed to? > > > What's your client? I'm using Thunderbird, and it too doesn't have any > idea. > > I see that Bob's email does have an In-Reply-To header: > > In-Reply-To: > > > and if I look at the email which started this thread, Keitaro Kaoru's > email with no subject line, I see it has the same message ID: > > Message-ID: > > > > so my guess is that Thunderbird is just stupid. > > But my copy of Thunderbird (12.0.1, running on Linux) recognized these as being the same thread as Keitaro Kaoru's message, and combined them properly. -- DaveA From jeanpierreda at gmail.com Sun May 13 12:22:08 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 13 May 2012 06:22:08 -0400 Subject: [Tutor] syntax error In-Reply-To: <4FAF827B.4040209@pearwood.info> References: <4FAF1C74.8070008@gmail.com> <4FAF827B.4040209@pearwood.info> Message-ID: On Sun, May 13, 2012 at 5:44 AM, Steven D'Aprano wrote: > Devin Jeanpierre wrote: >> >> On Sat, May 12, 2012 at 10:29 PM, bob gailer wrote: >>> >>> oh - and always provide a specific meaningful subject >> >> >> My client has no idea what thread this post came from. >> >> Is it supposed to? > > > > What's your client? I'm using Thunderbird, and it too doesn't have any idea. The gmail web interface. > I see that Bob's email does have an In-Reply-To header: > > In-Reply-To: > > > and if I look at the email which started this thread, Keitaro Kaoru's email > with no subject line, I see it has the same message ID: > > Message-ID: > > > > so my guess is that Thunderbird is just stupid. Welp. Not much I can do here. I should probably switch to a desktop client at some point. Thanks for the detective work. -- Devin From alan.gauld at btinternet.com Sun May 13 13:38:29 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 May 2012 12:38:29 +0100 Subject: [Tutor] syntax error In-Reply-To: <4FAF827B.4040209@pearwood.info> References: <4FAF1C74.8070008@gmail.com> <4FAF827B.4040209@pearwood.info> Message-ID: On 13/05/12 10:44, Steven D'Aprano wrote: > and if I look at the email which started this thread, Keitaro Kaoru's > email with no subject line, I see it has the same message ID: > > Message-ID: > > > > so my guess is that Thunderbird is just stupid. Like Dave I am on Thunderbird 12 and it is threading the messages just fine... But I never noticed a problem with T/Bird 3.1 either. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From russel at winder.org.uk Sun May 13 13:43:26 2012 From: russel at winder.org.uk (Russel Winder) Date: Sun, 13 May 2012 12:43:26 +0100 Subject: [Tutor] threading mind set In-Reply-To: <4FAEFEAC.8000403@pearwood.info> References: <4FAEFEAC.8000403@pearwood.info> Message-ID: <1336909406.19220.290.camel@launcelot.winder.org.uk> Steven, On Sun, 2012-05-13 at 10:22 +1000, Steven D'Aprano wrote: > carlo locci wrote: > > Hello All, > > I've started to study python a couple of month ago(and I truly love it :)), > > however I'm having some problems understanding how to modify a sequential > > script and make it multithreaded (I think it's because I'm not used to > > think in that way), > > No, that's because multithreading and parallel processing is hard. Shared memory multithreading may be hard due to locks, semaphores, monitors, etc., but concurrency and parallelism need not be hard. Using processes and message passing, using dataflow, actors or CSP, parallelism and concurrency is far more straightforward. Not easy, agreed, but then programming isn't easy. > > as well as when it's best to use it(some say that > > because of the GIL I won't get any real benefit from threading my script). > > That depends on what your script does. > > In a nutshell, if your program is limited by CPU processing, then using > threads in Python won't help. (There are other things you can do instead, such > as launching new Python processes.) The GIL in Python is a bad thing for parallelism. Using the multiprocessing package or concurrent.futures gets over the problem. Well sort of, these processes are a bit heavyweight compared to what can be achieved on the JVM or with Erlang. > If your program is limited by disk or network I/O, then there is a possibility > you can speed it up with threads. Or better still use an event based system, cf Twisted. [...] > -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From suryak at live.com Sun May 13 17:08:55 2012 From: suryak at live.com (Surya K) Date: Sun, 13 May 2012 20:38:55 +0530 Subject: [Tutor] How to start developing a website Message-ID: I have a idea (Website) which I want to develop using Django (Still learning it!). Currently I am following DjangoBook (reading DataBase..). As I am really new to webframe works and Web development, I have a real dumb question which I don't really figure out. # Question: Broadly speaking my website takes a RSS/Atom feed and try to display dynamic content on its page. So, with what ever I know about django until now, all I can say that my project can handle creating dynamic content with django but I don't figure out how to really "design" it. I mean how to "design the UI part.. ".. One way of doing is to explicitly edit the Django's HTML pages using HTML, CSS, JavaScript from scratch. But I only know little HTML (I cannot do the design with what I know). So, how can I achieve this thing.. I thought of using Adobe's Dreamweaver or any equivalent open source thing but their generated HTML code can't be easily edited for "django" template designing.. Can anyone explain me on it.. Thanks a lot Surya -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sun May 13 17:40:45 2012 From: emile at fenx.com (Emile van Sebille) Date: Sun, 13 May 2012 08:40:45 -0700 Subject: [Tutor] How to start developing a website In-Reply-To: References: Message-ID: On 5/13/2012 8:08 AM Surya K said... > I have a idea (Website) which I want to develop using Django (Still > learning it!). Currently I am following DjangoBook (reading DataBase..). > > As I am really new to webframe works and Web development, I have a real > dumb question which I don't really figure out. > > # Question: > > Broadly speaking my website takes a RSS/Atom feed and try to display > dynamic content on its page. Have you already found http://wiki.python.org/moin/RssLibraries ? > So, with what ever I know about django > until now, all I can say that my project can handle creating dynamic > content with django but I don't figure out how to really "design" it. I > mean how to "design the UI part.. ".. > > One way of doing is to explicitly edit the Django's HTML pages using > HTML, CSS, JavaScript from scratch. But I only know little HTML (I > cannot do the design with what I know). > > So, how can I achieve this thing.. Take a look at http://www.djangosites.org/s/patternry-com/ > > I thought of using Adobe's Dreamweaver or any equivalent open source > thing but their generated HTML code can't be easily edited for "django" > template designing.. > > > Can anyone explain me on it.. The folks at Django can -- see https://docs.djangoproject.com/en/dev/faq/help/ for django resources. HTH, Emile From joel.goldstick at gmail.com Sun May 13 18:27:03 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 13 May 2012 12:27:03 -0400 Subject: [Tutor] How to start developing a website In-Reply-To: References: Message-ID: On Sun, May 13, 2012 at 11:40 AM, Emile van Sebille wrote: > On 5/13/2012 8:08 AM Surya K said... > >> I have a idea (Website) which I want to develop using Django (Still >> learning it!). Currently I am following DjangoBook (reading DataBase..). >> >> As I am really new to webframe works and Web development, I have a real >> dumb question which I don't really figure out. >> >> # Question: >> >> Broadly speaking my website takes a RSS/Atom feed and try to display >> dynamic content on its page. > > > Have you already found http://wiki.python.org/moin/RssLibraries ? > > >> So, with what ever I know about django >> until now, all I can say that my project can handle creating dynamic >> content with django but I don't figure out how to really "design" it. I >> mean how to "design the UI part.. ".. >> >> One way of doing is to explicitly edit the Django's HTML pages using >> HTML, CSS, JavaScript from scratch. But I only know little HTML (I >> cannot do the design with what I know). >> >> So, how can I achieve this thing.. > > > Take a look at http://www.djangosites.org/s/patternry-com/ > > >> >> I thought of using Adobe's Dreamweaver or any equivalent open source >> thing but their generated HTML code can't be easily edited for "django" >> template designing.. >> >> >> Can anyone explain me on it.. > > > The folks at Django can -- see > https://docs.djangoproject.com/en/dev/faq/help/ for django resources. > > HTH, > > Emile > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I haven't tried this yet, but I have heard good things about this site: http://twitter.github.com/bootstrap/ There is a tutorial here http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/stepping-out-with-bootstrap-from-twitter/ Basically some people from twitter and elsewhere have put together a package that can be used with django or elsewhere to make designing html and css for webpages. Since you are new to django, I would recommend you just get the most basic site going. You will stumble and learn a lot along the way. After that you can dress it up -- Joel Goldstick From tokyo.rook at gmail.com Mon May 14 01:04:58 2012 From: tokyo.rook at gmail.com (Keitaro Kaoru) Date: Sun, 13 May 2012 19:04:58 -0400 Subject: [Tutor] hello~ Message-ID: hey. Austin here for some reason this command. all it does it produces the error message at the bottom.. itll say my name and the persons name im trying to send the message to but thats it. heres the command. mgr.addCommand("tell", 1, "send a person a message to the rooms he is in", tell, unlisted = True) def tell(mgr, croom, user, msg, args): name = args.lower().split(" ")[0] if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") data = shared_db.get("seen:" + name) if data == None: return Html("I have no records about this user.") data = json.loads(data) for room in mgr.rooms: if data[1] == "join": mgr.sendObject(target, Html("%s, %s wants to tell you %s", name.title, user.name.title$ else: return Error("%s I couldn't find %s anywhere", user.name.title(), name.title()) i built it off these 2 commands def broadcast(mgr, croom, user, msg, args): for room in mgr.rooms: mgr.sendObject(room, Html("Broadcast by %s:%s", user.name, args)) def seen(mgr, room, user, msg, args): name = args.lower().split(" ")[0] if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") data = shared_db.get("seen:" + name) if data == None: return Html("I have no records about this user.") data = json.loads(data) ifdata[1] == "join": return Html("Last seen %s join %s, %s ago.", name, data[0], tdelta(data[2])) elif data[1] == "leave": return Html("Last seen %s leave %s, %s ago.", name, data[0], tdelta(data[2])) elif data[1] == "message": return Html("Last seen %s message in %s, %s ago: \"%s\"", name, data[0], tdelta(data[2]), data[3]) return Html("I have no records about this user.") as you can see i only use some of the command. it doesnt produce an error message tho.. just repeats "return Error("%s I couldn't find %s anywhere", user.name.title(), name.title())" -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon May 14 01:19:43 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 14 May 2012 00:19:43 +0100 Subject: [Tutor] hello~ In-Reply-To: References: Message-ID: On 14/05/2012 00:04, Keitaro Kaoru wrote: > hey. Austin here for some reason this command. all it does it produces the > error message at the bottom.. itll say my name and the persons name im > trying to send the message to but thats it. heres the command. > > mgr.addCommand("tell", 1, "send a person a message to the rooms he is in", > tell, unlisted = True) > > def tell(mgr, croom, user, msg, args): > name = args.lower().split(" ")[0] > if not name.isalnum(): return Html("Non-alphanumeric name, > seriously?") > data = shared_db.get("seen:" + name) > if data == None: > return Html("I have no records about this user.") > data = json.loads(data) > for room in mgr.rooms: > if data[1] == "join": > mgr.sendObject(target, Html("%s, color='#3399CC'>%s wants to tell you%s", > name.title, user.name.title$ > else: > return Error("%s I couldn't find %s > anywhere", user.name.title(), name.title()) > > i built it off these 2 commands > > def broadcast(mgr, croom, user, msg, args): > for room in mgr.rooms: > mgr.sendObject(room, Html("Broadcast by%s:%s", > user.name, args)) > > def seen(mgr, room, user, msg, args): > name = args.lower().split(" ")[0] > if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") > data = shared_db.get("seen:" + name) > if data == None: > return Html("I have no records about this user.") > data = json.loads(data) > ifdata[1] == "join": > return Html("Last seen%s join%s,%s ago.", name, > data[0], tdelta(data[2])) > elif data[1] == "leave": > return Html("Last seen%s leave%s,%s ago.", name, > data[0], tdelta(data[2])) > elif data[1] == "message": > return Html("Last seen%s message in%s,%s ago: > \"%s\"", name, data[0], tdelta(data[2]), data[3]) > return Html("I have no records about this user.") > > as you can see i only use some of the command. it doesnt produce an error > message tho.. just repeats "return Error("%s I couldn't find %s > anywhere", user.name.title(), name.title())" > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Sorry but it's unreadable to me. Have you sent this in HTML when you should have sent in plain text? -- Cheers. Mark Lawrence. From tokyo.rook at gmail.com Mon May 14 01:22:04 2012 From: tokyo.rook at gmail.com (Keitaro Kaoru) Date: Sun, 13 May 2012 19:22:04 -0400 Subject: [Tutor] sorry seems like it was sent in html Message-ID: is that better? not html... ? hey. Austin here for some reason this command. all it does it produces the error message at the bottom.. itll say my name and the persons name im trying to send the message to but thats it. heres the command. mgr.addCommand("tell", 1, "send a person a message to the rooms he is in", tell, unlisted = True) def tell(mgr, croom, user, msg, args): name = args.lower().split(" ")[0] if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") data = shared_db.get("seen:" + name) if data == None: return Html("I have no records about this user.") data = json.loads(data) for room in mgr.rooms: if data[1] == "join": mgr.sendObject(target, Html("%s,%s wants to tell you%s", name.title, user.name.title$ else: return Error("%s I couldn't find %s anywhere", user.name.title(), name.title()) i built it off these 2 commands def broadcast(mgr, croom, user, msg, args): for room in mgr.rooms: mgr.sendObject(room, Html("Broadcast by%s:%s", user.name, args)) def seen(mgr, room, user, msg, args): name = args.lower().split(" ")[0] if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") data = shared_db.get("seen:" + name) if data == None: return Html("I have no records about this user.") data = json.loads(data) ifdata[1] == "join": return Html("Last seen%s join%s,%s ago.", name, data[0], tdelta(data[2])) elif data[1] == "leave": return Html("Last seen%s leave%s,%s ago.", name, data[0], tdelta(data[2])) elif data[1] == "message": return Html("Last seen%s message in%s,%s ago: \"%s\"", name, data[0], tdelta(data[2]), data[3]) return Html("I have no records about this user.") as you can see i only use some of the command. it doesnt produce an error message tho.. just repeats "return Error("%s I couldn't find %s anywhere", user.name.title(), name.title())" -- ~Keitaro Kaoru-Sama~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon May 14 01:37:44 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 14 May 2012 00:37:44 +0100 Subject: [Tutor] sorry seems like it was sent in html In-Reply-To: References: Message-ID: On 14/05/2012 00:22, Keitaro Kaoru wrote: > is that better? not html... ? hey. Austin here for some reason this > command. all it does it produces the > error message at the bottom.. itll say my name and the persons name im > trying to send the message to but thats it. heres the command. > > mgr.addCommand("tell", 1, "send a person a message to the rooms he is in", > tell, unlisted = True) > mgr is wahh ? > def tell(mgr, croom, user, msg, args): > name = args.lower().split(" ")[0] > if not name.isalnum(): return Html("Non-alphanumeric name, > seriously?") > data = shared_db.get("seen:" + name) > if data == None: > return Html("I have no records about this user.") > data = json.loads(data) > for room in mgr.rooms: > if data[1] == "join": > mgr.sendObject(target, Html("%s, color='#3399CC'>%s wants to tell you%s", > name.title, user.name.title$ > else: > return Error("%s I couldn't find %s > anywhere", user.name.title(), name.title()) > > i built it off these 2 commands > > def broadcast(mgr, croom, user, msg, args): > for room in mgr.rooms: > mgr.sendObject(room, Html("Broadcast by%s:%s", > user.name, args)) > > def seen(mgr, room, user, msg, args): > name = args.lower().split(" ")[0] > if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") > data = shared_db.get("seen:" + name) > if data == None: > return Html("I have no records about this user.") > data = json.loads(data) > ifdata[1] == "join": > return Html("Last seen%s join%s,%s ago.", name, > data[0], tdelta(data[2])) > elif data[1] == "leave": > return Html("Last seen%s leave%s,%s ago.", name, > data[0], tdelta(data[2])) > elif data[1] == "message": > return Html("Last seen%s message in%s,%s ago: > \"%s\"", name, data[0], tdelta(data[2]), data[3]) > return Html("I have no records about this user.") > > as you can see i only use some of the command. it doesnt produce an error > message tho.. just repeats "return Error("%s I couldn't find %s > anywhere", user.name.title(), name.title())" > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor No :( Please cut and past the exact code that you're using and the exception that you're getting, without that that it's impossible for us to help you. -- Cheers. Mark Lawrence. From steve at pearwood.info Mon May 14 02:31:36 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 14 May 2012 10:31:36 +1000 Subject: [Tutor] threading mind set In-Reply-To: <1336909406.19220.290.camel@launcelot.winder.org.uk> References: <4FAEFEAC.8000403@pearwood.info> <1336909406.19220.290.camel@launcelot.winder.org.uk> Message-ID: <4FB05268.7070003@pearwood.info> Russel Winder wrote: > Steven, > > On Sun, 2012-05-13 at 10:22 +1000, Steven D'Aprano wrote: >> carlo locci wrote: >>> Hello All, >>> I've started to study python a couple of month ago(and I truly love it :)), >>> however I'm having some problems understanding how to modify a sequential >>> script and make it multithreaded (I think it's because I'm not used to >>> think in that way), >> No, that's because multithreading and parallel processing is hard. > > Shared memory multithreading may be hard due to locks, semaphores, > monitors, etc., but concurrency and parallelism need not be hard. No hard compared to what? > Using processes and message passing, using dataflow, actors or CSP, > parallelism and concurrency is far more straightforward. Not easy, > agreed, but then programming isn't easy. My argument is that once you move beyond the one-operation-after-another programming model, almost any parallel processing problem is harder than the equivalent sequential version, inherently due to the parallelism. Except perhaps for "embarrassingly parallel" problems, parallelism adds complexity even if your framework abstracts away most of the tedious detail like semaphores. http://en.wikipedia.org/wiki/Embarrassingly_parallel Once you move beyond sequential execution, you have to think about issues that don't apply to sequential programs: how to divide the task up between processes/threads/actors/whatever, how to manage their synchronization, resource starvation (e.g. deadlocks, livelocks), etc. We have linear minds and it doesn't take that many real-time parallel tasks to overwhelm the human brain. I'm not saying that people can't reason in parallel, because we clearly can and do, but it's inherently harder than sequential reasoning. > The GIL in Python is a bad thing for parallelism. Using the > multiprocessing package or concurrent.futures gets over the problem. > Well sort of, these processes are a bit heavyweight compared to what can > be achieved on the JVM or with Erlang. Python doesn't have a GIL. Some Python implementations do, most obviously CPython, the reference implementation. But Jython and IronPython don't. If the GIL is a problem for your program, consider running it on Jython or IronPython. -- Steven From jeanpierreda at gmail.com Mon May 14 03:35:05 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 13 May 2012 21:35:05 -0400 Subject: [Tutor] threading mind set In-Reply-To: <4FB05268.7070003@pearwood.info> References: <4FAEFEAC.8000403@pearwood.info> <1336909406.19220.290.camel@launcelot.winder.org.uk> <4FB05268.7070003@pearwood.info> Message-ID: On Sun, May 13, 2012 at 8:31 PM, Steven D'Aprano wrote: >> Using processes and message passing, using dataflow, actors or CSP, >> parallelism and concurrency is far more straightforward. Not easy, >> agreed, but then programming isn't easy. > > My argument is that once you move beyond the one-operation-after-another > programming model, almost any parallel processing problem is harder than the > equivalent sequential version, inherently due to the parallelism. Except > perhaps for "embarrassingly parallel" problems, parallelism adds complexity > even if your framework abstracts away most of the tedious detail like > semaphores. If you agree that embarrassingly parallel multithreaded frameworks are easy, what do you think of dataflow programming? It is exactly the same, except that you can have multiple tasks, where one task depends on the output of a previous task. It shares the property that it makes no difference in what order things are executed (or sequential vs parallel), so long as the data dependencies are respected -- so it's another case where you don't actually have to think in a non-sequential manner. (Rather, think in a "vectorized" per-work-item manner.) http://en.wikipedia.org/wiki/Dataflow_programming It should be clear that not all ways of programming multithreaded code are equal, and some are easier than others. In particular, having mutable state shared between two concurrently-executing procedures is phenomenally hard, and when it's avoided things become simpler. -- Devin From d at davea.name Mon May 14 04:44:11 2012 From: d at davea.name (Dave Angel) Date: Sun, 13 May 2012 22:44:11 -0400 Subject: [Tutor] sorry seems like it was sent in html In-Reply-To: References: Message-ID: <4FB0717B.50003@davea.name> On 05/13/2012 07:22 PM, Keitaro Kaoru wrote: > is that better? not html... ? Your message is still html. The following section of code shows no indentation, so is very hard to interpret. > > def seen(mgr, room, user, msg, args): > name = args.lower().split(" ")[0] > if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") > data = shared_db.get("seen:" + name) > if data == None: > return Html("I have no records about this user.") > data = json.loads(data) > ifdata[1] == "join": > return Html("Last seen%s join%s,%s ago.", name, > data[0], tdelta(data[2])) > elif data[1] == "leave": > return Html("Last seen%s leave%s,%s ago.", name, > data[0], tdelta(data[2])) > elif data[1] == "message": > return Html("Last seen%s message in%s,%s ago: > \"%s\"", name, data[0], tdelta(data[2]), data[3]) > return Html("I have no records about this user.") > > as you can see i only use some of the command. it doesnt produce an error > message tho.. just repeats "return Error("%s I couldn't find %s > anywhere", user.name.title(), name.title())" > > The following excerpt will show some of the html you sent: Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
is that better? not html... ? hey. Austin here for some reason this co= mmand. all it does it produces the
error message at the bottom.. = itll say my name and the persons name im
trying to send the messa= ge to but thats it. heres the command.=A0

mgr.addCommand("tell", 1, "send a person= a message to the rooms he is in",
tell, unlisted =3D True)<= In addition you keep starting new threads. Use Reply-all to keep related messages together, and don't change the subject line if it's supposed to be part of the same thread. I can't tell what this message's context is. You start it with "hey Austin" but I don't see any other messages from an Austin, except about a year ago from an Austin Rodgers. I guess I need to back off. You don't list your imports, so people can only guess. But clearly you're using some libraries I'm not familiar with. Ask a clearer question, and somebody can probably help. -- DaveA From russel at winder.org.uk Mon May 14 07:43:28 2012 From: russel at winder.org.uk (Russel Winder) Date: Mon, 14 May 2012 06:43:28 +0100 Subject: [Tutor] hello~ In-Reply-To: References: Message-ID: <1336974208.18804.12.camel@launcelot.winder.org.uk> On Mon, 2012-05-14 at 00:19 +0100, Mark Lawrence wrote: [...] > Sorry but it's unreadable to me. Have you sent this in HTML when you > should have sent in plain text? I think it is just line wrapping, email still is supposed to have no lines greater that 78 characters (RFC 2822) and some email clients enforce this on sending by amending what the author thought they sent. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From russel at winder.org.uk Mon May 14 08:12:02 2012 From: russel at winder.org.uk (Russel Winder) Date: Mon, 14 May 2012 07:12:02 +0100 Subject: [Tutor] threading mind set In-Reply-To: <4FB05268.7070003@pearwood.info> References: <4FAEFEAC.8000403@pearwood.info> <1336909406.19220.290.camel@launcelot.winder.org.uk> <4FB05268.7070003@pearwood.info> Message-ID: <1336975922.18804.38.camel@launcelot.winder.org.uk> On Mon, 2012-05-14 at 10:31 +1000, Steven D'Aprano wrote: [...] > No hard compared to what? Compared to sequential programming. [...] > My argument is that once you move beyond the one-operation-after-another > programming model, almost any parallel processing problem is harder than the > equivalent sequential version, inherently due to the parallelism. Except > perhaps for "embarrassingly parallel" problems, parallelism adds complexity > even if your framework abstracts away most of the tedious detail like semaphores. > > http://en.wikipedia.org/wiki/Embarrassingly_parallel > > Once you move beyond sequential execution, you have to think about issues that > don't apply to sequential programs: how to divide the task up between > processes/threads/actors/whatever, how to manage their synchronization, > resource starvation (e.g. deadlocks, livelocks), etc. Actor systems, dataflow systems and CSP (Communicating Sequential Processes), do not guarantee lack of deadlock or livelock, but the whole "processes communicating by passing messages not by sharing data" make it hugely easier to reason about what is happening. Moreover if like with CSP, your actors or dataflow systems enforce sequential actors/operators then it gets even better. The secret to parallel processing (in general, there are always exception/corner cases) is to write sequential bits that then communicate using queues or channels. No semaphores. No locks. No monitors. These are tools for operating systems folk and for folk creating actor, dataflow and CSP queues and channels. > We have linear minds and it doesn't take that many real-time parallel tasks to > overwhelm the human brain. I'm not saying that people can't reason in > parallel, because we clearly can and do, but it's inherently harder than > sequential reasoning. I think if you delve into the psychology of it, our minds are far from linear. Certainly at the electro-chemical level the brain is a massively parallel machine. Over the last 50 years, we have enshrined single processor, single memory into our entire thinking about computing and programming. Our education systems enforce sequential programming for all but the final parallel programming option. The main reason for parallel programming being labelled hard is that we have the wrong tools for reasoning about it. This is the beauty of the 1960s/1970s models of actors, dataflow and CSP, you deconstruct the problem into small bits each of which are sequential and comprehensible, then the overall behaviour of the system is an emergent property of the interaction between these small subsystems. Instead of trying to reason about all the communications systems wide, we just worry about what happens with a small subsystem. The hard part is the decomposition. But then the hard part of software has always been the algorithm. You highlight "embarrassingly parallel" which is the simplest decomposition possible, straight scatter/gather, aka map/reduce. More often that not this is handled by a fa?ade such as "parallel reduce". It is perhaps worth noting that "Big Data" is moving to dataflow processing in a "Big Way" :-) Data mining and the like has been revolutionized by changing it's perception of algorithm and how to decompose problems. [...] > Python doesn't have a GIL. Some Python implementations do, most obviously > CPython, the reference implementation. But Jython and IronPython don't. If the > GIL is a problem for your program, consider running it on Jython or IronPython. It is true that Python doesn't have a GIL, thanks for the correction. CPython and (until recently) PyPy have a GIL. The PyPy folk are experimenting with software transactional memory (STM) in the interpreter to be able to remove the GIL. To date things are looking very positive. PyPy will rock :-) Although Guido had said (EuroPython 2010) he is happy to continue with the GIL in CPython, there are subversive elements (notable the PyPy folk) who are trying to show that STM will work with CPython as well. Jython is sadly lagging behind in terms of versions of Python supported and is increasingly becoming irrelevant -- unless someone does something soon. Groovy, JRuby and Clojure are the dynamic languages of choice on the JVM. IronPython is an interesting option except that there is all the FUD about use of the CLR and having to buy extortion^H^H^H^H^H^H^H^H^H licencing money to Microsoft. Also Microsoft ceasing to fund IronPython (and IronRuby) is a clear indicator that Microsoft have no intention of supporting use of Python on CLR. Thus it could end up in the same state as Jython. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From bala.biophysics at gmail.com Mon May 14 09:31:41 2012 From: bala.biophysics at gmail.com (Bala subramanian) Date: Mon, 14 May 2012 09:31:41 +0200 Subject: [Tutor] extracting lines between patterns. Message-ID: Friends, Could someone please give some hint on how to extract lines between two patterns in a file. I use the re module to compile my patterns but not able to figure out how i can use these patterns to extract the lines lying in between. Thanks, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From russel at winder.org.uk Mon May 14 09:53:20 2012 From: russel at winder.org.uk (Russel Winder) Date: Mon, 14 May 2012 08:53:20 +0100 Subject: [Tutor] extracting lines between patterns. In-Reply-To: References: Message-ID: <1336982000.18804.39.camel@launcelot.winder.org.uk> On Mon, 2012-05-14 at 09:31 +0200, Bala subramanian wrote: > Friends, > Could someone please give some hint on how to extract lines between two > patterns in a file. I use the re module to compile my patterns but not able > to figure out how i can use these patterns to extract the lines lying in > between. Without the source code you already have, it is difficult to provide any constructive suggestions. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From delegbede at dudupay.com Mon May 14 09:43:11 2012 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Mon, 14 May 2012 07:43:11 +0000 Subject: [Tutor] extracting lines between patterns. In-Reply-To: References: Message-ID: <621854468-1336982113-cardhu_decombobulator_blackberry.rim.net-1158357621-@b26.c12.bise7.blackberry> Give an example. Let's see what you've tried and then it becomes clear what help is needed. Regards. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Bala subramanian Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Mon, 14 May 2012 09:31:41 To: Subject: [Tutor] extracting lines between patterns. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From tokyo.rook at gmail.com Mon May 14 11:58:17 2012 From: tokyo.rook at gmail.com (Keitaro Kaoru) Date: Mon, 14 May 2012 05:58:17 -0400 Subject: [Tutor] (no subject) In-Reply-To: <4FAF1C3C.2060307@gmail.com> References: <4FAF1C3C.2060307@gmail.com> Message-ID: sorry if i keep missing this up. hey. Austin here for some reason this command. all it does it produces the error message at the bottom.. itll say my name and the persons name im trying to send the message to but thats it. heres the command. ################################################################ # Imports ################################################################ from tools import Html, Error, Text, shared_db, log import urllib.request as urlreq import urllib.parse as urlpar import xml.dom.minidom as xdm import random import time import json import re import ch mgr.addCommand("tell", 1, "send a person a message to the rooms he is in", tell, unlisted = True) def tell(mgr, croom, user, msg, args): ? ? ? ? name = args.lower().split(" ")[0] ? ? ? ? if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") ? ? ? ? data = shared_db.get("seen:" + name) ? ? ? ? if data == None: ? ? ? ? ? ? ? ? return Html("I have no records about this user.") ? ? ? ? data = json.loads(data) ? ? ? ? for room in mgr.rooms: ? ? ? ? ? ? ? ? if data[1] == "join": ? ? ? ? ? ? ? ? ? ? ? ? mgr.sendObject(target, Html("%s,%s ?wants to tell you%s ", name.title, user.name.title$ ? ? ? ? else: ? ? ? ? ? ? ? ? ? ? ? ? return Error("%s ?I couldn't find %s anywhere", user.name.title(), name.title()) i built it off these 2 commands def broadcast(mgr, croom, user, msg, args): ? ? ? ? for room in mgr.rooms: ? ? ? ? ? ? ? ? mgr.sendObject(room, Html("Broadcast by%s:%s", user.name, args)) def seen(mgr, room, user, msg, args): name = args.lower().split(" ")[0] if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") data = shared_db.get("seen:" + name) if data == None: ? ? ? ? return Html("I have no records about this user.") data = json.loads(data) ifdata[1] == "join": ? ? ? ? return Html("Last seen%s ?join%s,%s ago.", name, data[0], tdelta(data[2])) elif data[1] == "leave": ? ? ? ? return Html("Last seen%s ?leave%s,%s ago.", name, data[0], tdelta(data[2])) elif data[1] == "message": ? ? ? ? return Html("Last seen%s ?message in%s,%s ?ago: \"%s\"", name, data[0], tdelta(data[2]), data[3]) ? ? ? ? return Html("I have no records about this user.") as you can see i only use some of the command. it doesnt produce an error message tho.. just repeats "return Error("%s ?I couldn't find %s anywhere", user.name.title(), name.title())" On Sat, May 12, 2012 at 10:28 PM, bob gailer wrote: > > On 5/12/2012 6:34 PM, Keitaro Kaoru wrote: > > hey i keep having a problem with adding commands.. i get this error message > > Traceback (most recent call last): > ? File "bot.py", line 23, in > ? ? import modules.core, modules.ai, modules.dict, modules.fun, modules.kc, modules.games, modules.lulz2, modules.modding, modules.meta, modules.mpd, modules.post, modules.poll, modules.util, modules.yt > ? File "/home/digest/digest/modules/core.py", line 170 > ? ? def pm(mgr, room, user, msg, args): > ? ? ? ^ > SyntaxError: invalid syntax > > Thanks for posting the traceback. All we need is to see more of the program (especially the lines before the one you posted. It is always a good idea to post more of the code regardless of the problem. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC -- ~Keitaro Kaoru-Sama~ From tokyo.rook at gmail.com Mon May 14 12:11:23 2012 From: tokyo.rook at gmail.com (Keitaro Kaoru) Date: Mon, 14 May 2012 06:11:23 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: <4FAF1C3C.2060307@gmail.com> Message-ID: and i also realized my real name isnt on google i am austin but im guessing u see keitaro kaoru or whatever yeha this is a very old email account and i cant change the name i use.. lol i made my signature austin tho maybe thatll help On Mon, May 14, 2012 at 5:58 AM, Keitaro Kaoru wrote: > sorry if i keep missing this up. > > hey. Austin here for some reason this command. all it does it produces the > error message at the bottom.. itll say my name and the persons name im > trying to send the message to but thats it. heres the command. > > ################################################################ > # Imports > ################################################################ > from tools import Html, Error, Text, shared_db, log > import urllib.request as urlreq > import urllib.parse as urlpar > import xml.dom.minidom as xdm > import random > import time > import json > import re > import ch > > mgr.addCommand("tell", 1, "send a person a message to the rooms he is in", > tell, unlisted = True) > > def tell(mgr, croom, user, msg, args): > ? ? ? ? name = args.lower().split(" ")[0] > ? ? ? ? if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") > ? ? ? ? data = shared_db.get("seen:" + name) > ? ? ? ? if data == None: > ? ? ? ? ? ? ? ? return Html("I have no records about this user.") > ? ? ? ? data = json.loads(data) > ? ? ? ? for room in mgr.rooms: > ? ? ? ? ? ? ? ? if data[1] == "join": > ? ? ? ? ? ? ? ? ? ? ? ? mgr.sendObject(target, > Html("%s,%s ?wants to tell > you%s ", name.title, user.name.title$ > ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? return Error("%s ?I couldn't find %s > anywhere", user.name.title(), name.title()) > > i built it off these 2 commands > > def broadcast(mgr, croom, user, msg, args): > ? ? ? ? for room in mgr.rooms: > ? ? ? ? ? ? ? ? mgr.sendObject(room, Html("Broadcast by%s:%s", > user.name, args)) > > def seen(mgr, room, user, msg, args): > name = args.lower().split(" ")[0] > if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") > data = shared_db.get("seen:" + name) > if data == None: > ? ? ? ? return Html("I have no records about this user.") > data = json.loads(data) > ifdata[1] == "join": > ? ? ? ? return Html("Last seen%s ?join%s,%s > ago.", name, data[0], tdelta(data[2])) > elif data[1] == "leave": > ? ? ? ? return Html("Last seen%s ?leave%s,%s > ago.", name, data[0], tdelta(data[2])) > elif data[1] == "message": > ? ? ? ? return Html("Last seen%s ?message in%s,%s > ?ago: \"%s\"", name, data[0], tdelta(data[2]), data[3]) > ? ? ? ? return Html("I have no records about this user.") > > as you can see i only use some of the command. it doesnt produce an error > message tho.. just repeats "return Error("%s ?I couldn't find %s > anywhere", user.name.title(), name.title())" > > > > On Sat, May 12, 2012 at 10:28 PM, bob gailer wrote: >> >> On 5/12/2012 6:34 PM, Keitaro Kaoru wrote: >> >> hey i keep having a problem with adding commands.. i get this error message >> >> Traceback (most recent call last): >> ? File "bot.py", line 23, in >> ? ? import modules.core, modules.ai, modules.dict, modules.fun, modules.kc, modules.games, modules.lulz2, modules.modding, modules.meta, modules.mpd, modules.post, modules.poll, modules.util, modules.yt >> ? File "/home/digest/digest/modules/core.py", line 170 >> ? ? def pm(mgr, room, user, msg, args): >> ? ? ? ^ >> SyntaxError: invalid syntax >> >> Thanks for posting the traceback. All we need is to see more of the program (especially the lines before the one you posted. It is always a good idea to post more of the code regardless of the problem. >> >> -- >> Bob Gailer >> 919-636-4239 >> Chapel Hill NC > > > > > -- > ~Keitaro Kaoru-Sama~ -- ~Keitaro Kaoru-Sama~ From tokyo.rook at gmail.com Mon May 14 12:14:52 2012 From: tokyo.rook at gmail.com (Keitaro Kaoru) Date: Mon, 14 May 2012 06:14:52 -0400 Subject: [Tutor] hello~ In-Reply-To: <1336974208.18804.12.camel@launcelot.winder.org.uk> References: <1336974208.18804.12.camel@launcelot.winder.org.uk> Message-ID: i resent it but if that doesnt work. cause i sent it to myself also looks fine on my gmail.. but heres a link to pastebin http://pastebin.com/Jp7VJKGB maybe thatll help? On Mon, May 14, 2012 at 1:43 AM, Russel Winder wrote: > On Mon, 2012-05-14 at 00:19 +0100, Mark Lawrence wrote: > [...] >> Sorry but it's unreadable to me. ?Have you sent this in HTML when you >> should have sent in plain text? > > I think it is just line wrapping, email still is supposed to have no > lines greater that 78 characters (RFC 2822) and some email clients > enforce this on sending by amending what the author thought they sent. > > -- > Russel. > ============================================================================= > Dr Russel Winder ? ? ?t: +44 20 7585 2200 ? voip: sip:russel.winder at ekiga.net > 41 Buckmaster Road ? ?m: +44 7770 465 077 ? xmpp: russel at winder.org.uk > London SW11 1EN, UK ? w: www.russel.org.uk ?skype: russel_winder > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- ~~Austin From bala.biophysics at gmail.com Mon May 14 12:23:48 2012 From: bala.biophysics at gmail.com (Bala subramanian) Date: Mon, 14 May 2012 12:23:48 +0200 Subject: [Tutor] extracting lines between patterns. In-Reply-To: <1336982000.18804.39.camel@launcelot.winder.org.uk> References: <1336982000.18804.39.camel@launcelot.winder.org.uk> Message-ID: The code is given below. Here i try to extract lines that are between the two patterns atomtype and mol.type #!/usr/bin/env python import re mypat=re.compile(r'^[ atomtypes ]$[ moleculetype ]',re.MULTILINE) data=open('test.dat').read() extr=re.findall(mypat,data) print extr The data file is something like the following, [ defaults ] ; nbfunc comb-rule gen-pairs fudgeLJ fudgeQQ 1 2 no 0.5 0.8333 [ atomtypes ] ;name bond_type mass charge ptype N3 N3 0.00000 0.00000 A H H 0.00000 0.00000 A CT CT 0.00000 0.00000 A HP HP 0.00000 0.00000 A O2 O2 0.00000 0.00000 A [ moleculetype ] ;name nrexcl tripe 3 On Mon, May 14, 2012 at 9:53 AM, Russel Winder wrote: > On Mon, 2012-05-14 at 09:31 +0200, Bala subramanian wrote: > > Friends, > > Could someone please give some hint on how to extract lines between two > > patterns in a file. I use the re module to compile my patterns but not > able > > to figure out how i can use these patterns to extract the lines lying in > > between. > > Without the source code you already have, it is difficult to provide any > constructive suggestions. > > -- > Russel. > > ============================================================================= > Dr Russel Winder t: +44 20 7585 2200 voip: > sip:russel.winder at ekiga.net > 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk > London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder > -- C. Balasubramanian -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon May 14 12:44:44 2012 From: d at davea.name (Dave Angel) Date: Mon, 14 May 2012 06:44:44 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: <4FAF1C3C.2060307@gmail.com> Message-ID: <4FB0E21C.5030700@davea.name> On 05/14/2012 05:58 AM, Keitaro Kaoru wrote: > sorry if i keep missing this up. > > hey. Austin here for some reason this command. all it does it produces the > error message at the bottom.. itll say my name and the persons name im > trying to send the message to but thats it. heres the command. I spent some time trying to re-indent this code, and eventually got it to make sense. However then I got at least two syntax errors, noted inline. > ################################################################ > # Imports > ################################################################ > from tools import Html, Error, Text, shared_db, log > import urllib.request as urlreq > import urllib.parse as urlpar > import xml.dom.minidom as xdm > import random > import time > import json > import re > import ch > > mgr.addCommand("tell", 1, "send a person a message to the rooms he is in", > tell, unlisted = True) > > def tell(mgr, croom, user, msg, args): > name = args.lower().split(" ")[0] > if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") > data = shared_db.get("seen:" + name) > if data == None: > return Html("I have no records about this user.") > data = json.loads(data) > for room in mgr.rooms: > if data[1] == "join": > mgr.sendObject(target, > Html("%s,%s wants to tell > you%s ", name.title, user.name.title$ That $ at the end is a syntax error. At a minimum there should be two right parentheses there, but i can't tell if other stuff got lost there. > else: > return Error("%s I couldn't find %s > anywhere", user.name.title(), name.title()) > > i built it off these 2 commands > > def broadcast(mgr, croom, user, msg, args): > for room in mgr.rooms: > mgr.sendObject(room, Html("Broadcast by%s:%s", > user.name, args)) > > def seen(mgr, room, user, msg, args): > name = args.lower().split(" ")[0] > if not name.isalnum(): return Html("Non-alphanumeric name, seriously?") > data = shared_db.get("seen:" + name) > if data == None: > return Html("I have no records about this user.") > data = json.loads(data) > ifdata[1] == "join": Need a space after the 'if' > return Html("Last seen%s join%s,%s > ago.", name, data[0], tdelta(data[2])) > elif data[1] == "leave": > return Html("Last seen%s leave%s,%s > ago.", name, data[0], tdelta(data[2])) > elif data[1] == "message": > return Html("Last seen%s message in%s,%s > ago: \"%s\"", name, data[0], tdelta(data[2]), data[3]) > return Html("I have no records about this user.") > > as you can see i only use some of the command. it doesnt produce an error > message tho.. just repeats "return Error("%s I couldn't find %s > anywhere", user.name.title(), name.title())" > > At this point, I got import errors on four of the nine import statements. And then the following: Traceback (most recent call last): File "keitaro.py", line 15, in mgr.addCommand("tell", 1, "send a person a message to the rooms he is in", NameError: name 'mgr' is not defined This is with python 2.7 on Linux -- DaveA From bala.biophysics at gmail.com Mon May 14 13:00:08 2012 From: bala.biophysics at gmail.com (Bala subramanian) Date: Mon, 14 May 2012 13:00:08 +0200 Subject: [Tutor] List Indexing Issue In-Reply-To: References: Message-ID: Hi, I would suggest you to use the biopython package. It has a PDB parser with which you can extract any specific information like atom name, residue, chain etc as you wish. Bala On Wed, May 9, 2012 at 3:19 AM, Jerry Hill wrote: > On Tue, May 8, 2012 at 4:00 PM, Spyros Charonis > wrote: > > Hello python community, > > > > I'm having a small issue with list indexing. I am extracting certain > > information from a PDB (protein information) file and need certain > fields of > > the file to be copied into a list. The entries look like this: > > > > ATOM 1512 N VAL A 222 8.544 -7.133 25.697 1.00 48.89 > > N > > ATOM 1513 CA VAL A 222 8.251 -6.190 24.619 1.00 48.64 > > C > > ATOM 1514 C VAL A 222 9.528 -5.762 23.898 1.00 48.32 > > C > > > > I am using the following syntax to parse these lines into a list: > ... > > charged_res_coord.append(atom_coord[i].split()[1:9]) > > You're using split, assuming that there will be blank spaces between > your fields. That's not true, though. PDB is a fixed length record > format, according to the documentation I found here: > http://www.wwpdb.org/docs.html > > If you just have a couple of items to pull out, you can just slice the > string at the appropriate places. Based on those docs, you could pull > the x, y, and z coordinates out like this: > > > x_coord = atom_line[30:38] > y_coord = atom_line[38:46] > z_coord = atom_line[46:54] > > If you need to pull more of the data out, or you may want to reuse > this code in the future, it might be worth actually parsing the record > into all its parts. For a fixed length record, I usually do something > like this: > > pdbdata = """ > ATOM 1512 N VAL A 222 8.544 -7.133 25.697 1.00 48.89 > N > ATOM 1513 CA VAL A 222 8.251 -6.190 24.619 1.00 48.64 > C > ATOM 1514 C VAL A 222 9.528 -5.762 23.898 1.00 48.32 > C > ATOM 1617 N GLU A1005 11.906 -2.722 7.994 1.00 44.02 > N > """.splitlines() > > atom_field_spec = [ > slice(0,6), > slice(6,11), > slice(12,16), > slice(16,18), > slice(17,20), > slice(21,22), > slice(22,26), > slice(26,27), > slice(30,38), > slice(38,46), > slice(46,54), > slice(54,60), > slice(60,66), > slice(76,78), > slice(78,80), > ] > > for line in pdbdata: > if line.startswith('ATOM'): > data = [line[field_spec] for field_spec in atom_field_spec] > print(data) > > > You can build all kind of fancy data structures on top of that if you > want to. You could use that extracted data to build a namedtuple for > convenient access to the data by names instead of indexes into a list, > or to create instances of a custom class with whatever functionality > you need. > > -- > Jerry > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- C. Balasubramanian -------------- next part -------------- An HTML attachment was scrubbed... URL: From russel at winder.org.uk Mon May 14 14:07:01 2012 From: russel at winder.org.uk (Russel Winder) Date: Mon, 14 May 2012 13:07:01 +0100 Subject: [Tutor] extracting lines between patterns. In-Reply-To: References: <1336982000.18804.39.camel@launcelot.winder.org.uk> Message-ID: <1336997221.18804.79.camel@launcelot.winder.org.uk> On Mon, 2012-05-14 at 12:23 +0200, Bala subramanian wrote: [...] > mypat=re.compile(r'^[ atomtypes ]$[ moleculetype ]',re.MULTILINE) [...] mypat=re.compile(r'^\[ atomtypes \]$(.*)^\[ moleculetype \]$',re.MULTILINE | re.DOTALL) -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From bgailer at gmail.com Mon May 14 17:57:25 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 14 May 2012 11:57:25 -0400 Subject: [Tutor] syntax error In-Reply-To: References: <4FAF1C3C.2060307@gmail.com> Message-ID: <4FB12B65.4000206@gmail.com> I have changed the subject to "syntax error". Please always post a meaningful subject. On 5/14/2012 5:58 AM, Keitaro Kaoru wrote: > sorry if i keep missing this up. > > hey. Austin here for some reason this command. all it does it produces the > error message at the bottom.. The code you sent has numerous errors. How did you miss all the other errors? Are you using an IDE to edit the code? An IDE will help you locate the errors. I corrected the errors (so the program compiles) and put a copy in http://pastebin.com/zWcD7gnT. I have no idea if all the indentation is correct, as I can only guess, and don't want to spend time doing better guessing. Please sign up with pastebin and post your code there. That will guarantee we can copy it as you wrote it. Also please refer to your program as a program or script. It is not a command. -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Mon May 14 18:13:37 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 14 May 2012 12:13:37 -0400 Subject: [Tutor] syntax error In-Reply-To: References: <1336974208.18804.12.camel@launcelot.winder.org.uk> Message-ID: <4FB12F31.3070907@gmail.com> On 5/14/2012 6:14 AM, Keitaro Kaoru wrote: hello~ is NOT a good subject > i resent it but if that doesnt work. cause i sent it to myself also > looks fine on my gmail.. but heres a link to pastebin > > http://pastebin.com/Jp7VJKGB There are still numerous errors that prevent the program from compiling. PLEASE ONLY PASTEBIN code that we can run! Line 26 ends with ; should be )) Line 28 is split Line 31 - is that a comment if so put # in front of it. Line 38-51 must be indented Line 44 ifdata[1] == "join": Line 51 will never be executed. -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Mon May 14 21:01:32 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 May 2012 20:01:32 +0100 Subject: [Tutor] extracting lines between patterns. In-Reply-To: References: Message-ID: On 14/05/12 08:31, Bala subramanian wrote: > Friends, > Could someone please give some hint on how to extract lines between two > patterns in a file. I use the re module to compile my patterns but not > able to figure out how i can use these patterns to extract the lines > lying in between. Without much detail here goes the generic pattern in pseudo code: active_flag = False for line in file: if not active_flag: if start_pattern in line: active_flag = True else: if end_pattern in line: active_flag = False # or break if only one group possible else: #process line You can tweak the logic to make it more efficient but at the cost of readability. Hopefully that gives you a starting point. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From leamhall at gmail.com Mon May 14 21:33:46 2012 From: leamhall at gmail.com (leam hall) Date: Mon, 14 May 2012 15:33:46 -0400 Subject: [Tutor] Multiple DBs per application? Message-ID: All, Just a general question. If you have an application with different data types where it might be better to use one database over another, are there issues with having multiple databases used by the application? Thanks! Leam -- Mind on a Mission From bjorn.h.madsen at googlemail.com Mon May 14 22:07:26 2012 From: bjorn.h.madsen at googlemail.com (Bjorn Madsen) Date: Mon, 14 May 2012 21:07:26 +0100 Subject: [Tutor] pip errors for numpy, scipy matplotlib In-Reply-To: References: Message-ID: Hi Jerry, Sorry the missing details - but well spotted: I do use ubuntu and it was with the 12.04 upgrade that I experienced the issue. Your advice was spot on - sudo apt-get install python-numpy solved the job, and when I ran pip afterwards I received the message that "requirements are already satisfied". Thank you again - I will keep it in mind that "apt-get install python-some_packages" may be the right way about it on ubuntu. Bjorn On 11 May 2012 19:52, Jerry Hill wrote: > On Fri, May 11, 2012 at 2:42 PM, Bjorn Madsen > wrote: > > Hi, > > when attempting to use pip to install numpy, scipy matplotlib I get a > mile > > of errors. There is simply too much information printed - so it must be a > > systematic error (http://paste.ubuntu.com/982180/). What am I > missing/doing > > wrong? > > The error messages sound like you're missing a bunch of the thing > required to build the packages you're trying to compile. It looks > like libraries called Atlas and Blas, plus a fortran compiler, from > the errors you posted. > > Are you using ubuntu? You didn't say, but I see you're using a ubuntu > pastebin. Are you wedded to compiling and installing with pip? It's > a whole lot easier to just use the packaging system included with > ubuntu when you can. In this case you should be able to do `sudo > apt-get install python-numpy` to install numpy. > > If you do want to compile and build via pip, I would start by doing > `sudo apt-get build-dep python-numpy` to get all the required > prerequisites installed, then retry installing via pip. > > -- > Jerry > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Bjorn Madsen * * -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 15 00:44:52 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 May 2012 23:44:52 +0100 Subject: [Tutor] Multiple DBs per application? In-Reply-To: References: Message-ID: On 14/05/12 20:33, leam hall wrote: > Just a general question. If you have an application with different > data types where it might be better to use one database over another, > are there issues with having multiple databases used by the > application? No, you can usuially have multiple databases open at once. You can have multiple instances of the same database or different database types. However the data types are rarely ta reason to use different databases. More typically would be different performance requirements or security issues. For example it's common to hold some data in an LDAP structure for speed of access (at the expense of flexibility) and the rest of the data in an RDBMS such as MySql. But using say MySQL and Oracle together would normally only be done because they were pre-existing datastores from another project. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From leamhall at gmail.com Tue May 15 01:55:52 2012 From: leamhall at gmail.com (Leam Hall) Date: Mon, 14 May 2012 19:55:52 -0400 Subject: [Tutor] Multiple DBs per application? In-Reply-To: References: Message-ID: <4FB19B88.4040403@gmail.com> On 05/14/2012 06:44 PM, Alan Gauld wrote: > On 14/05/12 20:33, leam hall wrote: >> Just a general question. If you have an application with different >> data types where it might be better to use one database over another, >> are there issues with having multiple databases used by the >> application? > > > No, you can usuially have multiple databases open at once. > You can have multiple instances of the same database or > different database types. > > However the data types are rarely ta reason to use different databases. > More typically would be different performance requirements or security > issues. For example it's common to hold some data in an LDAP structure > for speed of access (at the expense of flexibility) and the rest of the > data in an RDBMS such as MySql. But using say MySQL and Oracle together > would normally only be done because they were pre-existing datastores > from another project. Thanks! I was more thinking of something like a CMS where user login information and admin functions might be in a SQLite database and then some larger backend big data stuff in MongoDB or similar. Just wasn't sure if there was a basic flaw to the idea that I wasn't aware of. Leam From bgailer at gmail.com Tue May 15 02:02:13 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 14 May 2012 20:02:13 -0400 Subject: [Tutor] Multiple DBs per application? In-Reply-To: References: Message-ID: <4FB19D05.6070101@gmail.com> On 5/14/2012 3:33 PM, leam hall wrote: > All, > > Just a general question. If you have an application with different > data types where it might be better to use one database over another, > are there issues with having multiple databases used by the > application? BY "database" do you mean a table (as in dBase) a collection of tables (as an Access file) a database management system (MySQL)? -- Bob Gailer 919-636-4239 Chapel Hill NC From questions.anon at gmail.com Tue May 15 04:16:19 2012 From: questions.anon at gmail.com (questions anon) Date: Tue, 15 May 2012 12:16:19 +1000 Subject: [Tutor] table to dictionary and then analysis Message-ID: I am completely new to dictionaries and I am not even sure if this is what I need to use. I have a text file that I would like to run summary stats on particular months, years and climate indices (in this case the climate indices are rainfall and fire area, so not actualy climate indices at all). A text file is attached but a small sample of the file: rainfall firearea 1972 Jan 12.7083199 0 1972 Feb 14.17007142 0 1972 Mar 14.5659302 0 1972 Apr 1.508517302 0 1972 May 2.780009889 0 1972 Jun 1.609619287 0 1972 Jul 0.138150181 28 1972 Aug 0.214346148 32 1972 Sep 1.322102228 34747.8 1972 Oct 0.092663137 3655.9 1972 Nov 1.852276635 85.1 1972 Dec 2.011206002 42959.6 1973 Jan 5.55704346 153.5 1973 Feb 12.60326356 116.2 1973 Mar 11.08849105 223.6 1973 Apr 5.864925449 2.4 ...... I have used an example from a book (a primer on scientific programming with python) and it seems to be working (see below) but I am not sure if I have my keys etc. are set up correctly to then begin anlaysis, and even how to use the dictionaries in my analysis. For example how can I print out the year with calculated the mean 'firearea' of June-July-August for that year along with the maximum 'rainfall' for June-July-august of the same year? Any feedback will be greatly appreaciated! infile=open('d:/yearmonthrainfire.txt','r') lines=infile.readlines() infile.close() data={} #data[index][year]=indexvalue first_line=lines[0] climateindexname=first_line.split() for index in climateindexname: data[index]={} YEAR={} MONTH={} for line in lines[2:]: words=line.split() year=words[0] #years YEAR[year]={} month=words[1] #months MONTH[month]={} values=words[2:] #values of climateindices for index, v in zip(climateindexname, values): if v !=' ': data[index][year]=float(v) print "years=", YEAR print "months=", MONTH print "data=", data -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- meanrain firearea 1972 Jan 12.7083199 0 1972 Feb 14.17007142 0 1972 Mar 14.5659302 0 1972 Apr 1.508517302 0 1972 May 2.780009889 0 1972 Jun 1.609619287 0 1972 Jul 0.138150181 28 1972 Aug 0.214346148 32 1972 Sep 1.322102228 34747.8 1972 Oct 0.092663137 3655.9 1972 Nov 1.852276635 85.1 1972 Dec 2.011206002 42959.6 1973 Jan 5.55704346 153.5 1973 Feb 12.60326356 116.2 1973 Mar 11.08849105 223.6 1973 Apr 5.864925449 2.4 1973 May 2.352622232 0 1973 Jun 1.600553474 0 1973 Jul 0.776217634 0.4 1973 Aug 0.369365192 0 1973 Sep 2.2226749 13523.2 1973 Oct 1.122739926 229.3 1973 Nov 7.904255106 144 1973 Dec 13.31568494 1558.5 1974 Jan 24.85492667 1170.8 1974 Feb 16.21160985 11.1 1974 Mar 15.68630322 64.5 1974 Apr 1.761830238 0 1974 May 3.245113376 0 1974 Jun 0.413113179 0 1974 Jul 0.056925965 0 1974 Aug 1.056679232 0 1974 Sep 0.506806924 0.2 1974 Oct 0.571465459 0 1974 Nov 1.747845479 2939.4 1974 Dec 5.423673558 2212.4 1975 Jan 8.246915224 34838.4 1975 Feb 10.09194262 14467.3 1975 Mar 8.228448671 2673.5 1975 Apr 4.033215013 608.4 1975 May 1.953680674 28.2 1975 Jun 1.343020358 0 1975 Jul 1.038350229 48 1975 Aug 1.217719419 0 1975 Sep 2.873960222 2.4 1975 Oct 3.647092246 2.1 1975 Nov 1.789754789 41135 1975 Dec 12.7257926 1837.2 1976 Jan 8.670511763 12972.1 1976 Feb 12.82303773 556.9 1976 Mar 8.693052739 646.6 1976 Apr 4.824761671 2441.1 1976 May 1.185164667 174.3 1976 Jun 0.807438979 0 1976 Jul 0.772650504 0 1976 Aug 0.339851675 0.8 1976 Sep 0.172502614 18.5 1976 Oct 0.942766622 18 1976 Nov 2.882269122 115558.6 1976 Dec 8.023477936 2566.7 1977 Jan 6.995102092 2771.8 1977 Feb 18.99860777 21637.1 1977 Mar 10.80012409 145.1 1977 Apr 7.522531332 792.3 1977 May 3.779496681 171.6 1977 Jun 0.653845173 0 1977 Jul 0.577692075 0 1977 Aug 0.46951093 903.4 1977 Sep 0.690806944 164 1977 Oct 0.355984233 38512.8 1977 Nov 2.256052975 1946.3 1977 Dec 4.696920357 3620.8 1978 Jan 7.361228919 38343.3 1978 Feb 6.082772277 7332.2 1978 Mar 2.345215476 298.3 1978 Apr 4.67913104 117.7 1978 May 2.831787858 5 1978 Jun 0.371906624 0 1978 Jul 0.815953022 0 1978 Aug 1.214826869 0 1978 Sep 0.822085465 480 1978 Oct 1.949806128 3811.3 1978 Nov 2.26078841 1413 1978 Dec 3.999907139 1160.1 1979 Jan 21.87961335 24431 1979 Feb 14.9501875 3155.7 1979 Mar 9.800489519 1924.9 1979 Apr 3.915820791 109.7 1979 May 1.309700733 5.5 1979 Jun 2.233918323 0 1979 Jul 0.853675529 0 1979 Aug 0.333655061 1 1979 Sep 0.29215987 85.2 1979 Oct 0.682168916 1195 1979 Nov 1.088198531 5734.9 1979 Dec 3.521986644 4679.4 1980 Jan 6.680534017 5282.1 1980 Feb 7.924590667 5664.1 1980 Mar 6.918765319 11465.5 1980 Apr 2.865413043 12712.2 1980 May 2.462878208 12 1980 Jun 1.285836016 0.1 1980 Jul 0.682107184 0.5 1980 Aug 1.571886257 4984 1980 Sep 0.021409787 92974.1 1980 Oct 0.517530831 32094.2 1980 Nov 1.108586343 23453.5 1980 Dec 3.213191566 167788.4 1981 Jan 26.24314963 134907.5 1981 Feb 13.38748218 2131.7 1981 Mar 2.369835156 2521.7 1981 Apr 2.105931953 5912.4 1981 May 4.723263861 1261.9 1981 Jun 0.474331956 0.1 1981 Jul 1.633319526 0 1981 Aug 0.24848172 1 1981 Sep 1.523939382 373 1981 Oct 1.374030119 4116.1 1981 Nov 4.134000547 168.2 1981 Dec 3.274688096 3672.4 1982 Jan 6.02705233 9128.2 1982 Feb 4.567044471 5303 1982 Mar 6.607413666 3317 1982 Apr 7.823935127 1063 1982 May 1.169920518 49 1982 Jun 0.992082419 0 1982 Jul 0.274846028 0.3 1982 Aug 1.906676094 5594 1982 Sep 0.522254326 100.5 1982 Oct 0.079977437 3596.7 1982 Nov 1.307046374 85323 1982 Dec 2.870249219 22181.5 1983 Jan 2.855475445 143760.9 1983 Feb 2.515061768 336861.6 1983 Mar 11.05386469 128333.7 1983 Apr 5.276516046 6550 1983 May 6.079337518 0 1983 Jun 0.946812531 0 1983 Jul 0.532662055 0 1983 Aug 1.006456011 0 1983 Sep 0.977370533 60 1983 Oct 0.539496993 3802 1983 Nov 3.143395435 191.2 1983 Dec 2.737488439 7632.9 1984 Jan 10.11088201 182.7 1984 Feb 15.5033194 180.9 1984 Mar 3.766858012 130.6 1984 Apr 1.633064341 4194.6 1984 May 1.143856983 258 1984 Jun 1.204634779 150 1984 Jul 1.326248452 0.1 1984 Aug 0.156389808 0 1984 Sep 0.184485674 100 1984 Oct 0.810719447 4514.7 1984 Nov 2.106038111 8285.1 1984 Dec 3.777131865 9288.6 1985 Jan 5.011390998 231255.5 1985 Feb 8.60879258 344.5 1985 Mar 9.235176983 70415.7 1985 Apr 3.699116243 5823.4 1985 May 2.373524399 203.7 1985 Jun 1.161396326 0 1985 Jul 0.845702914 3.4 1985 Aug 0.170493565 0 1985 Sep 0.276077967 5.7 1985 Oct 1.921874573 402.2 1985 Nov 4.201466182 166.1 1985 Dec 2.706100856 6628.3 1986 Jan 10.47965071 2115.3 1986 Feb 5.37365136 4778.1 1986 Mar 3.873115362 623.3 1986 Apr 4.584836939 11099.5 1986 May 1.743296951 45.5 1986 Jun 1.86496364 0 1986 Jul 0.556588324 0 1986 Aug 0.842487134 5.1 1986 Sep 0.726846716 170.1 1986 Oct 2.057291002 376.5 1986 Nov 1.035925427 4741.4 1986 Dec 1.708060575 10326.3 1987 Jan 4.457561014 5051.3 1987 Feb 9.897967871 1506.9 1987 Mar 4.311450182 1573.7 1987 Apr 3.975473663 4094.7 1987 May 2.179936139 0.5 1987 Jun 3.046559272 0 1987 Jul 1.396657135 20.5 1987 Aug 0.558126971 200.2 1987 Sep 1.076646124 891.7 1987 Oct 0.39166958 6014.3 1987 Nov 1.866614413 1584.7 1987 Dec 4.655993403 953.1 1988 Jan 2.22449808 14437 1988 Feb 8.847698502 848.5 1988 Mar 4.773818734 5747.1 1988 Apr 3.147990239 1453.5 1988 May 1.461767068 201.7 1988 Jun 1.002995145 0 1988 Jul 1.563390642 0 1988 Aug 1.830531756 18.5 1988 Sep 0.559768549 180.6 1988 Oct 1.029085162 7703.2 1988 Nov 3.493493432 1140.9 1988 Dec 8.879964753 577.1 1989 Jan 4.534711225 376 1989 Feb 6.721512903 20613.1 1989 Mar 10.29195875 122.2 1989 Apr 7.959824457 12.9 1989 May 4.341240432 0 1989 Jun 1.61926397 0 1989 Jul 1.104096165 0 1989 Aug 0.302561542 0.1 1989 Sep 0.14264302 131.5 1989 Oct 0.829273331 305.7 1989 Nov 8.560543606 2181.5 1989 Dec 3.796533528 711.8 1990 Jan 3.049078738 16302.4 1990 Feb 1.869648119 779.9 1990 Mar 10.60081201 2857.2 1990 Apr 7.285089356 458 1990 May 5.108933642 3345 1990 Jun 4.527347601 4.2 1990 Jul 0.646990838 3 1990 Aug 0.046415164 0 1990 Sep 1.092258758 153.1 1990 Oct 0.311219762 1108.9 1990 Nov 0.587291693 2382 1990 Dec 5.308972338 151051 1991 Jan 22.32453687 14657 1991 Feb 18.44824486 13698.3 1991 Mar 1.126359723 1776.9 1991 Apr 2.351234666 1822.4 1991 May 2.003649605 3648.8 1991 Jun 0.4555832 30.7 1991 Jul 0.565112346 0 1991 Aug 0.224883596 234 1991 Sep 0.015450395 22.2 1991 Oct 0.145235384 3180.4 1991 Nov 1.553013636 9825.3 1991 Dec 2.251326392 925.3 1992 Jan 2.599549108 337 1992 Feb 8.682109264 95.2 1992 Mar 2.174757808 1444 1992 Apr 3.052451015 672.8 1992 May 3.273742197 1 1992 Jun 0.39244459 0 1992 Jul 0.840604631 2.1 1992 Aug 0.412808914 3.8 1992 Sep 0.913561096 0.3 1992 Oct 0.361931296 776.6 1992 Nov 0.808052022 103.2 1992 Dec 5.561746222 111.3 1993 Jan 7.356005875 70.9 1993 Feb 9.421036774 401.4 1993 Mar 1.602188031 1118.9 1993 Apr 2.345366872 1974.5 1993 May 1.940469251 250.7 1993 Jun 1.09880524 3.5 1993 Jul 2.080590269 0 1993 Aug 0.770423966 111 1993 Sep 1.226436054 103.5 1993 Oct 0.439254646 362.2 1993 Nov 1.833521606 383.3 1993 Dec 3.097896158 925.2 1994 Jan 7.374966044 680.1 1994 Feb 11.0116763 1487.7 1994 Mar 5.117271775 141.4 1994 Apr 3.052883537 11569 1994 May 1.742208491 177.5 1994 Jun 1.164939189 60.2 1994 Jul 1.799578179 20.6 1994 Aug 0.832932325 838.7 1994 Sep 0.369372762 785.2 1994 Oct 0.583245128 1197.8 1994 Nov 0.998170393 3841 1994 Dec 2.292031843 869.9 1995 Jan 3.952888203 223 1995 Feb 14.98503552 10321.2 1995 Mar 8.786371933 518.5 1995 Apr 1.15537876 100.6 1995 May 2.548755845 2.3 1995 Jun 1.351001388 0.1 1995 Jul 0.228689756 16.1 1995 Aug 3.607614625 169.1 1995 Sep 0.140126023 2.1 1995 Oct 1.736401062 1559.3 1995 Nov 1.878256805 1342.7 1995 Dec 2.412888581 1050.3 1996 Jan 10.93723802 1482.8 1996 Feb 5.082749085 1637.2 1996 Mar 9.487968655 6351 1996 Apr 3.229533229 340.2 1996 May 2.401398017 218.6 1996 Jun 1.846022576 0.3 1996 Jul 1.199434211 0.1 1996 Aug 0.387229601 6.5 1996 Sep 0.190375922 114.8 1996 Oct 3.075383908 69.9 1996 Nov 0.68077727 280.8 1996 Dec 4.970757516 703.2 1997 Jan 8.790548173 12243.8 1997 Feb 8.534348074 1835.4 1997 Mar 10.25784484 2367.2 1997 Apr 2.025686853 8374.6 1997 May 1.505061617 67.4 1997 Jun 1.61775719 79.7 1997 Jul 0.841512119 45.5 1997 Aug 1.13390946 32.7 1997 Sep 0.793177789 175.2 1997 Oct 0.51100862 1539.6 1997 Nov 2.020241788 1864.9 1997 Dec 11.13430326 39973.7 1998 Jan 14.50427496 6981.6 1998 Feb 7.826202642 2158 1998 Mar 6.001887795 3407.9 1998 Apr 3.226931965 19.1 1998 May 3.369861482 28.1 1998 Jun 1.100020262 1.2 1998 Jul 0.966158915 1.6 1998 Aug 1.898565651 2.7 1998 Sep 2.286590285 707 1998 Oct 1.954612957 15530.4 1998 Nov 4.616066305 515.6 1998 Dec 5.468446007 21967.6 1999 Jan 9.553564564 21914.7 1999 Feb 14.57666726 1022.7 1999 Mar 12.09503898 1213.3 1999 Apr 6.200550272 1569 1999 May 1.120759693 226 1999 Jun 0.858177187 0.2 1999 Jul 1.238553864 11 1999 Aug 1.156362194 33.2 1999 Sep 0.696475044 8408.3 1999 Oct 0.575699231 65.6 1999 Nov 6.446502564 394.8 1999 Dec 6.648617816 2088.9 2000 Jan 5.987250899 2925.7 2000 Feb 20.16319547 3081.9 2000 Mar 6.798066345 257.6 2000 Apr 9.1328323 442.4 2000 May 1.5397691 5.9 2000 Jun 2.451942776 0 2000 Jul 0.219638479 15.5 2000 Aug 0.935226785 10.32 2000 Sep 0.134735405 29.001 2000 Oct 2.348875937 3.37 2000 Nov 7.375675069 1183.21 2000 Dec 10.71783577 13580.481 2001 Jan 5.325595722 7778.421 2001 Feb 14.91304157 3782.59 2001 Mar 5.876859974 3969.6931 2001 Apr 3.281430754 1583.8722 2001 May 0.155103437 67.601 2001 Jun 2.006395633 11.1 2001 Jul 0.325604959 8.1 2001 Aug 0.227212846 163.67 2001 Sep 0.527586533 28.631 2001 Oct 1.463056483 39.43 2001 Nov 2.257756323 179.925 2001 Dec 3.54509221 6312.5072 2002 Jan 6.478581916 2146.8811 2002 Feb 10.29281488 1349.532 2002 Mar 3.083575243 7790.012 2002 Apr 2.474725154 34848.2711 2002 May 1.86478044 632.79 2002 Jun 0.358581954 6.14 2002 Jul 0.343009071 25.831 2002 Aug 1.192817925 62.121 2002 Sep 0.291970376 2105.66 2002 Oct 0.015735386 274.523 2002 Nov 0.623493006 2766.307 2002 Dec 2.079099462 217542.637 2003 Jan 4.265188137 1119536.36 2003 Feb 8.040918003 1404.785 2003 Mar 5.305213174 780.2 2003 Apr 3.465696674 1037.9911 2003 May 2.496173679 3.89 2003 Jun 1.661322809 113.47 2003 Jul 0.977483907 7.32 2003 Aug 0.461953304 829.101 2003 Sep 0.106864347 6524.995 2003 Oct 0.426773025 3417.1801 2003 Nov 0.45507914 1331.27 2003 Dec 6.209697227 645.679 2004 Jan 8.23677275 603.0637 2004 Feb 11.56753974 1292.6503 2004 Mar 11.73459508 2106.064 2004 Apr 5.119202846 5280.116 2004 May 1.502925662 14.92 2004 Jun 0.829546367 25.361 2004 Jul 0.943796857 1.23 2004 Aug 0.186290381 64.245 2004 Sep 0.441521915 101.271 2004 Oct 0.486378075 1088.842 2004 Nov 2.500203824 960.12 2004 Dec 6.776089301 1040.034 2005 Jan 9.048194224 19342.1061 2005 Feb 3.388376157 666.111 2005 Mar 4.865344467 7547.881 2005 Apr 3.435378673 2119.1682 2005 May 0.645825203 120.4913 2005 Jun 1.422382075 26.16 2005 Jul 1.823086651 0.13 2005 Aug 2.249076383 14.9903 2005 Sep 0.17746017 1.813 2005 Oct 1.113971566 41.623 2005 Nov 1.515732371 91.6305 2005 Dec 2.232137387 10255.0104 2006 Jan 11.18158131 170791.625 2006 Feb 4.311152406 1606.5712 2006 Mar 15.26285318 4348.833 2006 Apr 11.90241981 1364.0228 2006 May 2.81938899 7.016 2006 Jun 2.37945952 29.147 2006 Jul 2.80622574 11.47 2006 Aug 0.258222313 323.642 2006 Sep 2.014129952 23355.003 2006 Oct 1.16087706 2415.734 2006 Nov 0.45965792 26622.0592 2006 Dec 4.138020688 1101463.715 2007 Jan 9.376425163 40727.366 2007 Feb 18.36368504 4726.1901 2007 Mar 5.547222998 377.026 2007 Apr 1.884331476 5268.022 2007 May 2.611790703 52.761 2007 Jun 4.106621019 1.503 2007 Jul 0.504714418 0.021 2007 Aug 0.529458095 406.024 2007 Sep 0.376155977 6.367 2007 Oct 1.255303806 65.9259 2007 Nov 2.369059569 19649.5152 2007 Dec 7.471254048 7225.033 2008 Jan 10.55731175 2176.8901 2008 Feb 15.78327792 1078.429 2008 Mar 10.30946732 1183.3301 2008 Apr 0.861034471 635.6581 2008 May 1.480145327 36.881 2008 Jun 0.636880083 2.32 2008 Jul 2.845478716 15.551 2008 Aug 0.147091135 50.421 2008 Sep 1.14039027 551.05 2008 Oct 1.133310063 11727.761 2008 Nov 3.59819497 1118.342 2008 Dec 6.151984026 127.6061 2009 Jan 22.76297266 8015.691 2009 Feb 17.79593844 402533.826 2009 Mar 3.009901396 12625.9623 2009 Apr 3.348459983 479.6262 2009 May 2.279772489 143.29 2009 Jun 0.313328878 0.1111 2009 Jul 0.244595851 3.781 2009 Aug 0.191970942 197.7892 2009 Sep 0.093562116 38.0925 2009 Oct 0.58448777 18.607 2009 Nov 2.45870127 6002.2512 2009 Dec 3.701254902 17831.4243 2010 Jan 14.66961631 9763.2427 2010 Feb 9.64794254 468.6606 2010 Mar 6.187229353 2890.7111 2010 Apr 6.155531294 15.258 2010 May 0.885427626 1.725 2010 Jun 0.703550438 0.012 2010 Jul 1.281893083 0.021 2010 Aug 1.63783392 75.1 2010 Sep 2.724098656 13.521 2010 Oct 4.354737226 807.813 2010 Nov 7.565594903 32.061 2010 Dec 11.87070645 382.612 2011 Jan 11.52153183 72.396 2011 Feb 15.5398423 11790.612 2011 Mar 15.56511994 788.411 2011 Apr 2.681864339 97.0701 2011 May 0.669399172 70 2011 Jun 1.313145635 2.141 2011 Jul 0.410214784 1.01 2011 Aug 0.427651311 0.361 2011 Sep 0.330379107 47.41 2011 Oct 3.318839464 5.262 2011 Nov 2.390030624 60.696 2011 Dec 5.469173888 540.2526 From bgailer at gmail.com Tue May 15 05:38:01 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 14 May 2012 23:38:01 -0400 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: References: Message-ID: <4FB1CF99.8050609@gmail.com> On 5/14/2012 10:16 PM, questions anon wrote: > I am completely new to dictionaries and I am not even sure if this is > what I need to use. > I have a text file that I would like to run summary stats on > particular months, years and climate indices (in this case the climate > indices are rainfall and fire area, so not actualy climate indices at > all). I would set up a SQLite database with a table of 4 numeric columns: year, month, rainfall, firearea Use SQL to select the desired date range and do the max and avg calculations: select year, avg(firearea), max(rainfall) from table where year = 1973 and month between 6 and 8) you can use dictionaries but that will be harder. Here a start (untested). Assumes data are correct. months = dict(Jan=1,Feb=2,Mar=4,Apr=4,May=5,Jun=6,Jul=7,Aug=8,Sep=9.Oct=10,Nov=11,Dec=12) for line in open('d:/yearmonthrainfire.txt','r'): line = line.split() year = int(line[0]) month = months[line[1]] rainfall = float(line[2] firearea = float(line[3] sql = "insert into table (year, month, rainfall, firearea) values(%i,%i,%f,%f)" % (year, month, rainfall, firearea) # I don't have handy how one runs the sql > > A text file is attached but a small sample of the file: > rainfall firearea > 1972 Jan 12.7083199 0 > 1972 Feb 14.17007142 0 > 1972 Mar 14.5659302 0 > 1972 Apr 1.508517302 0 > 1972 May 2.780009889 0 > 1972 Jun 1.609619287 0 > 1972 Jul 0.138150181 28 > 1972 Aug 0.214346148 32 > 1972 Sep 1.322102228 34747.8 > 1972 Oct 0.092663137 3655.9 > 1972 Nov 1.852276635 85.1 > 1972 Dec 2.011206002 42959.6 > 1973 Jan 5.55704346 153.5 > 1973 Feb 12.60326356 116.2 > 1973 Mar 11.08849105 223.6 > 1973 Apr 5.864925449 2.4 > ...... > > I have used an example from a book (a primer on scientific programming > with python) and it seems to be working (see below) but I am not sure > if I have my keys etc. are set up correctly to then begin anlaysis, > and even how to use the dictionaries in my analysis > . For example how can I print out the year with calculated the mean > 'firearea' of June-July-August for that year along with the maximum > 'rainfall' for June-July-august of the same year? > Any feedback will be greatly appreaciated! > > infile=open('d:/yearmonthrainfire.txt','r') > lines=infile.readlines() > infile.close() > data={} #data[index][year]=indexvalue > first_line=lines[0] > climateindexname=first_line.split() > for index in climateindexname: > data[index]={} > YEAR={} > MONTH={} > > for line in lines[2:]: > words=line.split() > year=words[0] #years > YEAR[year]={} > month=words[1] #months > MONTH[month]={} > values=words[2:] #values of climateindices > for index, v in zip(climateindexname, values): > if v !=' ': > data[index][year]=float(v) > > print "years=", YEAR > print "months=", MONTH > print "data=", data We usually reserve all caps names for constants. You have way too many dictionaries. Your program seems very complex for a very simple task. I will not attempt to figure out what it does. > > > _______________________________________________ > 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 Tue May 15 05:39:17 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 14 May 2012 23:39:17 -0400 Subject: [Tutor] Multiple DBs per application? In-Reply-To: <4FB19B88.4040403@gmail.com> References: <4FB19B88.4040403@gmail.com> Message-ID: <4FB1CFE5.9020703@gmail.com> On 5/14/2012 7:55 PM, Leam Hall wrote: > On 05/14/2012 06:44 PM, Alan Gauld wrote: >> On 14/05/12 20:33, leam hall wrote: >>> Just a general question. If you have an application with different >>> data types where it might be better to use one database over another, >>> are there issues with having multiple databases used by the >>> application? >> >> >> No, you can usuially have multiple databases open at once. >> You can have multiple instances of the same database or >> different database types. >> >> However the data types are rarely ta reason to use different databases. >> More typically would be different performance requirements or security >> issues. For example it's common to hold some data in an LDAP structure >> for speed of access (at the expense of flexibility) and the rest of the >> data in an RDBMS such as MySql. But using say MySQL and Oracle together >> would normally only be done because they were pre-existing datastores >> from another project. > > Thanks! I was more thinking of something like a CMS where user login > information and admin functions might be in a SQLite database and then > some larger backend big data stuff in MongoDB or similar. Just wasn't > sure if there was a basic flaw to the idea that I wasn't aware of. Seems like a good idea. Right tool for right purpose. -- Bob Gailer 919-636-4239 Chapel Hill NC From questions.anon at gmail.com Tue May 15 08:12:34 2012 From: questions.anon at gmail.com (questions anon) Date: Tue, 15 May 2012 16:12:34 +1000 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: <4FB1CF99.8050609@gmail.com> References: <4FB1CF99.8050609@gmail.com> Message-ID: Thanks Bob, sql does appear to be very simple although I cannot get the queries to work. Can you suggest a site that has examples for what I am trying to do. I have done some googling but it has not been successful so far. On Tue, May 15, 2012 at 1:38 PM, bob gailer wrote: > On 5/14/2012 10:16 PM, questions anon wrote: > > I am completely new to dictionaries and I am not even sure if this is what > I need to use. > I have a text file that I would like to run summary stats on particular > months, years and climate indices (in this case the climate indices are > rainfall and fire area, so not actualy climate indices at all). > > I would set up a SQLite database with a table of 4 numeric columns: year, > month, rainfall, firearea > Use SQL to select the desired date range and do the max and avg > calculations: > select year, avg(firearea), max(rainfall) from table where year = 1973 and > month between 6 and 8) > > you can use dictionaries but that will be harder. Here a start (untested). > Assumes data are correct. > > months = > dict(Jan=1,Feb=2,Mar=4,Apr=4,May=5,Jun=6,Jul=7,Aug=8,Sep=9.Oct=10,Nov=11,Dec=12) > for line in open('d:/yearmonthrainfire.txt','r'): > line = line.split() > year = int(line[0]) > month = months[line[1]] > rainfall = float(line[2] > firearea = float(line[3] > sql = "insert into table (year, month, rainfall, firearea) > values(%i,%i,%f,%f)" % (year, month, rainfall, firearea) > # I don't have handy how one runs the sql > > > A text file is attached but a small sample of the file: > rainfall firearea > 1972 Jan 12.7083199 0 > 1972 Feb 14.17007142 0 > 1972 Mar 14.5659302 0 > 1972 Apr 1.508517302 0 > 1972 May 2.780009889 0 > 1972 Jun 1.609619287 0 > 1972 Jul 0.138150181 28 > 1972 Aug 0.214346148 32 > 1972 Sep 1.322102228 34747.8 > 1972 Oct 0.092663137 3655.9 > 1972 Nov 1.852276635 85.1 > 1972 Dec 2.011206002 42959.6 > 1973 Jan 5.55704346 153.5 > 1973 Feb 12.60326356 116.2 > 1973 Mar 11.08849105 223.6 > 1973 Apr 5.864925449 2.4 > ...... > > I have used an example from a book (a primer on scientific programming > with python) and it seems to be working (see below) but I am not sure if I > have my keys etc. are set up correctly to then begin anlaysis, and even how > to use the dictionaries in my analysis > > . For example how can I print out the year with calculated the mean > 'firearea' of June-July-August for that year along with the maximum > 'rainfall' for June-July-august of the same year? > Any feedback will be greatly appreaciated! > > infile=open('d:/yearmonthrainfire.txt','r') > lines=infile.readlines() > infile.close() > data={} #data[index][year]=indexvalue > first_line=lines[0] > climateindexname=first_line.split() > for index in climateindexname: > data[index]={} > YEAR={} > MONTH={} > > for line in lines[2:]: > words=line.split() > year=words[0] #years > YEAR[year]={} > month=words[1] #months > MONTH[month]={} > values=words[2:] #values of climateindices > for index, v in zip(climateindexname, values): > if v !=' ': > data[index][year]=float(v) > > print "years=", YEAR > print "months=", MONTH > print "data=", data > > We usually reserve all caps names for constants. > You have way too many dictionaries. > Your program seems very complex for a very simple task. > I will not attempt to figure out what it does. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor > > > > -- > Bob Gailer919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 15 09:31:19 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 May 2012 08:31:19 +0100 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: References: <4FB1CF99.8050609@gmail.com> Message-ID: On 15/05/12 07:12, questions anon wrote: > Thanks Bob, > sql does appear to be very simple although I cannot get the queries to > work. Can you suggest a site that has examples for what I am trying to > do. I have done some googling but it has not been successful so far. You can try my tutorial topic on databases. It covers the basics of using SQLlite to query data in a fairly concise format. Its only available in the Version 2 tutor so far... http://www.alan-g.me.uk/tutor/tutdbms.htm -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From russel at winder.org.uk Tue May 15 11:36:45 2012 From: russel at winder.org.uk (Russel Winder) Date: Tue, 15 May 2012 10:36:45 +0100 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: <4FB1CF99.8050609@gmail.com> References: <4FB1CF99.8050609@gmail.com> Message-ID: <1337074605.18804.130.camel@launcelot.winder.org.uk> On Mon, 2012-05-14 at 23:38 -0400, bob gailer wrote: [...] > I would set up a SQLite database with a table of 4 numeric columns: > year, month, rainfall, firearea > Use SQL to select the desired date range and do the max and avg > calculations: > select year, avg(firearea), max(rainfall) from table where year = 1973 > and month between 6 and 8) > > you can use dictionaries but that will be harder. Here a start > (untested). Assumes data are correct. Clearly if the data is to be stored for a long time and have various (currently unknown) queries passed over it then year a database it the right thing -- though I would probably choose a non-SQL database. If the issues is to just do quick calculations over the data in the file format then nothing wrong with using dictionaries or parallel arrays ? la: with open ( 'yearmonthrainfire.txt' ) as infile : climateindexname = infile.readline ( ).split ( ) data = [ line.split ( ) for line in infile.readlines ( ) ] years = sorted ( { item[0] for item in data } ) months = [ 'Jan' , 'Feb' , 'Mar' , 'Apr' , 'May' , 'Jun' , 'Jul' , 'Aug' , 'Sep' , 'Oct' , 'Nov' , 'Dec' ] dataByYear = { year : [ ( float ( item[2] ) , float ( item[3] ) ) for item in data if item[0] == year ] for year in years } dataByMonth = { month : [ ( float ( item[2] ) , float ( item[3] ) ) for item in data if item[1] == month ] for month in months } averagesByYear = { year : ( sum ( dataByYear[year][0] ) / len ( dataByYear[year][0] ) , sum ( dataByYear[year][1] ) / len ( dataByYear[year][1] ) ) for year in years } averagesByMonth = { month : ( sum ( dataByMonth[month][0] ) / len ( dataByMonth[month][0] ) , sum ( dataByMonth[month][1] ) / len ( dataByMonth[month][1] ) ) for month in months } for year in years : print ( year , averagesByYear[year][0] , averagesByYear[year][1] ) for month in months : print ( month , averagesByMonth[month][0] , averagesByMonth[month][1] ) The cost of the repetition in the code here is probably minimal compared to the disc access costs. On the other hand this is a small data set so time is probably not a big issue. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From ramit.prasad at jpmorgan.com Tue May 15 17:45:34 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 15 May 2012 15:45:34 +0000 Subject: [Tutor] hello~ In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4740932D8A3@SCACMX008.exchad.jpmchase.net> >as you can see i only use some of the command. it doesnt produce an error message tho.. just repeats "return Error("%s I couldn't find %s anywhere", user.name.title(), name.title())" Your problem might be is indenting of the else. It is indenting to be a for...else loop. Which means that if nothing breaks out of the loop it will always do what is in the else (which in this case returns Error[...]) after the loop has finished running through the rooms. ? ? ? ? for room in mgr.rooms: ? ? ? ? ? ? ? ? if data[1] == "join": ? ? ? ? ? ? ? ? ? ? ? ? mgr.sendObject(target, Html("%s, %s wants to tell you %s", name.title, user.name.title$ ? ? ? ? else: ? ? ? ? ? ? ? ? ? ? ? ? return Error("%s I couldn't find %s anywhere", user.name.title(), name.title()) Why are you looping through the rooms and checking if data[1] == "join"? You do not even use the room object in the loop, and target is not defined in the local scope, although I suppose you meant to use room instead. This loop just "smells" to me. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Tue May 15 19:41:36 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 15 May 2012 17:41:36 +0000 Subject: [Tutor] extracting lines between patterns. In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4740932DA17@SCACMX008.exchad.jpmchase.net> > Friends, >Could someone please give some hint on how to extract lines between two patterns in a file. I use the re module to compile my patterns but not able to figure out how i can use these patterns to extract the lines lying in between. Not sure exactly what you want but something like this could work. Note, this is not memory efficient. line = file.read() index1 = line.find( PATTERN1 ) index2 = line.find( PATTERN2 ) in_between = line[index1 + len( index1 ):index2] number_of_lines = len( in_between.split() ) # -1 ? # might need to adjust (-1) to avoid the line PATTERN1 is on Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Tue May 15 20:14:45 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 May 2012 19:14:45 +0100 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: <1337074605.18804.130.camel@launcelot.winder.org.uk> References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> Message-ID: On 15/05/12 10:36, Russel Winder wrote: > ...queries passed over it then year a database it the > right thing -- though I would probably choose a non-SQL database. As a matter of interest why? And what kind of alternative would you use? It seems to me that SQL is ideally suited(*) to this type of role. I'm curious what the alternatives might be and why they would be preferred? (*)Because: Flexible query language, wide set of tools including GUI query builders, reporting tools etc. Plus easy integration with programming environments, scaleability (less an issue here), security(usually) etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From tvssarma.omega9 at gmail.com Wed May 16 12:13:46 2012 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Wed, 16 May 2012 15:43:46 +0530 Subject: [Tutor] Error Using A List And SMTP Message-ID: Hey guys, I was just trying out SMTP and I keep getting a attribute error, *AttributeError: 'list' object has no attribute 'lstrip''*, when I use a list to store the send address. Code - http://pastebin.com/9NmCNdRb Traceback - http://pastebin.com/m1cgKDnn I'm not sure I understand why this is happening. -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed May 16 13:19:20 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 16 May 2012 12:19:20 +0100 Subject: [Tutor] Error Using A List And SMTP In-Reply-To: References: Message-ID: Hi Sarma On 16 May 2012 11:13, Sarma Tangirala wrote: > Hey guys, > > I was just trying out SMTP and I keep getting a attribute error, *AttributeError: > 'list' object has no attribute 'lstrip''*, when I use a list to store the > send address. > > Code - http://pastebin.com/9NmCNdRb > > Traceback - http://pastebin.com/m1cgKDnn > > I'm not sure I understand why this is happening. > All the headers in the MimeText object needs to be strings. You can't directly pass a list object containing multiple recipients to the "To" header of your MimeText object on line 31 in your code, and expect it to work. You've got to instead first convert the list to valid string and assign that instead, as that's what the MimeText object expects. You can infer this from your error messages since lstrip() is a string method, and the code is (rightly) complaining that a list doesn't have an lstrip() method, which is understandable becuase you're getting the error when you pass a list as parameter. A quick google yields this question/answer on stackoverflow which is relevant to your question. (See the "cc:" bits): http://stackoverflow.com/questions/5304835/how-to-send-gmail-email-with-multiple-ccs Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From russel at winder.org.uk Wed May 16 13:27:28 2012 From: russel at winder.org.uk (Russel Winder) Date: Wed, 16 May 2012 12:27:28 +0100 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> Message-ID: <1337167648.590.6.camel@lionors.winder.org.uk> On Tue, 2012-05-15 at 19:14 +0100, Alan Gauld wrote: > On 15/05/12 10:36, Russel Winder wrote: > > ...queries passed over it then year a database it the > > right thing -- though I would probably choose a non-SQL database. > > As a matter of interest why? Because there are alternatives that need to be investigated on a per problem basis for the best database. SQL MongoDB CouchDB Cassandra Neo etc. Python only has SQLite3 as standard but there are alternatives. I have been using PyMongo quite successfully. > And what kind of alternative would you use? See above ;-) > It seems to me that SQL is ideally suited(*) to this type of role. I'm > curious what the alternatives might be and why they would be preferred? > > (*)Because: Flexible query language, wide set of tools including GUI > query builders, reporting tools etc. Plus easy integration with > programming environments, scaleability (less an issue here), > security(usually) etc. It is not clear that the original table works better with the relational model compared to one of the key-value stores or document stores. It might. But I no longer always go to SQL for persistence as I used to a few years ago. There are various articles around the Web comparing and contrasting these various models. Some of the articles are even reasonable :-) -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From tvssarma.omega9 at gmail.com Wed May 16 13:34:20 2012 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Wed, 16 May 2012 17:04:20 +0530 Subject: [Tutor] Error Using A List And SMTP In-Reply-To: References: Message-ID: Hi Walter, > All the headers in the MimeText object needs to be strings. You can't > directly pass a list object containing multiple recipients to the "To" > header of your MimeText object on line 31 in your code, and expect it to > work. You've got to instead first convert the list to valid string and > assign that instead, as that's what the MimeText object expects. You can > infer this from your error messages since lstrip() is a string method, and > the code is (rightly) complaining that a list doesn't have an lstrip() > method, which is understandable becuase you're getting the error when you > pass a list as parameter. > > Thank you for clearing that. Stupid mistake here. I forgot to change the variable names. But I do have another question. Maybe this is a misunderstanding about the MimeText type, but why does MimeText care about the To field when the actually sending is being done by SMTP? -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From tvssarma.omega9 at gmail.com Wed May 16 13:37:49 2012 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Wed, 16 May 2012 17:07:49 +0530 Subject: [Tutor] Error Using A List And SMTP In-Reply-To: References: Message-ID: On 16 May 2012 17:04, Sarma Tangirala wrote: > Hi Walter, > > >> All the headers in the MimeText object needs to be strings. You can't >> directly pass a list object containing multiple recipients to the "To" >> header of your MimeText object on line 31 in your code, and expect it to >> work. You've got to instead first convert the list to valid string and >> assign that instead, as that's what the MimeText object expects. You can >> infer this from your error messages since lstrip() is a string method, and >> the code is (rightly) complaining that a list doesn't have an lstrip() >> method, which is understandable becuase you're getting the error when you >> pass a list as parameter. >> >> > Thank you for clearing that. Stupid mistake here. I forgot to change the > variable names. > > But I do have another question. Maybe this is a misunderstanding about the > MimeText type, but why does MimeText care about the To field when the > actually sending is being done by SMTP? > > OK. That was a stupid question. Sorry for the noise. Please ignore. > > > -- > Sarma Tangirala, > Class of 2012, > Department of Information Science and Technology, > College of Engineering Guindy - Anna University > > -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed May 16 17:03:06 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 May 2012 16:03:06 +0100 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: <1337167648.590.6.camel@lionors.winder.org.uk> References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> <1337167648.590.6.camel@lionors.winder.org.uk> Message-ID: On 16/05/12 12:27, Russel Winder wrote: >> As a matter of interest why? > > Because there are alternatives that need to be investigated on a per > problem basis for the best database. I agree, but in this case SQL seemed like the most likely fit of the ones I knew. however: > SQL > MongoDB I know about these > CouchDB > Cassandra > Neo These are new to me. > etc. Python only has SQLite3 as standard but there are alternatives. I > have been using PyMongo quite successfully. Python comes with several storage/access options including shelve, gdbm, ldap, cobfig files, XML, in addition to SQL. > It is not clear that the original table works better with the relational > model compared to one of the key-value stores or document stores. Most key-value stores are optimised for fast queries of a single type and generally not great at grouping or ordering. They also tend to major on flexiblity of data format. The OPs requirements suggested intelligent filtering of a fixed record format which is one of the areas where SQL works well. The other side of the coin is that the data is essentially single table so the relationship management aspects of SQL would not be needed. So I agree we don't have enough detail to be 100% sure that another option would not work as well or better. But most other options require learning new (often bespoke) query languages and have limited user tools. All of these factors need to be included too. Mongo et al tend to be better suited, in my experience, to machine access applications rather than end user access. > There are various articles around the Web comparing and contrasting > these various models. Some of the articles are even reasonable :-) Wikipedia is my friend :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed May 16 17:07:34 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 May 2012 16:07:34 +0100 Subject: [Tutor] Error Using A List And SMTP In-Reply-To: References: Message-ID: On 16/05/12 12:37, Sarma Tangirala wrote: > But I do have another question. Maybe this is a misunderstanding > about the MimeText type, but why does MimeText care about the To > field when the actually sending is being done by SMTP? > OK. That was a stupid question. Sorry for the noise. Please ignore. Actually for a beginners list I thought it was a perfectly reasonable question! :-) But I assume you figured out the answer for yourself so that's fine. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From tvssarma.omega9 at gmail.com Wed May 16 17:17:08 2012 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Wed, 16 May 2012 20:47:08 +0530 Subject: [Tutor] Error Using A List And SMTP In-Reply-To: References: Message-ID: On 16 May 2012 20:37, Alan Gauld wrote: > On 16/05/12 12:37, Sarma Tangirala wrote: > >> But I do have another question. Maybe this is a misunderstanding >> about the MimeText type, but why does MimeText care about the To >> field when the actually sending is being done by SMTP? >> > > OK. That was a stupid question. Sorry for the noise. Please ignore. >> > > Actually for a beginners list I thought it was a perfectly reasonable > question! :-) > > But I assume you figured out the answer for yourself so that's fine. > > Not exactly. I did not read the immediate reply properly and got stupid. :P > -- > Alan G > 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 > -- An monkey typed up this email. Please excuse him if he made a stupid error! -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed May 16 18:57:36 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 16 May 2012 12:57:36 -0400 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> <1337167648.590.6.camel@lionors.winder.org.uk> Message-ID: On Wed, May 16, 2012 at 11:03 AM, Alan Gauld wrote: > On 16/05/12 12:27, Russel Winder wrote: > >>> As a matter of interest why? >> >> >> Because there are alternatives that need to be investigated on a per >> problem basis for the best database. > > > I agree, but in this case SQL seemed like the most likely fit of the ones I > knew. however: > >> ? ? ? ? SQL >> ? ? ? ? MongoDB > > > I know about these > >> ? ? ? ? CouchDB >> ? ? ? ? Cassandra >> ? ? ? ? Neo > > > These are new to me. > > >> etc. Python only has SQLite3 as standard but there are alternatives. I >> have been using PyMongo quite successfully. > > > Python comes with several storage/access options including shelve, gdbm, > ldap, cobfig files, XML, in addition to SQL. > > >> It is not clear that the original table works better with the relational >> model compared to one of the key-value stores or document stores. > > > Most key-value stores are optimised for fast queries of a single type > and generally not great at grouping or ordering. They also tend to major on > flexiblity of data format. The OPs requirements suggested intelligent > filtering of a fixed record format which is one of the areas where SQL works > well. The other side of the coin is that the data is essentially single > table so the relationship management aspects of SQL would not be needed. So > I agree we don't have enough detail > to be 100% sure that another option would not work as well or better. > > But most other options require learning new (often bespoke) query languages > and have limited user tools. All of these factors need to be included too. > Mongo et al tend to be better suited, in my experience, to machine access > applications rather than end user access. > > >> There are various articles around the Web comparing and contrasting >> these various models. Some of the articles are even reasonable :-) > > > Wikipedia is my friend :-) > > > -- > Alan G > 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 I think the OP is just learning and this thread may have gotten of track. Here is some code to get started. I decided to use sqlite3 since its easy to use with python -- no finding and learning to load packages. #!/usr/bin/env python import sqlite3 as db # Ideally this shouldn't be global, but in this short code snippet it gets the job done # here we create a database and get a cursor conn = db.connect('climate.db') cursor = conn.cursor() print cursor # this will create a table for our data sql_create = """CREATE TABLE if not exists rain ( id INTEGER PRIMARY KEY, year INTEGER, month TEXT(3), rainfall FLOAT, fire_area FLOAT )""" # this will read the data file and put it in our database def populate_climate_table(file_name): """ reads the file_name and insert data into sqlite table """ sql_insert_string = "insert into rain (year, month, rainfall, fire_area) values (%d, '%s', %f, %f)" f = open(file_name) f.readline() # get rid of column headers for l in f.readlines(): data_list = l.split() print data_list sql_insert = sql_insert_string % (int(data_list[0]), data_list[1], float(data_list[2]), float(data_list[3])) print sql_insert cursor.execute(sql_insert) conn.commit() if __name__ == '__main__': print sql_create cursor.execute(sql_create) populate_climate_table('data.txt') So, I haven't solved all of the questions with this code. The next thing to do is to read a little about sqlite select statements. for example: sqlite> select sum(rainfall)/count(*) from rain; 3.97352768125 This statement will give the average rainfall over the complete dataset. To get the ave rainfall for a given year do this: sqlite> select sum(rainfall)/count(*) from rain where year = 1983; Come back with more questions -- Joel Goldstick From adamgold at lavabit.com Wed May 16 20:17:39 2012 From: adamgold at lavabit.com (Adam Gold) Date: Wed, 16 May 2012 19:17:39 +0100 Subject: [Tutor] ssh socks proxy Message-ID: <9DA9E81C-6897-42BB-A326-B7487B7F5986@lavabit.com> I'm trying to write a 'simple' script that will set up a socks proxy over ssh and maintain the connection until manually terminated. It's not possible to use key-based authentication so a password will need to be supplied. Also, note, the user is presented with a list of servers to choose from at the beginning. The actual ssh command is: 'ssh -vNCD 23333 user at host'. I've been tinkering with both pexpect and paramiko but fear I'm making a mountain out of a mole hill. I'm aware both have example scripts for ssh forwarding but, to be honest, they are both too complicated (aka I don't know how to customise them). Here is one script I've attempted to get working and the associated error listing: http://pastebin.com/jj8Fgvwm - script http://pastebin.com/jRA8zpzi - error Could anyone help me either correct the script I've started or suggest an ockham's-razor-adherent alternative! Many thanks. From glchristian at comcast.net Wed May 16 22:17:55 2012 From: glchristian at comcast.net (Greg Christian) Date: Wed, 16 May 2012 14:17:55 -0600 Subject: [Tutor] TypeError: 'int' object is not callable Message-ID: <4122AFB44E7148A5806A09BD128CA07E@GREGPC> Can anyone tell me what I am doing wrong here. When trying to call the factors function from main with x = factors(Tn), getting the error message: ?TypeError: 'int' object is not callable?? Any help would be appreciated. Thanks. def factors(n): L = [] for i in range(1, int(n ** 0.5) + 1): if (n % i == 0): L.append(i) return L def main(): factors = 0 counter = 0 L = [] while len(L) < 50: counter += 1 L.append(counter) Tn = sum(L) x = factors(Tn) #print x print(sum(L)) if __name__ == '__main__': main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From modulok at gmail.com Wed May 16 22:37:53 2012 From: modulok at gmail.com (Modulok) Date: Wed, 16 May 2012 14:37:53 -0600 Subject: [Tutor] TypeError: 'int' object is not callable In-Reply-To: <4122AFB44E7148A5806A09BD128CA07E@GREGPC> References: <4122AFB44E7148A5806A09BD128CA07E@GREGPC> Message-ID: On 5/16/12, Greg Christian wrote: > Can anyone tell me what I am doing wrong here. When trying to call the > factors function from main with x = factors(Tn), getting the error message: > ?TypeError: 'int' object is not callable?? Any help would be appreciated. > Thanks. > > > def factors(n): > L = [] > for i in range(1, int(n ** 0.5) + 1): > if (n % i == 0): > L.append(i) > return L > > def main(): > factors = 0 > counter = 0 > L = [] > while len(L) < 50: > counter += 1 > L.append(counter) > Tn = sum(L) > x = factors(Tn) > #print x > print(sum(L)) > > > if __name__ == '__main__': > main() You declared 'factors' as a variable on line 1 in main:: factors = 0 This masks the call to the function 'factors'. You get the error because you assigned factors an integer and you cannot 'call' an integer. The easiest solution is to use another name for the variable 'factors' instead. -Modulok- From emile at fenx.com Wed May 16 22:43:55 2012 From: emile at fenx.com (Emile van Sebille) Date: Wed, 16 May 2012 13:43:55 -0700 Subject: [Tutor] TypeError: 'int' object is not callable In-Reply-To: <4122AFB44E7148A5806A09BD128CA07E@GREGPC> References: <4122AFB44E7148A5806A09BD128CA07E@GREGPC> Message-ID: On 5/16/2012 1:17 PM Greg Christian said... > def factors(n): > L = [] > for i in range(1, int(n ** 0.5) + 1): > if (n % i == 0): > L.append(i) > return L ... now you've completed defining the function factors... > def main(): > factors = 0 ... and here you create an integer of the same name... > counter = 0 > L = [] > while len(L) < 50: > counter += 1 > L.append(counter) > Tn = sum(L) > x = factors(Tn) ... and here you attempt to call the interger factors passing it the argument Tn > #print x > print(sum(L)) Also, in the future please post the complete traceback -- it relly helps. Emile From rbastian at musiques-rb.org Wed May 16 22:44:26 2012 From: rbastian at musiques-rb.org (=?ISO-8859-1?B?UmVu6Q==?= Bastian) Date: Wed, 16 May 2012 22:44:26 +0200 Subject: [Tutor] TypeError: 'int' object is not callable In-Reply-To: References: <4122AFB44E7148A5806A09BD128CA07E@GREGPC> Message-ID: <20120516224426.7c455eb1@rene.carmen> Le Wed, 16 May 2012 14:37:53 -0600, Modulok a ?crit : > On 5/16/12, Greg Christian wrote: > > Can anyone tell me what I am doing wrong here. When trying to call > > the factors function from main with x = factors(Tn), getting the > > error message: ?TypeError: 'int' object is not callable?? Any help > > would be appreciated. Thanks. > > > > > > def factors(n): > > L = [] > > for i in range(1, int(n ** 0.5) + 1): > > if (n % i == 0): > > L.append(i) > > return L > > > > def main(): > > factors = 0 > > counter = 0 > > L = [] > > while len(L) < 50: > > counter += 1 > > L.append(counter) > > Tn = sum(L) > > x = factors(Tn) > > #print x > > print(sum(L)) > > > > > > if __name__ == '__main__': > > main() > > You declared 'factors' as a variable on line 1 in main:: > > factors = 0 > > This masks the call to the function 'factors'. You get the error > because you assigned factors an integer and you cannot 'call' an > integer. The easiest solution is to use another name for the variable > 'factors' instead. > > -Modulok- If you use 'pylint', a syntax checker, you get this: C: 1,0: Missing docstring C: 1,0:factors: Missing docstring W: 9,4:main: Redefining name 'factors' from outer scope (line 1) C: 8,0:main: Missing docstring E: 16,12:main: factors is not callable W: 16,8:main: Unused variable 'x' > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Ren? Bastian www.pythoneon.org From kushal.kumaran+python at gmail.com Thu May 17 04:59:16 2012 From: kushal.kumaran+python at gmail.com (kushal.kumaran+python at gmail.com) Date: Thu, 17 May 2012 08:29:16 +0530 Subject: [Tutor] ssh socks proxy In-Reply-To: <9DA9E81C-6897-42BB-A326-B7487B7F5986@lavabit.com> References: <9DA9E81C-6897-42BB-A326-B7487B7F5986@lavabit.com> Message-ID: Adam Gold wrote: >I'm trying to write a 'simple' script that will set up a socks proxy >over ssh and maintain the connection until manually terminated. It's >not possible to use key-based authentication so a password will need to >be supplied. Also, note, the user is presented with a list of servers >to choose from at the beginning. The actual ssh command is: 'ssh -vNCD >23333 user at host'. > >I've been tinkering with both pexpect and paramiko but fear I'm making >a mountain out of a mole hill. I'm aware both have example scripts for >ssh forwarding but, to be honest, they are both too complicated (aka I >don't know how to customise them). Here is one script I've attempted >to get working and the associated error listing: > >http://pastebin.com/jj8Fgvwm - script >http://pastebin.com/jRA8zpzi - error > >Could anyone help me either correct the script I've started or suggest >an ockham's-razor-adherent alternative! Many thanks. The error message indicates that there hostname HOST could not be resolved. You need to replace that with the value of the variable HOST. COMMAND = "ssh -vNDR 23333 {}@{}".format(USER, HOST) I'm curious to know why you can't use keys. They make things much simpler. -- regards, kushal From kushal.kumaran+python at gmail.com Thu May 17 05:01:44 2012 From: kushal.kumaran+python at gmail.com (kushal.kumaran+python at gmail.com) Date: Thu, 17 May 2012 08:31:44 +0530 Subject: [Tutor] ssh socks proxy In-Reply-To: References: <9DA9E81C-6897-42BB-A326-B7487B7F5986@lavabit.com> Message-ID: kushal.kumaran+python at gmail.com wrote: >Adam Gold wrote: > >>I'm trying to write a 'simple' script that will set up a socks proxy >>over ssh and maintain the connection until manually terminated. It's >>not possible to use key-based authentication so a password will need >to >>be supplied. Also, note, the user is presented with a list of servers >>to choose from at the beginning. The actual ssh command is: 'ssh >-vNCD >>23333 user at host'. >> >>I've been tinkering with both pexpect and paramiko but fear I'm making >>a mountain out of a mole hill. I'm aware both have example scripts >for >>ssh forwarding but, to be honest, they are both too complicated (aka I >>don't know how to customise them). Here is one script I've attempted >>to get working and the associated error listing: >> >>http://pastebin.com/jj8Fgvwm - script >>http://pastebin.com/jRA8zpzi - error >> >>Could anyone help me either correct the script I've started or suggest >>an ockham's-razor-adherent alternative! Many thanks. > >The error message indicates that there hostname HOST could not be >resolved. You need to replace that with the value of the variable HOST. > >COMMAND = "ssh -vNDR 23333 {}@{}".format(USER, HOST) > >I'm curious to know why you can't use keys. They make things much >simpler. Excuse the incorrect ssh command. New mail client tripped me up. -- regards, kushal From russel at winder.org.uk Thu May 17 09:27:07 2012 From: russel at winder.org.uk (Russel Winder) Date: Thu, 17 May 2012 08:27:07 +0100 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> <1337167648.590.6.camel@lionors.winder.org.uk> Message-ID: <1337239627.15934.94.camel@launcelot.winder.org.uk> On Wed, 2012-05-16 at 12:57 -0400, Joel Goldstick wrote: [...] > I think the OP is just learning and this thread may have gotten of track. I didn't realize discussion of immediate side issues and alternatives, and allowing people to exchange information was OT in this mailing list. Also of course, OP didn't mention databases, but was asking how to do it with lists and dictionaries. I think there is irony somewhere in here. > Here is some code to get started. I decided to use sqlite3 since its > easy to use with python -- no finding and learning to load packages. > > > #!/usr/bin/env python > > import sqlite3 as db > > # Ideally this shouldn't be global, but in this short code snippet it > gets the job done > # here we create a database and get a cursor > conn = db.connect('climate.db') > cursor = conn.cursor() > print cursor I believe that there are more problems than just global data here. One obvious thing is this code is not safe against exceptions. I appreciate this is a trivially small program, but I think it important that sample code presents good style or explicitly states what is wrong so as to present what not to do. Your comment about global sits well with this, but for me doesn't go far enough. Python introduced context managers and the with statement exactly for this sort of situation, following the lead of C++ with RAII. I think we should all get into the habit of using the with statement automatically in this situation. > # this will create a table for our data > sql_create = """CREATE TABLE if not exists rain ( > id INTEGER PRIMARY KEY, > year INTEGER, > month TEXT(3), > rainfall FLOAT, > fire_area FLOAT > )""" > > # this will read the data file and put it in our database > def populate_climate_table(file_name): > """ > reads the file_name and insert data into sqlite table > """ > sql_insert_string = "insert into rain (year, month, rainfall, > fire_area) values (%d, '%s', %f, %f)" > > f = open(file_name) Same comment about context managers and with statement applies here: this code is not exception safe. > f.readline() # get rid of column headers > for l in f.readlines(): > data_list = l.split() > print data_list > sql_insert = sql_insert_string % (int(data_list[0]), > data_list[1], float(data_list[2]), float(data_list[3])) Should we be promoting use of the format method in strings rather than the % operator? % is deprecated now. Although not an issue here, this sort of SQL string manipulation is at the heart of SQL injection attacks and so should be frowned upon. Hence SQLAlchemy's expression languages, which goes some way to avoiding the whole issue. At the expense of having to load an additional package. With package management on Debian/Fedora/Ubuntu/MacPorts or the pip command this is not difficult to add. > print sql_insert > cursor.execute(sql_insert) > conn.commit() > > > if __name__ == '__main__': > > print sql_create > cursor.execute(sql_create) > populate_climate_table('data.txt') > > > So, I haven't solved all of the questions with this code. The next > thing to do is to read a little about sqlite select statements. > for example: sqlite> select sum(rainfall)/count(*) from rain; > 3.97352768125 > > This statement will give the average rainfall over the complete dataset. > To get the ave rainfall for a given year do this: > sqlite> select sum(rainfall)/count(*) from rain where year = 1983; > > Come back with more questions -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From russel at winder.org.uk Thu May 17 09:39:59 2012 From: russel at winder.org.uk (Russel Winder) Date: Thu, 17 May 2012 08:39:59 +0100 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> <1337167648.590.6.camel@lionors.winder.org.uk> Message-ID: <1337240399.15934.106.camel@launcelot.winder.org.uk> On Wed, 2012-05-16 at 16:03 +0100, Alan Gauld wrote: [...] > I agree, but in this case SQL seemed like the most likely fit of the > ones I knew. however: Which raises the point that the best design of a given problem in a given context is the one that is most comprehensible to the people directly involved. > > SQL > > MongoDB > > I know about these I have it on good authority yesterday that MongDB is only properly useful in a single store context, i.e. not a replicated cluster. Along withthis comes news that Riak is very good and has a Python API. > > > CouchDB > > Cassandra > > Neo > > These are new to me. CouchDB is an Erlang implemented system. Ubuntu One uses this for example. Cassandra is an Apache project, a JVM-based system. MongoDB, CouchDB and Cassandra are "document stores". Neo4J is a graph repository so of a very different architecture and performance characteristics. And then there is Redis :-) > > > etc. Python only has SQLite3 as standard but there are alternatives. I > > have been using PyMongo quite successfully. > > Python comes with several storage/access options including shelve, gdbm, > ldap, cobfig files, XML, in addition to SQL. Indeed. The problem I have had with shelve for this sort of thing is that is is critically dependent on the pickling algorithm and so potentially Python version dependent. [...] > on flexiblity of data format. The OPs requirements suggested intelligent > filtering of a fixed record format which is one of the areas where SQL > works well. The other side of the coin is that the data is essentially > single table so the relationship management aspects of SQL would not be > needed. So I agree we don't have enough detail > to be 100% sure that another option would not work as well or better. The signpost here is that the table as is is likely not in third normal form, and that if the problem currently being solved was actually a small part of a bigger problem, this issue would need to be addressed. > But most other options require learning new (often bespoke) query > languages and have limited user tools. All of these factors need to be > included too. Mongo et al tend to be better suited, in my experience, to > machine access applications rather than end user access. Agreed. Unfortunately, vendor commercial issues often get in the way of experimenting to find out where the NoSQL systems are genuinely better than SQL ones. We will get there though. Interesting, or not, the "Big Data" people are rapidly realizing that data mining and SQL are mutually incompatible. The current trend is towards streaming whole databases through dataflow programs. But Java rather than Python is the default language in that world. > > There are various articles around the Web comparing and contrasting > > these various models. Some of the articles are even reasonable :-) > > Wikipedia is my friend :-) :-) -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From alan.gauld at btinternet.com Thu May 17 11:12:05 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 May 2012 10:12:05 +0100 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: <1337240399.15934.106.camel@launcelot.winder.org.uk> References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> <1337167648.590.6.camel@lionors.winder.org.uk> <1337240399.15934.106.camel@launcelot.winder.org.uk> Message-ID: On 17/05/12 08:39, Russel Winder wrote: > Interesting, or not, the "Big Data" people are rapidly realizing that > data mining and SQL are mutually incompatible. After many years working with big data mining teams/apps my considered opinion is use SAS or one of its peers! It costs money but it works. And the savings in development time far outweigh the costs. And if you have to manage 100TB or more then the costs of SAS licenses are likely to be the least of your worries! And if you are really serious about it run SAS on top of a Teradata $torage $ystem... Note: I have no commercial connection with either company, just an admirer of their technology solutions. :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Thu May 17 11:35:01 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 May 2012 19:35:01 +1000 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: <1337239627.15934.94.camel@launcelot.winder.org.uk> References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> <1337167648.590.6.camel@lionors.winder.org.uk> <1337239627.15934.94.camel@launcelot.winder.org.uk> Message-ID: <20120517093500.GA11535@ando> On Thu, May 17, 2012 at 08:27:07AM +0100, Russel Winder wrote: > Should we be promoting use of the format method in strings rather than > the % operator? % is deprecated now. It most certainly is not. There are no plans to deprecate the string % operator any time in the foreseeable future. It may, hypothetically, wither away from lack of use (although I doubt it -- so long as there are C programmers, there will be people who like % formatting). If you think it is deprecated, please show me in the official Python documentation where it says so. As far as I am concerned, the final word on deprecation belongs to the creator of Python, and BDFL, Guido van Rossum, who hopes that *at best* the format method will gradually replace % formatting over the next decade or so before the (as yet hypothetical) Python 4: http://mail.python.org/pipermail/python-dev/2009-September/092399.html Rather than repeat myself, I will just point to what I wrote back in January: http://mail.python.org/pipermail/python-list/2012-January/1285894.html -- Steven From adamgold at lavabit.com Thu May 17 12:19:10 2012 From: adamgold at lavabit.com (Adam Gold) Date: Thu, 17 May 2012 11:19:10 +0100 Subject: [Tutor] ssh socks proxy In-Reply-To: References: <9DA9E81C-6897-42BB-A326-B7487B7F5986@lavabit.com> Message-ID: Many thanks Kushal (it's always the silly things one has to look for!). The answer to your question is I don't have shell access to the proxy server, I can only access it for the purpose of setting up a socks proxy. Btw, I'm probably pushing my luck here but any idea what the same script would look like if one used paramiko? On 17 May 2012, at 04:01, kushal.kumaran+python at gmail.com wrote: kushal.kumaran+python at gmail.com wrote: > Adam Gold wrote: > >> I'm trying to write a 'simple' script that will set up a socks proxy >> over ssh and maintain the connection until manually terminated. It's >> not possible to use key-based authentication so a password will need > to >> be supplied. Also, note, the user is presented with a list of servers >> to choose from at the beginning. The actual ssh command is: 'ssh > -vNCD >> 23333 user at host'. >> >> I've been tinkering with both pexpect and paramiko but fear I'm making >> a mountain out of a mole hill. I'm aware both have example scripts > for >> ssh forwarding but, to be honest, they are both too complicated (aka I >> don't know how to customise them). Here is one script I've attempted >> to get working and the associated error listing: >> >> http://pastebin.com/jj8Fgvwm - script >> http://pastebin.com/jRA8zpzi - error >> >> Could anyone help me either correct the script I've started or suggest >> an ockham's-razor-adherent alternative! Many thanks. > > The error message indicates that there hostname HOST could not be > resolved. You need to replace that with the value of the variable HOST. > > COMMAND = "ssh -vNDR 23333 {}@{}".format(USER, HOST) > > I'm curious to know why you can't use keys. They make things much > simpler. Excuse the incorrect ssh command. New mail client tripped me up. -- regards, kushal ____________________________________________________________________________________ Use the link below to report this message as spam. https://lavabit.com/apps/teacher?sig=3087369&key=478586400 ____________________________________________________________________________________ From suryak at live.com Thu May 17 15:28:07 2012 From: suryak at live.com (Surya K) Date: Thu, 17 May 2012 18:58:07 +0530 Subject: [Tutor] How to read blog posts in python Message-ID: Hi, I want to write a python code which read blog's RSS/ Atom feeds and gives us the all post's content of blog... I am currently trying to use FeedParser (Universal Feed Parser). I am able to get all post's titles and URL's but not a content.. I tried to use certain functions mentioned in documentation but couldn't really understand how to do.. Can anyone help me how to do that? (I want to print the "content" exactly the way it has been written. I don't mind about fonts/ styles..) Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu May 17 15:33:07 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 17 May 2012 09:33:07 -0400 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: <1337239627.15934.94.camel@launcelot.winder.org.uk> References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> <1337167648.590.6.camel@lionors.winder.org.uk> <1337239627.15934.94.camel@launcelot.winder.org.uk> Message-ID: <4FB4FE13.4060108@gmail.com> On 5/17/2012 3:27 AM, Russel Winder wrote: > Should we be promoting use of the format method in strings rather than > the % operator? % is deprecated now. I for one do not like seeing % deprecated. Why? It is not broken, and IMHO the easiest to use of all formatting options. -- Bob Gailer 919-636-4239 Chapel Hill NC From Garry.Willgoose at newcastle.edu.au Thu May 17 15:32:55 2012 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Thu, 17 May 2012 23:32:55 +1000 Subject: [Tutor] shutil.rmtree clarification Message-ID: <4FB58AA7020000400005D884@WINDOMPRD00.newcastle.edu.au> I'm trying to remove a directory that has within it a directory tree structure and files and thought the following would work (the online docs seem to suggest it will remove the underlying directory tree and included files) shutil.rmtree('test_directory') but I got back an error (Python 2.7 on OSX) Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/shutil.py", line 253, in rmtree onerror(os.rmdir, path, sys.exc_info()) File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/shutil.py", line 251, in rmtree os.rmdir(path) OSError: [Errno 66] Directory not empty: 'test_directory' which seems to suggest that the directory has to be empty to work ... sort of defeats the purpose of wanting to removing the tree in one command. What do people suggest short of calling os.system('rm -R test_directory'). ------------------------------------------------- Prof Garry Willgoose Australian Professorial Fellow, School of Engineering, The University of Newcastle, Callaghan, NSW, 2308. Australia Phone: +61 2 4921 6050 (Tues-Thurs) +61 2 6545 9574 (Fri-Mon) FAX: +61 2 4921 6991 email: garry.willgoose at newcastle.edu.au g.willgoose at telluricresearch.com --------------------------------------------------- From glenbot at gmail.com Thu May 17 15:53:16 2012 From: glenbot at gmail.com (Glen Zangirolami) Date: Thu, 17 May 2012 08:53:16 -0500 Subject: [Tutor] shutil.rmtree clarification In-Reply-To: <4FB58AA7020000400005D884@WINDOMPRD00.newcastle.edu.au> References: <4FB58AA7020000400005D884@WINDOMPRD00.newcastle.edu.au> Message-ID: Garry, It should be able to remove the tree. I am not able to replicate this on OSX .. yet. What are the contents of the directory and the permissions of the directories/files? Although it should throw an exception if it is a symbolic link or a file it can't remove. On Thu, May 17, 2012 at 8:32 AM, Garry Willgoose < Garry.Willgoose at newcastle.edu.au> wrote: > /Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/shutil.py > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Thu May 17 16:00:29 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 17 May 2012 15:00:29 +0100 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: <20120517093500.GA11535@ando> References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> <1337167648.590.6.camel@lionors.winder.org.uk> <1337239627.15934.94.camel@launcelot.winder.org.uk> <20120517093500.GA11535@ando> Message-ID: On 17/05/2012 10:35, Steven D'Aprano wrote: > On Thu, May 17, 2012 at 08:27:07AM +0100, Russel Winder wrote: > >> Should we be promoting use of the format method in strings rather than >> the % operator? % is deprecated now. > > It most certainly is not. > > There are no plans to deprecate the string % operator any time in the > foreseeable future. It may, hypothetically, wither away from lack of use > (although I doubt it -- so long as there are C programmers, there will > be people who like % formatting). > > If you think it is deprecated, please show me in the official Python > documentation where it says so. > > As far as I am concerned, the final word on deprecation belongs to the > creator of Python, and BDFL, Guido van Rossum, who hopes that *at best* > the format method will gradually replace % formatting over the next > decade or so before the (as yet hypothetical) Python 4: > > http://mail.python.org/pipermail/python-dev/2009-September/092399.html > > Rather than repeat myself, I will just point to what I wrote back in > January: > > http://mail.python.org/pipermail/python-list/2012-January/1285894.html > > > You beat me to it :) -- Cheers. Mark Lawrence. From Garry.Willgoose at newcastle.edu.au Thu May 17 15:32:29 2012 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Thu, 17 May 2012 23:32:29 +1000 Subject: [Tutor] shutil.rmtree clarification Message-ID: <4FB58A8C020000400005D87E@WINDOMPRD00.newcastle.edu.au> I'm trying to remove a directory that has within it a directory tree structure and files and thought the following would work (the online docs seem to suggest it will remove the underlying directory tree and included files) shutil.rmtree('test_directory') but I got back an error (Python 2.7 on OSX) Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/shutil.py", line 253, in rmtree onerror(os.rmdir, path, sys.exc_info()) File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/shutil.py", line 251, in rmtree os.rmdir(path) OSError: [Errno 66] Directory not empty: 'test_directory' which seems to suggest that the directory has to be empty to work ... sort of defeats the purpose of wanting to removing the tree in one command. What do people suggest short of calling os.system('rm -R test_directory'). ------------------------------------------------- Prof Garry Willgoose Australian Professorial Fellow, School of Engineering, The University of Newcastle, Callaghan, NSW, 2308. Australia Phone: +61 2 4921 6050 (Tues-Thurs) +61 2 6545 9574 (Fri-Mon) FAX: +61 2 4921 6991 email: garry.willgoose at newcastle.edu.au g.willgoose at telluricresearch.com --------------------------------------------------- From Garry.Willgoose at newcastle.edu.au Thu May 17 15:32:29 2012 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Thu, 17 May 2012 23:32:29 +1000 Subject: [Tutor] shutil.rmtree clarification Message-ID: <4FB58A8C020000400005D881@WINDOMPRD00.newcastle.edu.au> I'm trying to remove a directory that has within it a directory tree structure and files and thought the following would work (the online docs seem to suggest it will remove the underlying directory tree and included files) shutil.rmtree('test_directory') but I got back an error (Python 2.7 on OSX) Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/shutil.py", line 253, in rmtree onerror(os.rmdir, path, sys.exc_info()) File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/shutil.py", line 251, in rmtree os.rmdir(path) OSError: [Errno 66] Directory not empty: 'test_directory' which seems to suggest that the directory has to be empty to work ... sort of defeats the purpose of wanting to removing the tree in one command. What do people suggest short of calling os.system('rm -R test_directory'). ------------------------------------------------- Prof Garry Willgoose Australian Professorial Fellow, School of Engineering, The University of Newcastle, Callaghan, NSW, 2308. Australia Phone: +61 2 4921 6050 (Tues-Thurs) +61 2 6545 9574 (Fri-Mon) FAX: +61 2 4921 6991 email: garry.willgoose at newcastle.edu.au g.willgoose at telluricresearch.com --------------------------------------------------- From brad.hudson at gmail.com Fri May 18 01:02:35 2012 From: brad.hudson at gmail.com (Brad Hudson) Date: Thu, 17 May 2012 18:02:35 -0500 Subject: [Tutor] How to create self contained Windows executables (.exe files) from python scripts Message-ID: Can someone point me to information on how to create Windows .exe files from python 2.7.3? The py2exe method (www.py2exe.org) appears to only be available for python 2.6 from the sites I've seen. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From brian.van.den.broek at gmail.com Fri May 18 01:05:26 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Fri, 18 May 2012 01:05:26 +0200 Subject: [Tutor] How to read blog posts in python In-Reply-To: References: Message-ID: On 17 May 2012 16:31, "Surya K" wrote: > > Hi, > > I want to write a python code which read blog's RSS/ Atom feeds and gives us the all post's content of blog... > > I am currently trying to use FeedParser (Universal Feed Parser). I am able to get all post's titles and URL's but not a content.. > > I tried to use certain functions mentioned in documentation but couldn't really understand how to do.. > > Can anyone help me how to do that? (I Hi, You are much more likely to get help if you include the code you tried. It's fine to say "what I have isn't working; I've pasted it at the end of this message" or the like. Also, with evidence of your attempt, those who know UFP (not me, I am afraid), will be better able to aim their efforts to help at your level. Best, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri May 18 01:27:39 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 May 2012 00:27:39 +0100 Subject: [Tutor] How to create self contained Windows executables (.exe files) from python scripts In-Reply-To: References: Message-ID: On 18/05/12 00:02, Brad Hudson wrote: > Can someone point me to information on how to create Windows .exe files > from python 2.7.3? The py2exe method (www.py2exe.org > ) appears to only be available for python 2.6 > from the sites I've seen. You can try PyInstaller: http://www.pyinstaller.org/ It claims to work on 2.7. Rumour has it that its slightly more complex to use than py2exe but I can't vouch for that since I've never found a need to create exe files... There are several other such tools too, Google will find them for you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From emekamicro at gmail.com Fri May 18 07:22:18 2012 From: emekamicro at gmail.com (Emeka) Date: Fri, 18 May 2012 07:22:18 +0200 Subject: [Tutor] Installing graphics module on python 2.7 Message-ID: Hello All, I would like to install graphics. So that I can do this: import graphics Please help me. I tried "pip install graphics" nothing came out of it. Regards, \Janus -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremy.traurig at gmail.com Fri May 18 08:45:51 2012 From: jeremy.traurig at gmail.com (Jeremy Traurig) Date: Thu, 17 May 2012 23:45:51 -0700 Subject: [Tutor] New to Python Message-ID: Hello, I very new to python and have been playing around with some simple code that I would eventually use in the real word. Below is the code I have created. I want the code to read data from a file called SIL633.txt and then output that data into another file called test.txt. below is my code: #! /usr/bin/env python # Read NRG Text File def readNRGtxt(): import numpy as np f1 = open('SIL633_original.txt','r') data = np.genfromtxt(f1,delimiter='\t',skip_header=141) f1.close f2 = open('test.txt','w') np.savetxt(f2,data,fmt='%6.2f',delimiter='\t') f2.close I'm running this on mac 10.5.8. When I run this script from the command line, there is no file output. However, if I remove the "def" statement in the script and run again from the command line, a test.txt file is output. I guess I'm trying to understand why using the def statement changes how the script operates and since it does, how do I correct this code so it runs from the command line with the def statement. thanks for any help -- jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri May 18 09:03:35 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 May 2012 17:03:35 +1000 Subject: [Tutor] Installing graphics module on python 2.7 In-Reply-To: References: Message-ID: <4FB5F447.60808@pearwood.info> Emeka wrote: > Hello All, > > I would like to install graphics. > So that I can do this: > import graphics > > Please help me. I tried "pip install graphics" nothing came out of it. Is this for the John Zelle book "Python Programming: An Introduction to Computer Science"? If so, did you follow the instructions in the book? Did you try googling for "import graphics python"? https://duckduckgo.com/html/?q=python%20import%20graphics It comes up with plenty of information about the graphics module from Zelle's book. Since it is not a standard Python module, you have to install it from Zelle's website. If you mean some other "graphics" module, you will have to explain in more detail what it is and where you expect to find it. -- Steven From steve at pearwood.info Fri May 18 09:10:29 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 May 2012 17:10:29 +1000 Subject: [Tutor] New to Python In-Reply-To: References: Message-ID: <4FB5F5E5.40506@pearwood.info> Hi Jeremy, Welcome to Python, but please don't send HTML email (what some programs wrongly call "Rich Text"), as it completely destroys the necessary indentation of your Python code and makes it difficult or impossible to work out what your code is supposed to be. However, I will take a wild guess as to what your problem is. You wrote: > I'm running this on mac 10.5.8. When I run this script from the command > line, there is no file output. However, if I remove the "def" statement in > the script and run again from the command line, a test.txt file is output. > I guess I'm trying to understand why using the def statement changes how > the script operates and since it does, how do I correct this code so it > runs from the command line with the def statement. The "def" statement defines a function. The function doesn't run until you call it. For example: # Define a function. def test(): print("Hello world") # Nothing gets printed here, since the function is only defined, # but not yet called. # Now actually call it. test() # Take note that you need the round brackets () to call it. "Hello world" will be printed. Does that help? -- Steven From dineshbvadhia at hotmail.com Fri May 18 11:34:26 2012 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 18 May 2012 02:34:26 -0700 Subject: [Tutor] Python sqlite with implicit cursor open and close Message-ID: In the Python documentation (http://docs.python.org/library/sqlite3.html?highlight=sqlite#using-shortcut-methods) it says: "Using the nonstandard execute(), executemany() and executescript() methods of the Connection object, your code can be written more concisely because you don't have to create the (often superfluous) Cursor objects explicitly. Instead, the Cursor objects are created implicitly and these shortcut methods return the cursor objects. This way, you can execute a SELECT statement and iterate over it directly using only a single call on the Connection object." Here is pseudo-code: db = sqlite.connect(path, ...) cursor = db.cursor() # normal method def doDBStuff(): cursor = db.cursor() cursor.execute(somestatement) or cursor.executemany(somestatement) or cursor.executescript(somestatement) cursor.close() return # suggested method def doDbStuffCorrectly(): cursor.execute(somestatement) or cursor.executemany(somestatement) or cursor.executescript(somestatement) return Does the implicit method close the cursor? This would be important in a multi-user environment with read/write access. -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Fri May 18 12:53:15 2012 From: timomlists at gmail.com (Timo) Date: Fri, 18 May 2012 12:53:15 +0200 Subject: [Tutor] How to create self contained Windows executables (.exe files) from python scripts In-Reply-To: References: Message-ID: <4FB62A1B.60507@gmail.com> Op 18-05-12 01:02, Brad Hudson schreef: > Can someone point me to information on how to create Windows .exe > files from python 2.7.3? The py2exe method (www.py2exe.org > ) appears to only be available for python 2.6 > from the sites I've seen. I distribute a PyGTK application that is written in Python 2.7 and compiled with Py2exe, so it's possible. When looking at the downloads, there are -py2.7 versions available: http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/ Timo > > Thanks in advance. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From russel at winder.org.uk Fri May 18 12:54:55 2012 From: russel at winder.org.uk (Russel Winder) Date: Fri, 18 May 2012 11:54:55 +0100 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: <20120517093500.GA11535@ando> References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> <1337167648.590.6.camel@lionors.winder.org.uk> <1337239627.15934.94.camel@launcelot.winder.org.uk> <20120517093500.GA11535@ando> Message-ID: <1337338495.15934.212.camel@launcelot.winder.org.uk> On Thu, 2012-05-17 at 19:35 +1000, Steven D'Aprano wrote: > On Thu, May 17, 2012 at 08:27:07AM +0100, Russel Winder wrote: > > > Should we be promoting use of the format method in strings rather than > > the % operator? % is deprecated now. > > It most certainly is not. > > There are no plans to deprecate the string % operator any time in the > foreseeable future. It may, hypothetically, wither away from lack of use OK I am clearly wrong with the statement I made. I had assumed the statement (*) that it would be deprecated in 3.1 was carried through, I had not actually checked the reality in the 3.1 and 3.2 differences documents. My apologies for misdirection, thanks for pulling me up on this. (*) There is no statement of when deprecation would happen in PEP 3101 itself http://www.python.org/dev/peps/pep-3101/ but there is an explicit statement in http://docs.python.org/release/3.0/whatsnew/3.0.html#pep-3101-a-new-approach-to-string-formatting which clearly didn't happen even though it led to a lot of people thinking it would. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From joel.goldstick at gmail.com Fri May 18 14:40:43 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 18 May 2012 08:40:43 -0400 Subject: [Tutor] Python sqlite with implicit cursor open and close In-Reply-To: References: Message-ID: On Fri, May 18, 2012 at 5:34 AM, Dinesh B Vadhia wrote: > In the Python documentation > (http://docs.python.org/library/sqlite3.html?highlight=sqlite#using-shortcut-methods) > it says: > "Using the nonstandard execute(), executemany() and executescript() methods > of the Connection object, your code can be written more concisely because > you don?t have to create the (often superfluous) Cursor objects explicitly. > Instead, the Cursor objects are created implicitly and these shortcut > methods return the cursor objects. This way, you can execute a SELECT > statement and iterate over it directly using only a single call on the > Connection object." > Here is pseudo-code: > > db = sqlite.connect(path, ...) > cursor = db.cursor() > > # normal method > def doDBStuff(): > ????cursor = db.cursor() > ????cursor.execute(somestatement) or cursor.executemany(somestatement) or > cursor.executescript(somestatement) > ????cursor.close() > ????return > > # suggested method > def doDbStuffCorrectly(): > ????cursor.execute(somestatement) or cursor.executemany(somestatement) or > cursor.executescript(somestatement) > ????return > I think you meant to use conn instead of cursor here? > Does the implicit method close the cursor?? This would be important in a > multi-user environment with read/write access. The document says that these methods return a cursor If you close the connection I would assume that the cursor would be closed, since it is a method of the connection object. But what does it actually mean to close the cursor? In a muti-user environment each user would have a different conn object and a different cursor. > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick From s.charonis at gmail.com Fri May 18 20:23:23 2012 From: s.charonis at gmail.com (Spyros Charonis) Date: Fri, 18 May 2012 19:23:23 +0100 Subject: [Tutor] Parsing data from a set of files iteratively Message-ID: Dear Python community, I have a set of ~500 files which I would like to run a script on. My script extracts certain information and generates several lists with items I need. For one of these lists, I need to combine the information from all 500 files into one super-list. Is there a way in which I can iteratively execute my script over all 500 files and get them to write the list I need into a new file? Many thanks in advance for your time. Spyros -------------- next part -------------- An HTML attachment was scrubbed... URL: From tvssarma.omega9 at gmail.com Fri May 18 20:27:41 2012 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Fri, 18 May 2012 23:57:41 +0530 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: References: Message-ID: On 18 May 2012 23:53, Spyros Charonis wrote: > Dear Python community, > > I have a set of ~500 files which I would like to run a script on. My > script extracts certain information and > generates several lists with items I need. For one of these lists, I need > to combine the information from all > 500 files into one super-list. Is there a way in which I can iteratively > execute my script over all 500 files > and get them to write the list I need into a new file? Many thanks in > advance for your time. > > Spyros > Hi Spyros, Did you try writing some code to achieve this? -- An monkey typed up this email. Please excuse him if he made a stupid error! -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri May 18 20:31:26 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 18 May 2012 14:31:26 -0400 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: References: Message-ID: On Fri, May 18, 2012 at 2:23 PM, Spyros Charonis wrote: > Dear Python community, > > I have a set of ~500 files which I would like to run a script on. My script > extracts certain information and > generates several lists with items I need. For one of these lists, I need to > combine the information from all > 500 files into one super-list. Is there a way in which I can iteratively > execute my script over all 500 files > and get them to write the list I need into a new file? Many thanks in > advance for your time. > > Spyros > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Yes, of course. Python comes with the os module. You should google 'iterating over files in a folder in python to learn a bit about it. Also, its best if you ask specific questions. Paste your present code into your email and tell us what works or what doesn't. -- Joel Goldstick From ramit.prasad at jpmorgan.com Fri May 18 20:33:05 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 18 May 2012 18:33:05 +0000 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474093347AA@SCACMX008.exchad.jpmchase.net> >I have a set of ~500 files which I would like to run a script on. My script extracts certain information and >generates several lists with items I need. For one of these lists, I need to combine the information from all >500 files into one super-list. Is there a way in which I can iteratively execute my script over all 500 files >and get them to write the list I need into a new file? Many thanks in advance for your time. Yes, it is possible. Have you made an attempt? Do you have some working or non-working code? The Python tutorials will help as will the online documentation How to get a list of files: http://docs.python.org/library/glob.html How to read/write a file: http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files Hopefully that will give you a start. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Fri May 18 20:57:40 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 May 2012 19:57:40 +0100 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: References: Message-ID: On 18/05/12 19:23, Spyros Charonis wrote: > Dear Python community, > > I have a set of ~500 files which I would like to run a script on. > ...Is there a way in which I can iteratively execute my script > over all 500 files Yes. You could use os.walk() or the glob module depending on whether the files are in a folder heirarchy or a single folder. That will give you access to each file. Put your functionality into a function taking a single file as input and a list to which you append the new data. Call that function for each file in turn. Try that and if you get stuck come back with a more specific question, the code you used and the full error text. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From learnpythonvs at gmail.com Sat May 19 00:45:48 2012 From: learnpythonvs at gmail.com (Vignesh Sathiamoorthy) Date: Fri, 18 May 2012 15:45:48 -0700 Subject: [Tutor] New to Python In-Reply-To: References: Message-ID: Hi Jeremy, I am new to Python too. I find docs.python.org very helpful. *Understanding functions:* http://docs.python.org/tutorial/controlflow.html#defining-functions *Reading and Writing Files:* http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files *File Objects:* http://docs.python.org/library/stdtypes.html#file-objects *Comments - Coding Style* http://www.python.org/dev/peps/pep-0008/#comments Hope the above links are useful. Thanks, Vignesh On Thu, May 17, 2012 at 11:45 PM, Jeremy Traurig wrote: > Hello, > > I very new to python and have been playing around with some simple code > that I would eventually use in the real word. Below is the code I have > created. I want the code to read data from a file called SIL633.txt and > then output that data into another file called test.txt. below is my code: > > #! /usr/bin/env python > # Read NRG Text File > def readNRGtxt(): > import numpy as np > f1 = open('SIL633_original.txt','r') > data = np.genfromtxt(f1,delimiter='\t',skip_header=141) > f1.close > f2 = open('test.txt','w') > np.savetxt(f2,data,fmt='%6.2f',delimiter='\t') > f2.close > > I'm running this on mac 10.5.8. When I run this script from the command > line, there is no file output. However, if I remove the "def" statement in > the script and run again from the command line, a test.txt file is output. > I guess I'm trying to understand why using the def statement changes how > the script operates and since it does, how do I correct this code so it > runs from the command line with the def statement. > > thanks for any help -- jeremy > > _______________________________________________ > 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 Sat May 19 04:35:44 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 19 May 2012 12:35:44 +1000 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: References: Message-ID: <4FB70700.4010703@pearwood.info> Spyros Charonis wrote: > Dear Python community, > > I have a set of ~500 files which I would like to run a script on. My script > extracts certain information and > generates several lists with items I need. For one of these lists, I need > to combine the information from all > 500 files into one super-list. Is there a way in which I can iteratively > execute my script over all 500 files > and get them to write the list I need into a new file? Many thanks in > advance for your time. Naturally; one way is to explicitly iterate over the names of the files: for filename in ('a.txt', 'b.txt', 'c.txt'): # and 497 more... do something with filename... Of course, writing 500 file names in your script is probably going to be quite painful. What you can do is list the file names in an external file, one per line, then use that: names = open('list of names.txt').readlines() for filename in [name.strip() for name in names]: ... Note the use of a list comprehension (the bit inside the square brackets) to strip away whitespace from the names, including the newline that occurs after every line. Another approach is to make sure all the files are in a single directory, then walk the directory: import os for filename in os.listdir('where the files are'): ... If the files are in subdirectories, you can use the os.walk() function. See the documentation for details of how to use it: http://docs.python.org/library/os.html#os.listdir http://docs.python.org/library/os.html#os.walk (Aside: if you think os.walk is complicated, you should try using its predecessor, os.path.walk!) A fourth approach is to use the fileinput module, which takes a list of files, then treats them all as one giant file. Beware though, fileinput is not very efficient and may struggle a little with 500 files. http://docs.python.org/library/fileinput.html -- Steven From steve at pearwood.info Sat May 19 04:41:27 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 19 May 2012 12:41:27 +1000 Subject: [Tutor] shutil.rmtree clarification In-Reply-To: <4FB58AA7020000400005D884@WINDOMPRD00.newcastle.edu.au> References: <4FB58AA7020000400005D884@WINDOMPRD00.newcastle.edu.au> Message-ID: <4FB70857.5010506@pearwood.info> Garry Willgoose wrote: > I'm trying to remove a directory that has within it a directory tree structure and files and thought the following would work (the online docs seem to suggest it will remove the underlying directory tree and included files) > > shutil.rmtree('test_directory') > > but I got back an error (Python 2.7 on OSX) > > > Traceback (most recent call last): > File "", line 1, in > File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/shutil.py", line 253, in rmtree > onerror(os.rmdir, path, sys.exc_info()) > File "/Library/Frameworks/Python.framework/Versions/7.0/lib/python2.7/shutil.py", line 251, in rmtree > os.rmdir(path) > OSError: [Errno 66] Directory not empty: 'test_directory' > > > which seems to suggest that the directory has to be empty to work ... sort of defeats the purpose of wanting to removing the tree in one command. What do people suggest short of calling os.system('rm -R test_directory'). No, the directory doesn't have to be empty. It's hard to say what's wrong, but my guess would be that there's a file in test_directory that you don't have permission to remove. -- Steven From s.charonis at gmail.com Sat May 19 13:42:36 2012 From: s.charonis at gmail.com (Spyros Charonis) Date: Sat, 19 May 2012 12:42:36 +0100 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: References: Message-ID: I have tried the following two snippets which both results in the same error import os, glob os.chdir('users/spyros/desktop/3NY8MODELSHUMAN/') homology_models = glob.glob('*.pdb') for i in range(len(homology_models)): python serialize_PIPELINE_models.py homology_models[i] import os, sys path = "/users/spyros/desktop/3NY8MODELSHUMAN/ dirs = os.listdir(path) for file in dirs: python serialize_PIPELINE_models.py The error, respectively for each snipped, read: File "", line 2 python serialize_PIPELINE_models.py homology_models[i] ^ SyntaxError: invalid syntax File "", line 2 python serialize_PIPELINE_models.py ^ SyntaxError: invalid syntax In the first snippet, the final line reads: 'python' (calling the interpreter) 'serialize_PIPELINE_models.py' (calling my python program) 'homology_models[i]' (the file to run it on) the glob.glob routine returns a list of files, so maybe python does not allow the syntax "python (call interpreter)" "list entry" ? Many thanks. Spyros On Fri, May 18, 2012 at 7:57 PM, Alan Gauld wrote: > On 18/05/12 19:23, Spyros Charonis wrote: > >> Dear Python community, >> >> I have a set of ~500 files which I would like to run a script on. >> > > ...Is there a way in which I can iteratively execute my script > > over all 500 files > > Yes. > You could use os.walk() or the glob module depending on whether > the files are in a folder heirarchy or a single folder. > > That will give you access to each file. > Put your functionality into a function taking a single file > as input and a list to which you append the new data. > Call that function for each file in turn. > > Try that and if you get stuck come back with a more specific question, the > code you used and the full error text. > > -- > Alan G > 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 May 19 14:36:58 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 May 2012 13:36:58 +0100 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: References: Message-ID: On 19/05/12 12:42, Spyros Charonis wrote: > I have tried the following two snippets which both results in the same > error > > import os, glob > os.chdir('users/spyros/desktop/3NY8MODELSHUMAN/') > homology_models = glob.glob('*.pdb') > for i in range(len(homology_models)): > python serialize_PIPELINE_models.py homology_models[i] OK, now we see the problem. You are trying to invoke the interpreter from within the interpreter. You don't do that. Instead you need to call the functions defined inside serialize_PIPELINE_models.py from your script. To do that you will need to import serialize_PIPELINE_models.py using import serialize_PIPELINE_models or, since its a long name: import serialize_PIPELINE_models as spm Than you can access the code functions inside using spm.serialise(filename) Or whatever the functions inside serialize_PIPELINE_models.py are. Another thing which makes life easier is to use the for loop differently. Instead of: > homology_models = glob.glob('*.pdb') > for i in range(len(homology_models)): Just use: for fn in glob.glob('*.pdb'): spm.serialise(fn) But you will first need to ensure that the code inside serialize_PIPELINE_models.py is available to use as functions. The other option of course is to miss out Python at this level and write a bash script to call Python. It would look something like: #!/bin/bash ########################### cd users/spyros/desktop/3NY8MODELSHUMAN/ for file in *.pdb do python serialize_PIPELINE_models.py $file done ############################ Which might be the simplest thing if the serialize_PIPELINE_models.py already works as you require. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From benjaming286 at gmail.com Sat May 19 19:46:42 2012 From: benjaming286 at gmail.com (Benjamin G) Date: Sat, 19 May 2012 13:46:42 -0400 Subject: [Tutor] Translating R Code to Python-- reading in csv files, writing out to csv files Message-ID: I'm trying to improve my python by translating R code that I wrote into Python. I've been reading about the python csv module and realized it was best to get some expert input to clarify some confusion on my part. As background, GSEXXXXX_full_pdata.csv has different patient information (such as unique patient ID's, whether the tissue used was tumor or normal, and other things. I'll just use the first two characteristics for now). Template.csv is a template we built that allows us to take different datasets and standardize them for meta-analysis. So for example, "curated$alt_sample_name" refers to the unique patient ID, and "curated$sample_type" refers to the type of tissue used. Here is sample code in R. uncurated <- read.csv("../uncurated/GSEXXXXX_full_pdata.csv",as.is =TRUE,row.names=1) ##initial creation of curated dataframe curated <- initialCuratedDF(rownames(uncurated),template.filename="template.csv") ##-------------------- ##start the mappings ##-------------------- ##title -> alt_sample_name tmp <- uncurated$title curated$alt_sample_name <- tmp ##sample_type are all tumor curated$sample_type <- "tumor" _________________________________________________________________ In Python, I have figured out how to assign "uncurated" and "curated" to the correct paths. *My trouble arose when trying to execute the following R code:* ##title -> alt_sample_name tmp <- uncurated$title curated$alt_sample_name <- tmp *All I am trying to do is take in a specific column in "uncurated" and write that whole column as output to "curated." It should be a pretty basic command, I'm just not clear on how to execute it.* Thanks, benjamin -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Sat May 19 19:58:57 2012 From: eire1130 at gmail.com (eire1130 at gmail.com) Date: Sat, 19 May 2012 17:58:57 +0000 Subject: [Tutor] Translating R Code to Python-- reading in csv files, writing out to csv files In-Reply-To: References: Message-ID: <1318229924-1337450331-cardhu_decombobulator_blackberry.rim.net-1190924810-@b11.c28.bise6.blackberry> I confese I haven't read your entire email, but have you looked at pyR? I believe it is a wrapper for python, giiving you access to r. Sent from my Verizon Wireless BlackBerry -----Original Message----- From: Benjamin G Sender: tutor-bounces+eire1130=gmail.com at python.org Date: Sat, 19 May 2012 13:46:42 To: Subject: [Tutor] Translating R Code to Python-- reading in csv files, writing out to csv files _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From joel.goldstick at gmail.com Sat May 19 20:18:43 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 19 May 2012 14:18:43 -0400 Subject: [Tutor] Translating R Code to Python-- reading in csv files, writing out to csv files In-Reply-To: <1318229924-1337450331-cardhu_decombobulator_blackberry.rim.net-1190924810-@b11.c28.bise6.blackberry> References: <1318229924-1337450331-cardhu_decombobulator_blackberry.rim.net-1190924810-@b11.c28.bise6.blackberry> Message-ID: On Sat, May 19, 2012 at 1:58 PM, wrote: > I confese I haven't read your entire email, but have you looked at pyR? I believe it is a wrapper for python, giiving you access to r. > > > Sent from my Verizon Wireless BlackBerry > > -----Original Message----- > From: Benjamin G > Sender: tutor-bounces+eire1130=gmail.com at python.org > Date: Sat, 19 May 2012 13:46:42 > To: > Subject: [Tutor] Translating R Code to Python-- reading in csv files, > ?writing out to csv files > > _______________________________________________ > 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 I am not sure I understand what you want to do. Could you show a few lines of your input data and then show how you want it to look once it is processed? The csv module is pretty easy to get going. If your goal is to learn python I would check the documentation or find a csv tutorial http://docs.python.org/library/csv.html The reader will either write to python list or dict. If you use the list, you access each item with my_list[n] where n is the position (starting with 0). If you need to change the data, you can do that to the list items. If you need to output in a different order, or just some fields try this: in_date: [1, 2, 3] --> out_data [2,1,3] would code like this: out_data[] out_data.append[1] out_data.append[0] out_data.append[2] Then use the csv writer to write out_data to your file I don't know R, but most python people will tell you its best to learn the 'python way', and not try to 'translate' from another language. -- Joel Goldstick From benjaming286 at gmail.com Sat May 19 23:07:04 2012 From: benjaming286 at gmail.com (Benjamin G) Date: Sat, 19 May 2012 17:07:04 -0400 Subject: [Tutor] Translating R Code to Python-- reading in csv files, writing out to csv files In-Reply-To: References: <1318229924-1337450331-cardhu_decombobulator_blackberry.rim.net-1190924810-@b11.c28.bise6.blackberry> Message-ID: Thanks, Joel. Here is a simple example of the input data (top row is column headers in the input file) Patient ID Sample Type Survival Time(months) unique_patient_ID1 Tumor 12 unique_patient_ID2 Normal 5 unique_patient_ID3 Normal 60 unique_patient_ID4 Tumor 2 unique_patient_ID5 Tumor 13 Since we are handling many different input files, we standardized the column names and values. For example, we want the output file to have the following column headers instead of the three above: alt_sample_name, sample_type and days_to_death The output file should look like this: alt_sampleName sample_type days_to_death 1 tumor 360 2 normal 150 3 normal 1800 4 tumor 60 5 tumor 390 Thanks again, Benjamin On Sat, May 19, 2012 at 2:18 PM, Joel Goldstick wrote: > On Sat, May 19, 2012 at 1:58 PM, wrote: > > I confese I haven't read your entire email, but have you looked at pyR? > I believe it is a wrapper for python, giiving you access to r. > > > > > > Sent from my Verizon Wireless BlackBerry > > > > -----Original Message----- > > From: Benjamin G > > Sender: tutor-bounces+eire1130=gmail.com at python.org > > Date: Sat, 19 May 2012 13:46:42 > > To: > > Subject: [Tutor] Translating R Code to Python-- reading in csv files, > > writing out to csv files > > > > _______________________________________________ > > 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 > > I am not sure I understand what you want to do. Could you show a few > lines of your input data and then show how you want it to look once it > is processed? The csv module is pretty easy to get going. > > If your goal is to learn python I would check the documentation or > find a csv tutorial http://docs.python.org/library/csv.html > > The reader will either write to python list or dict. If you use the > list, you access each item with my_list[n] where n is the position > (starting with 0). If you need to change the data, you can do that to > the list items. If you need to output in a different order, or just > some fields try this: > > in_date: [1, 2, 3] --> out_data [2,1,3] would code like this: > out_data[] > out_data.append[1] > out_data.append[0] > out_data.append[2] > > Then use the csv writer to write out_data to your file > > I don't know R, but most python people will tell you its best to learn > the 'python way', and not try to 'translate' from another language. > > -- > Joel Goldstick > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at linux-ip.net Sat May 19 23:32:39 2012 From: martin at linux-ip.net (Martin A. Brown) Date: Sat, 19 May 2012 17:32:39 -0400 Subject: [Tutor] Translating R Code to Python-- reading in csv files, writing out to csv files In-Reply-To: References: Message-ID: Greetings Benjamin, To begin: I do not know R. : I'm trying to improve my python by translating R code that I : wrote into Python. : : *All I am trying to do is take in a specific column in : "uncurated" and write that whole column as output to "curated." : It should be a pretty basic command, I'm just not clear on how to : execute it.* The hardest part about translation is learning how to think in a different language. If you know any other human languages, you probably know that you can say things in some languages that do not translate particularly well (other than circumlocution) into another language. Why am I starting with this? I am starting here because you seem quite comfortable with thinking and operating in R, but you don't seem as comfortable yet with thinking and operating in Python. Naturally, that's why you are asking the Tutor list about this, so welcome to the right place! Let's see if we can get you some help. : As background, GSEXXXXX_full_pdata.csv has different patient : information (such as unique patient ID's, whether the tissue used : was tumor or normal, and other things. I'll just use the first : two characteristics for now). Template.csv is a template we built : that allows us to take different datasets and standardize them : for meta-analysis. So for example, "curated$alt_sample_name" : refers to the unique patient ID, and "curated$sample_type" refers : to the type of tissue used. I have fabricated some data after your description that looks like this: patientID,title,sample_type V6IF0OqVu,0.5788,70 GXj51ljB2,0.3449,88 You, doubtless have more columns and the data here are probably nothing like yours, but consider it useful for illustrative purposes only. (Illustrating porpoises! How did they get here? Next thing you know we will have illuminating egrets and animating dromedaries!) : I've been reading about the python csv module and realized it was : best to get some expert input to clarify some confusion on my : part. The csv module is very useful and quite powerful for reading data in different ways and iterating over data sets. Supposing you know the index of the column of interest to you...well this is quite trivial: import csv def main(f,field): for row in csv.reader(f): print row[0],row[field] # -- lists/tuples are zero-based [0,1,2], so 2 is the third column # # main(open('GSEXXXXX_full_pdata.csv'),2) OK, but if your data files have different numbers of or ordering of columns, then this can become a bit fragile. So maybe you would want to learn how to use the csv.DictReader, which will give you the same thing but uses the first (header) line to name the columns, so then you could do something more like this: import csv def main(f,id,field): for row in csv.DictReader(f): print row[id],row[field] main(open('GSEXXXXX_full_pdata.csv'),'patientID','sample_type') Would you like more detail on this? Well, have a look at this nice little summary: http://www.doughellmann.com/PyMOTW/csv/ Now, that really is just giving you a glimpse of the csv module. This is not really your question. Your question was more along the lines of 'How do I, in Python, accomplish this task that is quite simple in R?' You may find that list-comprehensions, generators and iterators are all helpful in mangling the data according to your nefarious will once you have used the csv module to load the data into a data structure. In point of fact, though, Python does not have this particular feature that you are seek...not in the core libraries, however. The lack of this capability has bothered a few people over the years, so there are a few different types of solutions. You have already heard a reference to RPy (about which I know nothing): http://rpy.sourceforge.net/ There are, however, a few other tools that you may find quite useful. One chap wanted access to some features of R that he used all the time along with many of the other convenient features of Python, so he decided to implement dataframes (an R concept?) in Python. This idea was present at the genesis of the pandas library. http://pandas.pydata.org/ So, how would you do this with pandas? Well, you could: import pandas def main(f,field): uncurated = pandas.read_csv(f) curated = uncurated[field] print curated main(open('GSEXXXXX_full_pdata.csv'),'sample_type') Note that pandas is geared to allow you to access your data by the 'handles', the unique identifier for the row and the column name. This will produce a tabular output of just the single column you want. You may find that pandas affords you access to tools with which you are already intellectually familiar. Good luck, -Martin P.S. While I was writing this, you sent in some sample data that looked tab-separated (well, anyway, not comma-separated). The csv and pandas libraries allow for delimiter='\t' options to most object constructor calls. So, you could do: csv.reader(f,delimiter='\t') -- Martin A. Brown http://linux-ip.net/ From benjaming286 at gmail.com Sun May 20 04:28:58 2012 From: benjaming286 at gmail.com (Benjamin G) Date: Sat, 19 May 2012 22:28:58 -0400 Subject: [Tutor] Translating R Code to Python-- reading in csv files, writing out to csv files In-Reply-To: References: Message-ID: Thanks Martin-- this is really great. My major question now is that I need to transition to Python for a project and I need to learn how to think in Python instead of in R. The two strategies I have used so far are: a) going through the description and exercises in http://www.openbookproject.net/thinkcs/python/english2e/ and b) trying to convert my R code into Python. On a high-level, do you have any other suggestions for how I could go about becoming more proficient in Python? Thanks again to you and everyone else who responded. I am really very much obliged. Benjamin On Sat, May 19, 2012 at 5:32 PM, Martin A. Brown wrote: > > Greetings Benjamin, > > To begin: I do not know R. > > : I'm trying to improve my python by translating R code that I > : wrote into Python. > : > : *All I am trying to do is take in a specific column in > : "uncurated" and write that whole column as output to "curated." > : It should be a pretty basic command, I'm just not clear on how to > : execute it.* > > The hardest part about translation is learning how to think in a > different language. If you know any other human languages, you > probably know that you can say things in some languages that do not > translate particularly well (other than circumlocution) into another > language. Why am I starting with this? I am starting here because > you seem quite comfortable with thinking and operating in R, but you > don't seem as comfortable yet with thinking and operating in Python. > > Naturally, that's why you are asking the Tutor list about this, so > welcome to the right place! Let's see if we can get you some help. > > : As background, GSEXXXXX_full_pdata.csv has different patient > : information (such as unique patient ID's, whether the tissue used > : was tumor or normal, and other things. I'll just use the first > : two characteristics for now). Template.csv is a template we built > : that allows us to take different datasets and standardize them > : for meta-analysis. So for example, "curated$alt_sample_name" > : refers to the unique patient ID, and "curated$sample_type" refers > : to the type of tissue used. > > I have fabricated some data after your description that looks like > this: > > patientID,title,sample_type > V6IF0OqVu,0.5788,70 > GXj51ljB2,0.3449,88 > > You, doubtless have more columns and the data here are probably > nothing like yours, but consider it useful for illustrative purposes > only. (Illustrating porpoises! How did they get here? Next thing > you know we will have illuminating egrets and animating > dromedaries!) > > : I've been reading about the python csv module and realized it was > : best to get some expert input to clarify some confusion on my > : part. > > The csv module is very useful and quite powerful for reading data in > different ways and iterating over data sets. Supposing you know the > index of the column of interest to you...well this is quite trivial: > > import csv > def main(f,field): > for row in csv.reader(f): > print row[0],row[field] > > # -- lists/tuples are zero-based [0,1,2], so 2 is the third column > # > # > main(open('GSEXXXXX_full_pdata.csv'),2) > > OK, but if your data files have different numbers of or ordering of > columns, then this can become a bit fragile. So maybe you would > want to learn how to use the csv.DictReader, which will give you the > same thing but uses the first (header) line to name the columns, so > then you could do something more like this: > > import csv > def main(f,id,field): > for row in csv.DictReader(f): > print row[id],row[field] > > main(open('GSEXXXXX_full_pdata.csv'),'patientID','sample_type') > > Would you like more detail on this? Well, have a look at this nice > little summary: > > http://www.doughellmann.com/PyMOTW/csv/ > > Now, that really is just giving you a glimpse of the csv module. > This is not really your question. Your question was more along the > lines of 'How do I, in Python, accomplish this task that is quite > simple in R?' > > You may find that list-comprehensions, generators and iterators are > all helpful in mangling the data according to your nefarious will > once you have used the csv module to load the data into a data > structure. > > In point of fact, though, Python does not have this particular > feature that you are seek...not in the core libraries, however. > > The lack of this capability has bothered a few people over the > years, so there are a few different types of solutions. You have > already heard a reference to RPy (about which I know nothing): > > http://rpy.sourceforge.net/ > > There are, however, a few other tools that you may find quite > useful. One chap wanted access to some features of R that he used > all the time along with many of the other convenient features of > Python, so he decided to implement dataframes (an R concept?) in > Python. This idea was present at the genesis of the pandas library. > > http://pandas.pydata.org/ > > So, how would you do this with pandas? Well, you could: > > import pandas > def main(f,field): > uncurated = pandas.read_csv(f) > curated = uncurated[field] > print curated > > main(open('GSEXXXXX_full_pdata.csv'),'sample_type') > > Note that pandas is geared to allow you to access your data by the > 'handles', the unique identifier for the row and the column name. > This will produce a tabular output of just the single column you > want. You may find that pandas affords you access to tools with > which you are already intellectually familiar. > > Good luck, > > -Martin > > P.S. While I was writing this, you sent in some sample data that > looked tab-separated (well, anyway, not comma-separated). The > csv and pandas libraries allow for delimiter='\t' options to > most object constructor calls. So, you could do: > csv.reader(f,delimiter='\t') > > -- > Martin A. Brown > http://linux-ip.net/ > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at linux-ip.net Sun May 20 08:42:02 2012 From: martin at linux-ip.net (Martin A. Brown) Date: Sun, 20 May 2012 02:42:02 -0400 Subject: [Tutor] Translating R Code to Python-- reading in csv files, writing out to csv files In-Reply-To: References: Message-ID: Benjamin, : Thanks Martin-- this is really great. My major question now is : that I need to transition to Python for a project and I need to : learn how to think in Python instead of in R. The two strategies : I have used so far are: a) going through the description and : exercises in http://www.openbookproject.net/thinkcs/python/english2e/ : and b) trying to convert my R code into Python. I haven't seen that before, but, of course, there ar scads of resources out there for anybody learning these days. : On a high-level, do you have any other suggestions for how I : could go about becoming more proficient in Python? Well, here is my list. Others probably have some suggestions, too: * solve a specific and immediate real problem in Python, but solve the problem as generally as possible; apply * lurk here (and on other lists) and watch how experienced Python practitioners help others face a problem in Python; absorb * join domain-specific Python groups that discuss libraries, tools or techniques that apply in your area of interest; inquire * learn Python's common datatypes well, you will encounter them often: str, int, float, list, dict, set; study * learn Pythonic programming idioms, and, importantly, learn why they are considered Pythonic (that will give you insight into thinking in Python); gain relevant experience * browse the standard library occasionally to learn a new module http://docs.python.org/py-modindex.html * learn how to make modules; build your code into modules (if appropriate and where possible) * read a book (lots of options here); I'm a 'learn by example' sort so I liked the O'Reilly _Python Cookbook_ [0] * read PEP 8 http://www.python.org/dev/peps/pep-0008/ Good luck and enjoy Python, -Martin [0] http://shop.oreilly.com/product/9780596007973.do -- Martin A. Brown http://linux-ip.net/ From massimodisasha at gmail.com Sun May 20 12:30:43 2012 From: massimodisasha at gmail.com (Massimo Di Stefano) Date: Sun, 20 May 2012 06:30:43 -0400 Subject: [Tutor] Translating R Code to Python-- reading in csv files, writing out to csv files In-Reply-To: References: Message-ID: <6444142E-D5DE-436C-8F53-B8710E8FD901@gmail.com> Maybe this doc. http://mathesaurus.sourceforge.net/matlab-python-xref.pdf can help ? i found it useful. Massimo. Il giorno May 20, 2012, alle ore 2:42 AM, Martin A. Brown ha scritto: > > Benjamin, > > : Thanks Martin-- this is really great. My major question now is > : that I need to transition to Python for a project and I need to > : learn how to think in Python instead of in R. The two strategies > : I have used so far are: a) going through the description and > : exercises in http://www.openbookproject.net/thinkcs/python/english2e/ > : and b) trying to convert my R code into Python. > > I haven't seen that before, but, of course, there ar scads of > resources out there for anybody learning these days. > > : On a high-level, do you have any other suggestions for how I > : could go about becoming more proficient in Python? > > Well, here is my list. Others probably have some suggestions, too: > > * solve a specific and immediate real problem in Python, but solve > the problem as generally as possible; apply > > * lurk here (and on other lists) and watch how experienced Python > practitioners help others face a problem in Python; absorb > > * join domain-specific Python groups that discuss libraries, > tools or techniques that apply in your area of interest; inquire > > * learn Python's common datatypes well, you will encounter them > often: str, int, float, list, dict, set; study > > * learn Pythonic programming idioms, and, importantly, learn > why they are considered Pythonic (that will give you insight > into thinking in Python); gain relevant experience > > * browse the standard library occasionally to learn a new module > http://docs.python.org/py-modindex.html > > * learn how to make modules; build your code into modules (if > appropriate and where possible) > > * read a book (lots of options here); I'm a 'learn by example' > sort so I liked the O'Reilly _Python Cookbook_ [0] > > * read PEP 8 http://www.python.org/dev/peps/pep-0008/ > > Good luck and enjoy Python, > > -Martin > > [0] http://shop.oreilly.com/product/9780596007973.do > > -- > 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 From joel.goldstick at gmail.com Sun May 20 14:44:25 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 20 May 2012 08:44:25 -0400 Subject: [Tutor] Translating R Code to Python-- reading in csv files, writing out to csv files In-Reply-To: <6444142E-D5DE-436C-8F53-B8710E8FD901@gmail.com> References: <6444142E-D5DE-436C-8F53-B8710E8FD901@gmail.com> Message-ID: On Sun, May 20, 2012 at 6:30 AM, Massimo Di Stefano wrote: > Maybe this doc. > > http://mathesaurus.sourceforge.net/matlab-python-xref.pdf > > can help ? > > i found it useful. > > Massimo. > > > Il giorno May 20, 2012, alle ore 2:42 AM, Martin A. Brown ha scritto: > >> >> Benjamin, >> >> : Thanks Martin-- this is really great. ?My major question now is >> : that I need to transition to Python for a project and I need to >> : learn how to think in Python instead of in R. ?The two strategies >> : I have used so far are: a) going through the description and >> : exercises in ?http://www.openbookproject.net/thinkcs/python/english2e/ >> : and b) trying to convert my R code into Python. >> >> I haven't seen that before, but, of course, there ar scads of >> resources out there for anybody learning these days. >> >> : On a high-level, do you have any other suggestions for how I >> : could go about becoming more proficient in Python? >> >> Well, here is my list. ?Others probably have some suggestions, too: >> >> ?* solve a specific and immediate real problem in Python, but solve >> ? ?the problem as generally as possible; apply >> >> ?* lurk here (and on other lists) and watch how experienced Python >> ? ?practitioners help others face a problem in Python; absorb >> >> ?* join domain-specific Python groups that discuss libraries, >> ? ?tools or techniques that apply in your area of interest; inquire >> >> ?* learn Python's common datatypes well, you will encounter them >> ? ?often: str, int, float, list, dict, set; study >> >> ?* learn Pythonic programming idioms, and, importantly, learn >> ? ?why they are considered Pythonic (that will give you insight >> ? ?into thinking in Python); gain relevant experience >> >> ?* browse the standard library occasionally to learn a new module >> ? ?http://docs.python.org/py-modindex.html >> >> ?* learn how to make modules; build your code into modules (if >> ? ?appropriate and where possible) >> >> ?* read a book (lots of options here); I'm a 'learn by example' >> ? ?sort so I liked the O'Reilly _Python Cookbook_ [0] >> >> ?* read PEP 8 http://www.python.org/dev/peps/pep-0008/ >> >> Good luck and enjoy Python, >> >> -Martin >> >> [0] http://shop.oreilly.com/product/9780596007973.do >> >> -- >> 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 > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor So, with the example file you showed previously, sit down and write some code. It probably will take less than a screen size full of code -- maybe 20 lines or so. See what you get for output. You will certainly get errors -- syntax and runtime. When you get stuck, cut and paste the code and the trace-back that python gives you to your email, and people will help you move forward. -- Joel Goldstick From d at davea.name Sun May 20 17:53:29 2012 From: d at davea.name (Dave Angel) Date: Sun, 20 May 2012 11:53:29 -0400 Subject: [Tutor] Translating R Code to Python-- reading in csv files, writing out to csv files In-Reply-To: References: <1318229924-1337450331-cardhu_decombobulator_blackberry.rim.net-1190924810-@b11.c28.bise6.blackberry> Message-ID: <4FB91379.4030400@davea.name> Please don't top-post. You lose the context of what was written before, since it's now out of order. When replying to a message, quote the parts you're replying to, and put your comments AFTER the quotes. On 05/19/2012 05:07 PM, Benjamin G wrote: > Thanks, Joel. Here is a simple example of the input data (top row is > column headers in the input file) > Patient ID Sample Type Survival Time(months) > unique_patient_ID1 Tumor 12 > unique_patient_ID2 Normal 5 > unique_patient_ID3 Normal 60 > unique_patient_ID4 Tumor 2 > unique_patient_ID5 Tumor 13 But your subject line said you have comma-separated files. Just how are these files defined? The csv module can handle other separators, but I don't see any separator at all, just fixed columns. -- DaveA From quidam_senfuit at yahoo.com Sun May 20 20:08:16 2012 From: quidam_senfuit at yahoo.com (Quidam S-enfuit) Date: Sun, 20 May 2012 11:08:16 -0700 (PDT) Subject: [Tutor] print 'hello world' - invalid syntax Message-ID: <1337537296.69967.YahooMailClassic@web121107.mail.ne1.yahoo.com> I have installed python on the windows 7 machine. (Tried 64 bit version also; same error). I tried print "Hello world" and? print 'hello world'.? It stated syntax error!?... Thanks. =======copied from python (interactive command) /pasted below================== Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> print 'hello world' ? File "", line 1 ??? print 'hello world' ????????????????????? ^ SyntaxError: invalid syntax ==============================end==================================== -------------- next part -------------- An HTML attachment was scrubbed... URL: From robertvstepp at gmail.com Sun May 20 20:16:47 2012 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 20 May 2012 13:16:47 -0500 Subject: [Tutor] print 'hello world' - invalid syntax In-Reply-To: <1337537296.69967.YahooMailClassic@web121107.mail.ne1.yahoo.com> References: <1337537296.69967.YahooMailClassic@web121107.mail.ne1.yahoo.com> Message-ID: On Sun, May 20, 2012 at 1:08 PM, Quidam S-enfuit wrote: > > I have installed python on the windows 7 machine. (Tried 64 bit version > also; same error). > I tried print "Hello world" and? print 'hello world'.? It stated syntax > error!?... > Thanks. > =======copied from python (interactive command) /pasted > below================== > Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] > on win > 32 > Type "help", "copyright", "credits" or "license" for more information. > >>> print 'hello world' > ? File "", line 1 > ??? print 'hello world' > ????????????????????? ^ > SyntaxError: invalid syntax > > ==============================end==================================== I am starting to learn Python as well. Apparently one of the significant changes from Python 2.x versions to the new Python 3.x versions is that print is now treated as a function. So instead try: print('hello world') I think that should work for your version of Python. -- Cheers! boB From brianjamesarb at gmail.com Sun May 20 20:19:24 2012 From: brianjamesarb at gmail.com (brian arb) Date: Sun, 20 May 2012 14:19:24 -0400 Subject: [Tutor] print 'hello world' - invalid syntax In-Reply-To: <1337537296.69967.YahooMailClassic@web121107.mail.ne1.yahoo.com> References: <1337537296.69967.YahooMailClassic@web121107.mail.ne1.yahoo.com> Message-ID: http://docs.python.org/release/3.0.1/whatsnew/3.0.html The print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the oldprint statement (*PEP 3105* ). try print('hello world') On Sun, May 20, 2012 at 2:08 PM, Quidam S-enfuit wrote: > I have installed python on the windows 7 machine. (Tried 64 bit version > also; same error). > I tried print "Hello world" and print 'hello world'. It stated syntax > error!?... > Thanks. > =======copied from python (interactive command) /pasted > below================== > Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] > on win > 32 > Type "help", "copyright", "credits" or "license" for more information. > >>> print 'hello world' > File "", line 1 > print 'hello world' > ^ > SyntaxError: invalid syntax > > > > > > > ==============================end==================================== > > > _______________________________________________ > 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 breamoreboy at yahoo.co.uk Sun May 20 20:20:32 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 20 May 2012 19:20:32 +0100 Subject: [Tutor] print 'hello world' - invalid syntax In-Reply-To: <1337537296.69967.YahooMailClassic@web121107.mail.ne1.yahoo.com> References: <1337537296.69967.YahooMailClassic@web121107.mail.ne1.yahoo.com> Message-ID: On 20/05/2012 19:08, Quidam S-enfuit wrote: > I have installed python on the windows 7 machine. (Tried 64 bit version also; same error). > I tried print "Hello world" and print 'hello world'. It stated syntax error!?... > Thanks. > =======copied from python (interactive command) /pasted below================== > Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win > > 32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> print 'hello world' > > File "", line 1 > > print 'hello world' > > ^ > > SyntaxError: invalid syntax > > > ==============================end==================================== > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Print is a function in Python 3, so you need print('hello world'). -- Cheers. Mark Lawrence. From alan.gauld at btinternet.com Sun May 20 20:48:44 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 May 2012 19:48:44 +0100 Subject: [Tutor] print 'hello world' - invalid syntax In-Reply-To: <1337537296.69967.YahooMailClassic@web121107.mail.ne1.yahoo.com> References: <1337537296.69967.YahooMailClassic@web121107.mail.ne1.yahoo.com> Message-ID: On 20/05/12 19:08, Quidam S-enfuit wrote: > I have installed python on the windows 7 machine. (Tried 64 bit version > also; same error). > I tried print "Hello world" and print 'hello world'. It stated syntax > error!?... As others have said you are using version 2 syntax with version 3 Python. You need to "downgrade" to version 2.7 of Python or find a version 3 tutorial. If you have programmed before in another language you should probably stick with v3 and use the official tutorial on the Python web site. If you are a complete beginner to programming and Python then you need to visit the beginners page and find a v3 tutor you like (you could try mine! :-) Or downgrade to 2.7 and use any of the many v2 tutorials out there (including mine! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From robertvstepp at gmail.com Sun May 20 22:01:48 2012 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 20 May 2012 15:01:48 -0500 Subject: [Tutor] While learning Py: To IDE or not to IDE? Message-ID: Programming background; 1975-1978: FORTRAN, BASIC, some machine language/assembler. 1988: A summer of FORTRAN. Post-1988: No programming until past 1.5 yr. FORTRAN was used during pursuit of physics degree. Others while playing around developing games for minicomputers. Structured programming paradigm the only one I've used. Currently have been doing scripting in a custom scripting environment at work to make my life easier. This is on Solaris-based systems. Have recently augmented the custom scripting environment with Perl scripting to give me more power and error-checking capabilities (Others have started to use my scripts. They don't always use them as I intended.). Perl is a new language for me. Goals: Learn Python. While learning Python, learn all of the good C.Sc. stuff that I should have learned the first go-around, Learn Java and C/C++. Reevaluate. At home where I will be doing the brunt of my study, I am working on a W7 laptop. Currently continue to work on scripting projects at work, replacing Perl scripts with Python scripts. My wife, who is a Montessori teacher, has immediate need of programs for her students. Have currently outlined a design for a program to drill spelling words, which will have to have audio record/playback capabilities. Hope to get this and others done this summer before the new school year starts. I am certain that my wife will continue to have new projects for me as I complete the current ones. Hope to have educational software solutions to my wife's requests that are usable whether the students are at home or in class. Finally to the question: With the stated goals above, would it be better to invest time now at the front-end in learning a powerful IDE, or am I better served, while learning Python, to stick with IDLE and the shell and worry about an IDE later? I am willing to invest time now on learning an IDE if it will save me time overall. IF it would be beneficial now to learn an IDE, then it begs the question as to whether I should search for the best IDE for Python, then later the best one for Java, etc., or, instead, look for the best one that can handle all of the languages I plan to learn and use. Thanks for any guidance you can provide! -- Cheers! boB From robertvstepp at gmail.com Sun May 20 22:07:22 2012 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 20 May 2012 15:07:22 -0500 Subject: [Tutor] Teaching an 8-year-old programming. Message-ID: This is, in a sense, a related question to the ones I just posted. While observing me studying programming, my son has become interested in learning how to program as well. I have given him a very old Gateway PC to play around with. It was new when W95 came out. I have started him out with QBASIC, which comes with W95. He seems to be doing fine, but I am wondering if this is the best way to start him in the world of programming? Any thoughts about this? Thanks! -- Cheers! boB From jeanpierreda at gmail.com Sun May 20 23:15:07 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sun, 20 May 2012 17:15:07 -0400 Subject: [Tutor] Teaching an 8-year-old programming. In-Reply-To: References: Message-ID: I've heard remarkable things about http://www.programbydesign.org/ , but it's aimed at students a little older. Its design might help you; although, it also probably depends on motivation / what you want to teach. Anyway, that's the best I can offer. Good luck! It sounds like you're in for a fun time. :) -- Devin From robertvstepp at gmail.com Sun May 20 23:41:38 2012 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 20 May 2012 16:41:38 -0500 Subject: [Tutor] Teaching an 8-year-old programming. In-Reply-To: References: Message-ID: On Sun, May 20, 2012 at 4:15 PM, Devin Jeanpierre wrote: > I've heard remarkable things about http://www.programbydesign.org/ , > but it's aimed at students a little older. Its design might help you; > although, it also probably depends on motivation / what you want to > teach. > > Anyway, that's the best I can offer. Good luck! It sounds like you're > in for a fun time. :) > > -- Devin Thanks for the link. It looks interesting, but I'm not sure it is the way to go currently for my son. However, it gives me some ideas for my wife's class, which covers 7th through 9th grades in a single classroom. There seem to be many, ... , many thoughts on how to best teach programming to kids! I am currently thinking about "Invent Your Own Computer Games with Python" by Al Sweigart. His thought is to give kids complete, workable code for a real game and let them fool around with it. This might work! I did something similar starting out with my son using QBASIC, giving him a brief program that played music. He seemed to have quite a lot of fun fooling around with different permutations of the commands. Later, when I introduced him to some new commands, like generating random numbers, he combined a number guessing game with his self-composed musical theme. Has anyone experience using this book? -- Cheers! boB From brian.van.den.broek at gmail.com Sun May 20 23:44:03 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Sun, 20 May 2012 23:44:03 +0200 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: References: Message-ID: On 20 May 2012 23:04, "boB Stepp" wrote: > Goals: Learn Python. While learning Python, learn all of the good > C.Sc. stuff that I should have learned the first go-around, Learn Java > and C/C++. Reevaluate. > > Finally to the question: With the stated goals above, would it be > better to invest time now at the front-end in learning a powerful IDE, > or am I better served, while learning Python, to stick with IDLE and > the shell and worry about an IDE later? I am willing to invest time > now on learning an IDE if it will save me time overall. IF it would be > beneficial now to learn an IDE, then it begs the question as to > whether I should search for the best IDE for Python, then later the > best one for Java, etc., or, instead, look for the best one that can > handle all of the languages I plan to learn and use. > > Thanks for any guidance you can provide! > -- > Cheers! > boB Hi boB, These are close to religious questions :-) With you polyglot agenda, I would say you would be much better off to learn a powerful multipurpose editor well than to try to find the best of breed of each class of special purpose tool. There are three basic choice: emacs, vi or vim, and everything else. There is widespread, though not uniform, consensus that The One True Editor is one of emacs and vi. After that, the rest is flamewars. I am an emacist, myself. But some of my best friends are vimists. Good luck, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From robertvstepp at gmail.com Mon May 21 00:19:52 2012 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 20 May 2012 17:19:52 -0500 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: References: Message-ID: On Sun, May 20, 2012 at 4:44 PM, Brian van den Broek wrote: > These are close to religious questions :-) > > With you polyglot agenda, I would say you would be much better off to learn > a powerful multipurpose editor well than to try to find the best of breed of > each class of special purpose tool. > > There are three basic choice: emacs, vi or vim, and everything else. There > is widespread, though not uniform, consensus that The One True Editor is one > of emacs and vi. After that, the rest is flamewars. > > I am an emacist, myself. But some of my best friends are vimists. I gather, then, that you feel my time would be well-spent now to learn a good editor/IDE now, rather than continue with IDLE? I did not intend to start a holy war on the best editor/IDE with my questions! ~(:>)) But since you brought it up, I'll ask a somewhat more general question: Why do you prefer an editor instead of a graphical IDE? I have limited experience with Emacs as I finally installed it on my PC at work to avoid having Windows-style end-of-line characters messing up my scripts which were to run in an UNIX environment. I can see potential there, but as my future projects get larger and more involved will it be able to do everything I would want it to do? Would I find myself wanting a full-fledged IDE? I don't have enough technical knowledge to answer these questions right now. Your thoughts? Cheers! boB From mlybrand at gmail.com Mon May 21 00:28:23 2012 From: mlybrand at gmail.com (Mark Lybrand) Date: Sun, 20 May 2012 15:28:23 -0700 Subject: [Tutor] Teaching an 8-year-old programming. In-Reply-To: References: Message-ID: Have you considered this book: http://www.amazon.com/Hello-World-Computer-Programming-Beginners/dp/1933988495 Mark On Sun, May 20, 2012 at 2:41 PM, boB Stepp wrote: > On Sun, May 20, 2012 at 4:15 PM, Devin Jeanpierre > wrote: >> I've heard remarkable things about http://www.programbydesign.org/ , >> but it's aimed at students a little older. Its design might help you; >> although, it also probably depends on motivation / what you want to >> teach. >> >> Anyway, that's the best I can offer. Good luck! It sounds like you're >> in for a fun time. :) >> >> -- Devin > > Thanks for the link. It looks interesting, but I'm not sure it is the > way to go currently for my son. However, it gives me some ideas for my > wife's class, which covers 7th through 9th grades in a single > classroom. > > There seem to be many, ... , many thoughts on how to best teach > programming to kids! > > I am currently thinking about "Invent Your Own Computer Games with > Python" by Al Sweigart. His thought is to give kids complete, workable > code for a real game and let them fool around with it. This might > work! I did something similar starting out with my son using QBASIC, > giving him a brief program that played music. He seemed to have quite > a lot of fun fooling around with different permutations of the > commands. Later, when I introduced him to some new commands, like > generating random numbers, he combined a number guessing game with his > self-composed musical theme. > > Has anyone experience using this book? > > -- > Cheers! > boB > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Mark :) From leamhall at gmail.com Mon May 21 00:29:10 2012 From: leamhall at gmail.com (Leam Hall) Date: Sun, 20 May 2012 18:29:10 -0400 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: References: Message-ID: <4FB97036.3060406@gmail.com> On 05/20/2012 06:19 PM, boB Stepp wrote: > On Sun, May 20, 2012 at 4:44 PM, Brian van den Broek >> I am an emacist, myself. But some of my best friends are vimists. Will pray for your soul... > But since you brought it up, I'll ask a somewhat more general > question: Why do you prefer an editor instead of a graphical IDE? Because I work on a Winderz desktop at work but have to connect to my servers via ssh. So terminal enabled programs are better for me. Because my hardware at home is so old that your average Gameboy has more computing power and better graphics. Because I'm too cheap to pay for much of anything I can't touch. And mostly because I don't make myself program as much as I want to and spend what little time coding actually in the code. Since I claim to want to be a programmer I need to do programmer stuff. Leam From robert.sjoblom at gmail.com Mon May 21 01:16:44 2012 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 21 May 2012 01:16:44 +0200 Subject: [Tutor] Teaching an 8-year-old programming. In-Reply-To: References: Message-ID: >> I am currently thinking about "Invent Your Own Computer Games with >> Python" by Al Sweigart. [snip] >> Has anyone experience using this book? "Snake wrangling for kids" is pretty good for teaching Python; it's also free (which is a bonus): http://www.briggs.net.nz/snake-wrangling-for-kids.html I've not had the chance to read "Invent your own computer games with Python", so can't say anything about it. -- best regards, Robert S. From david at pythontoo.com Mon May 21 01:19:28 2012 From: david at pythontoo.com (David Abbott) Date: Sun, 20 May 2012 19:19:28 -0400 Subject: [Tutor] Teaching an 8-year-old programming. In-Reply-To: References: Message-ID: On Sun, May 20, 2012 at 6:28 PM, Mark Lybrand wrote: > Have you considered this book: > > http://www.amazon.com/Hello-World-Computer-Programming-Beginners/dp/1933988495 > > Mark [snip] Another great book I really enjoyed it; http://www.amazon.com/Python-Programming-Absolute-Beginner-Edition/dp/1435455002 All the best, David From alan.gauld at btinternet.com Mon May 21 01:25:42 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 May 2012 00:25:42 +0100 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: References: Message-ID: On 20/05/12 21:01, boB Stepp wrote: > Programming background; > 1975-1978: FORTRAN, BASIC, some machine language/assembler. ... > > FORTRAN was used during pursuit of physics degree. That makes you the same vintage as me :-) > Goals: Learn Python. While learning Python, learn all of the good > C.Sc. stuff that I should have learned the first go-around, Learn Java > and C/C++. Reevaluate. There are a couple of tutorials that try to do that, although most just teach Python without any of the CS theory. I'd humbly suggest mine is one of the couple... :-) > Finally to the question: With the stated goals above, would it be > better to invest time now at the front-end in learning a powerful IDE, > or am I better served, while learning Python, to stick with IDLE and > the shell and worry about an IDE later? I strongly recommend sticking to the basics. An IDE just becomes one extra variable to worry about. Even IDLE has some idiosyncrasies but at least they are well known! A good editor is a Godsend but they don't need to be super powerful. You will of course get emacs and vim pushed- both are great, I use them both for different tasks. But both are best on Unix. (vim is less powerful in vanilla form and so is better on Windows because its more of a pure editor than a text processing toolset like emacs). But tools like Scite or Notepad++ or even Kate and gedit will do the basics of syntax coloring etc. > now on learning an IDE if it will save me time overall. Picking an IDE depends on what you are programming, some are better suited to particular tasks. If you only want a single IDE to cover Perl, Python, Java, C/C++ then Eclipse and Netbeans are the obvious choices. If you want to do GUI development in wxPython or Qt or..... others might work better. And if you want database connectivity then still others come into play. The vim/emacs and a terminal approach works for everything of course but are less GUI friendly. More useful yet might be to learn a more advanced python shell. Ironpython is popular and adds several features to the simple >>> prompt. Coming from FORTRAN and even Perl its easy to miss the potential of the >>> prompt as a power tool for experimentally building code. It is one of Python's best features. If you are on Windows make sure you have turned all the CMD prompt options (> HELP CMD) to bring it up close to the standard of bash. And of course ask questions here: - post sample code that illustrates the problem, the shorter the better. - always include full error text - include sample data in and out if the question is data related HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon May 21 01:39:34 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 May 2012 00:39:34 +0100 Subject: [Tutor] Teaching an 8-year-old programming. In-Reply-To: References: Message-ID: On 20/05/12 21:07, boB Stepp wrote: > This is, in a sense, a related question to the ones I just posted. > While observing me studying programming, my son has become interested > in learning how to program as well. While its possible to write good code in QBASIC it's much easier to learn a lot of bad habits. Learning Python will be better. Python was largely born as a tool to teach beginners to program while also usable in the real world. (There are many excellent child friendly languages to teach programming to kids but most are seriously limited beyond the basics - examples are Logo, Squeak/Robots/eToys etc.) A good compromise is the excellent Turtle module in Python. It gives instant graphical results, teaches how to apply sequences, loops and branches and leads naturally into other programming challenges in Python. Just >>> import turtle >>> help(turtle) and experiment... remember that >>> prompt thing? :-) You can also try my tutorial, I have had one 10 year old and one 14 year old complete it that I know of and it is/was used in a junior school computing class for a while. And of course, the author is readily available :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon May 21 02:36:08 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 May 2012 10:36:08 +1000 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: References: Message-ID: <4FB98DF8.4090504@pearwood.info> boB Stepp wrote: > Finally to the question: With the stated goals above, would it be > better to invest time now at the front-end in learning a powerful IDE, Depends on the powerful IDE. Personally, I haven't found an IDE that I like since I last used THINK Pascal on Apple Mac back in the 1990s. Since you are using Solaris, I expect your options for IDEs are limited. You're probably best off using Unix as your IDE: http://blog.sanctum.geek.nz/series/unix-as-ide/ which is my preferred solution. There's very little I can't do between my editor and a terminal window with a few tabs open. If you can run KDE 3, I recommend "kate" (KDE Advanced Text Editor). Avoid KDE 4, it is bloated and buggy and slow. > or am I better served, while learning Python, to stick with IDLE and > the shell and worry about an IDE later? I am willing to invest time > now on learning an IDE if it will save me time overall. IF it would be > beneficial now to learn an IDE, then it begs the question No it doesn't. It RAISES the question -- begging the question means to *assume the answer in the question*, and it is a logical fallacy. "Notepad is the best editor, because no other editor is as good as Notepad" is begging the question. http://begthequestion.info/ http://grammar.quickanddirtytips.com/begs-the-question.aspx > as to > whether I should search for the best IDE for Python, then later the > best one for Java, etc., or, instead, look for the best one that can > handle all of the languages I plan to learn and use. That depends on the IDEs themselves. Good applications (whether an IDE or something else) should make it easy to discover functionality and as simple to learn as the task allows, so there's no disadvantage to exploring a number of good IDEs rather than committing to one early on and then sticking with it forever. -- Steven From steve at pearwood.info Mon May 21 02:41:05 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 May 2012 10:41:05 +1000 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: References: Message-ID: <4FB98F21.5030402@pearwood.info> Brian van den Broek wrote: > There are three basic choice: emacs, vi or vim, and everything else. There > is widespread, though not uniform, consensus that The One True Editor is > one of emacs and vi. After that, the rest is flamewars. That is insanity! There is only One True EDitor, ed! It is right there in the name, it's an EDitor! ed is the true unix editor: http://www.gnu.org/fun/jokes/ed.msg.html -- Steven From jugurtha.hadjar at gmail.com Mon May 21 03:06:52 2012 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Mon, 21 May 2012 02:06:52 +0100 Subject: [Tutor] Teaching an 8-year-old programming. In-Reply-To: References: Message-ID: <4FB9952C.8030800@gmail.com> On 05/20/2012 09:07 PM, boB Stepp wrote: > This is, in a sense, a related question to the ones I just posted. > While observing me studying programming, my son has become interested > in learning how to program as well. I have given him a very old > Gateway PC to play around with. It was new when W95 came out. I have > started him out with QBASIC, which comes with W95. He seems to be > doing fine, but I am wondering if this is the best way to start him in > the world of programming? Any thoughts about this? > > Thanks! This sounds great! I started programming around 8 or 9 too with BASIC (QBasic, GWBasic,,,). Your son is very lucky in two ways: 1- He is an english speaker: When I was his age, all I spoke were four languages (french, arabic, kabyle and algerian dialect) and none of them was english. English is the language to really access good resources on programming. 2- There is Internet in 2012: I didn't log in until I was a teenager and it was from an internet caf? because it was very expensive. 3- (I know I said two ways, but you shouldn't have believed me): He has a father who's an insider. It's a tremendous plus because you "get it". The syntax is kind of merciful so he'd be up and running in no time, tackling what he really wants to do. If I may suggest Zed Shaw's excellent series: http://learnpythonthehardway.org/ The book can be found here (HTML): http://learnpythonthehardway.org/book/ I'm biased, the guy has similar stuff for C too. Later, he could do things with C/Python. I'm reading a book called "Real World Instrumentation with Python" where the author shows a combination between hardware level programming with C and wrapping/binding with Python. It's very interesting. Good luck to both of you! -- ~Jugurtha Hadjar, From robertvstepp at gmail.com Mon May 21 05:16:46 2012 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 20 May 2012 22:16:46 -0500 Subject: [Tutor] Teaching an 8-year-old programming. In-Reply-To: References: Message-ID: On Sun, May 20, 2012 at 6:16 PM, Robert Sjoblom wrote: > "Snake wrangling for kids" is pretty good for teaching Python; it's > also free (which is a bonus): > http://www.briggs.net.nz/snake-wrangling-for-kids.html > Thanks everyone for all of the good suggestions! After spending most of the day looking at them I think that (for us) "Snake Wrangling for Kids" is the winner. It is a very readable book that I think Jeremy will be able to follow. It also incorporates the suggestions of Bill and Alan in using Turtle Graphics, which I think (after playing with it myself today) is pretty cool. Now I just have to get Jeremy some updated hardware, so that he can both connect to the Internet and run Python 3. This is an obvious opportunity to convince my wife to allow me to update "my" hardware, so that both she and Jeremy can update theirs. -- Cheers! boB From modulok at gmail.com Mon May 21 07:57:14 2012 From: modulok at gmail.com (Modulok) Date: Sun, 20 May 2012 23:57:14 -0600 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: <4FB98DF8.4090504@pearwood.info> References: <4FB98DF8.4090504@pearwood.info> Message-ID: > Since you are using Solaris, I expect your options for IDEs are limited. > You're probably best off using Unix as your IDE: > > http://blog.sanctum.geek.nz/series/unix-as-ide/ > > which is my preferred solution. There's very little I can't do between my > editor and a terminal window with a few tabs open. Apparently I'm not alone. I've not found an IDE I liked much either. They all feel kind of bloated with 37+ useless features I don't need. Instead, I use jEdit, a few choice plugins and an ssh connection to a command shell on a FreeBSD file server. (The fact that jEdit was written in java is irritating form a licensing perspective on some OS's but the editor itself is top notch.) A decent editor combined with a good command shell is all I've ever needed. If I'm on the console alone, for minor editing I just use nano. Personally, and this is just me, I've felt that big IDE's add a lot of interface and fluff but not a lot of substance. One of the benefits of learning a few basic editors and how to really use a command shell, is that it doesn't matter what brand of linux/BSD/unix you're on, you're still pretty much at home. That said, IDE's still have their place, especially when writing a lot of GUI stuff. Learning to use a command line at first feels really clunky and primitive, but eventually it eclipses most GUI's and IDE's in terms of speed and the tools available. You can also ooze right into system administration without much effort. But again, that's just me :p -Modulok- From alan.gauld at btinternet.com Mon May 21 09:44:20 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 May 2012 08:44:20 +0100 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: <4FB98F21.5030402@pearwood.info> References: <4FB98F21.5030402@pearwood.info> Message-ID: On 21/05/12 01:41, Steven D'Aprano wrote: > That is insanity! There is only One True EDitor, ed! It is right there > in the name, it's an EDitor! ed is the true unix editor: > > http://www.gnu.org/fun/jokes/ed.msg.html Having once had no alternative to ed and a 3500 line C program to write, I don't get the joke! (but I did get very tight C!) :-( $ cat > hello.py print 'hello world' ^D $ ed -p'->' hello.py 20 ->1,$p print 'hello world' ->i for n in range(3): . ->1,$p for n in range(3): print 'hello world' ->2s/print/ print/ ->1,$p for n in range(3): print 'hello world' ->wq 42 $ Note I made ed more "user friendly" by including a prompt (->)... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon May 21 09:48:47 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 May 2012 08:48:47 +0100 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: References: <4FB98DF8.4090504@pearwood.info> Message-ID: On 21/05/12 06:57, Modulok wrote: > Learning to use a command line at first feels really clunky and primitive, but > eventually it eclipses most GUI's and IDE's in terms of speed and the tools An old colleague of mine used to say: "A GUI makes easy things trivial and hard things impossible" :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon May 21 11:06:25 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 May 2012 19:06:25 +1000 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: References: <4FB98DF8.4090504@pearwood.info> Message-ID: <20120521090625.GB32207@ando> On Sun, May 20, 2012 at 11:57:14PM -0600, Modulok wrote: > Learning to use a command line at first feels really clunky and primitive, but > eventually it eclipses most GUI's and IDE's in terms of speed and the tools > available. You can also ooze right into system administration without much > effort. Perhaps the hardest part about using the command line is *discoverability*. There is nothing even close to the equivalent of clicking on a menu to see what commands are available. If you have a bad memory for commands you use only once every six months, like I do, you'll forever be googling for "how do I do X on Linux?" type questions. "Oh yeah, that's right, it's such-and-such a command." But if you can get past that, and I understand that commandlines are not for everyone, they are *much* more powerful and efficient than graphical applications, for many (although not all!) tasks. -- Steven From wolfrage8765 at gmail.com Mon May 21 12:38:51 2012 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Mon, 21 May 2012 12:38:51 +0200 Subject: [Tutor] Is this possible and should it be done? Message-ID: All, I have had a curious idea for awhile, and was wondering the best way to implement it in Python and if it is even possible. The concept is this, a file that is actually a folder that contains multiple files (Like an Archive format). The actual files are really un-important. What I want is for the folder to be represented as a single file by any normal file browser, but to be able to access the files with-in via Python. I will actually use the word archive to represent my mystical folder as a file concept for the rest of this message.?Some additional things I would like to be possible: is for multiple copies of the program to write to the same archive, but different files with-in at the same time (Reading & Writing to the archive should not lock the archive as long as they are different files); and for just the desired files with-in the archive to be loaded to memory with out having to hold the entire archive in memory. Use case for these additional capabilities. I was reading about how some advanced word processing programs (MS Word) actually save multiple working copies of the file with-in a single file representation and then just prior to combining the working copies it locks the original file and saves the working changes. That is what I would like to do. I want the single file because it is easy for a user to grasp that they need to copy a single file or that they are working on a single file, but it is not so easy for them to grasp the multiple file concepts. MS Word uses Binary streams as shown here: http://download.microsoft.com/download/5/0/1/501ED102-E53F-4CE0-AA6B-B0F93629DDC6/WindowsCompoundBinaryFileFormatSpecification.pdf Is this easy to do with python? Does it prevent file locking if you use streams? Is this worth the trouble, or should I just use a directory and forget this magical idea? A piece of reference for?my archive thoughts, ISO/IEC 26300:2006?chapter 17.2 From joel.goldstick at gmail.com Mon May 21 13:21:36 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 21 May 2012 07:21:36 -0400 Subject: [Tutor] Is this possible and should it be done? In-Reply-To: References: Message-ID: On Mon, May 21, 2012 at 6:38 AM, wolfrage8765 at gmail.com wrote: > All, I have had a curious idea for awhile, and was wondering the best > way to implement it in Python and if it is even possible. The concept > is this, a file that is actually a folder that contains multiple files > (Like an Archive format). The actual files are really un-important. > What I want is for the folder to be represented as a single file by > any normal file browser, but to be able to access the files with-in > via Python. I will actually use the word archive to represent my > mystical folder as a file concept for the rest of this message.?Some > additional things I would like to be possible: is for multiple copies > of the program to write to the same archive, but different files > with-in at the same time (Reading & Writing to the archive should not > lock the archive as long as they are different files); and for just > the desired files with-in the archive to be loaded to memory with out > having to hold the entire archive in memory. > Use case for these additional capabilities. I was reading about how > some advanced word processing programs (MS Word) actually save > multiple working copies of the file with-in a single file > representation and then just prior to combining the working copies it > locks the original file and saves the working changes. That is what I > would like to do. I want the single file because it is easy for a user > to grasp that they need to copy a single file or that they are working > on a single file, but it is not so easy for them to grasp the multiple > file concepts. > > MS Word uses Binary streams as shown here: > http://download.microsoft.com/download/5/0/1/501ED102-E53F-4CE0-AA6B-B0F93629DDC6/WindowsCompoundBinaryFileFormatSpecification.pdf > Is this easy to do with python? Does it prevent file locking if you > use streams? Is this worth the trouble, or should I just use a > directory and forget this magical idea? > A piece of reference for?my archive thoughts, ISO/IEC 26300:2006?chapter 17.2 > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I'm not sure if this is exactly what you are looking for, but python handles tar files (various compression formats) with this module: http://docs.python.org/library/tarfile.html. What is your motivation for this idea? -- Joel Goldstick From steve at pearwood.info Mon May 21 13:33:52 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 May 2012 21:33:52 +1000 Subject: [Tutor] Is this possible and should it be done? In-Reply-To: References: Message-ID: <4FBA2820.6000405@pearwood.info> wolfrage8765 at gmail.com wrote: > All, I have had a curious idea for awhile, and was wondering the best > way to implement it in Python and if it is even possible. The concept > is this, a file that is actually a folder that contains multiple files > (Like an Archive format). The actual files are really un-important. What you are describing is exactly like any one of many different file formats, such as zip files, tar files, and others. > What I want is for the folder to be represented as a single file by > any normal file browser, but to be able to access the files with-in > via Python. I will actually use the word archive to represent my > mystical folder as a file concept for the rest of this message. Actual folders ("directories") are special, since they are handled by the file system. But you can create any file format you like, it is just data. For example, a GIF file can contain multiple frames (animated GIFs); Libre Office and Open Office files contain multiple pieces of data; zip files can contain multiple compressed files of any type; AVI files can contain multiple audio streams; cd/dvd image files can contain multiple file system; etc. There's nothing special about file browsers: if they don't understand a file format, they can't do anything special with files of that format. But if they do understand the file format, then they can. *Any* program that understands the file format can do anything it likes with the data. > Some > additional things I would like to be possible: is for multiple copies > of the program to write to the same archive, but different files > with-in at the same time (Reading & Writing to the archive should not > lock the archive as long as they are different files); and for just > the desired files with-in the archive to be loaded to memory with out > having to hold the entire archive in memory. *shrug* Sure, whatever you like. You just have to program it. [...] > MS Word uses Binary streams as shown here: > http://download.microsoft.com/download/5/0/1/501ED102-E53F-4CE0-AA6B-B0F93629DDC6/WindowsCompoundBinaryFileFormatSpecification.pdf > Is this easy to do with python? Does it prevent file locking if you File locking is not a property of the programming language, but of the file system and operating system. > use streams? Is this worth the trouble, or should I just use a > directory and forget this magical idea? Seems like a lot of work for very little benefit, but if you want it, you can build it. Personally, I think that instead of re-inventing the wheel, use existing tools. Python comes with the pre-built tools to use tar, zip, gzip, xml, json, pickle file formats. You should investigate the powers and limitations of those file formats before inventing your own. I'm sorry that I can't be more specific, but your question is awfully generic. It's a bit like somebody saying "Can I build a remote-controlled car out of electronics and metal?" Of course you can. But to actually do so, you need to have detailed plans rather than vague questions -- you need to know electronics and mechanics. But good luck! -- Steven From joel.goldstick at gmail.com Mon May 21 13:34:40 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 21 May 2012 07:34:40 -0400 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: <20120521090625.GB32207@ando> References: <4FB98DF8.4090504@pearwood.info> <20120521090625.GB32207@ando> Message-ID: On Mon, May 21, 2012 at 5:06 AM, Steven D'Aprano wrote: > On Sun, May 20, 2012 at 11:57:14PM -0600, Modulok wrote: > >> Learning to use a command line at first feels really clunky and primitive, but >> eventually it eclipses most GUI's and IDE's in terms of speed and the tools >> available. You can also ooze right into system administration without much >> effort. > > Perhaps the hardest part about using the command line is > *discoverability*. There is nothing even close to the equivalent of > clicking on a menu to see what commands are available. If you have a bad > memory for commands you use only once every six months, like I do, > you'll forever be googling for "how do I do X on Linux?" type questions. > "Oh yeah, that's right, it's such-and-such a command." > > But if you can get past that, and I understand that commandlines are not > for everyone, they are *much* more powerful and efficient than graphical > applications, for many (although not all!) tasks. > > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor There seem to be two different mindsets about ide vs plain editor. I used to be an MS guy and I used MS IDE. Its nice in that you get dropdowns for things you might kind of know, but can't remember. They save keystrokes. And if that world is good for you, then go that way. Since moving away from MS to Linux, I have had to switch my thinking. Of course in python there is good documentation available with help(whatever) in the interactive shell. Its great! I like the spareness of an editor, switching from vim (which I know just the tip of the iceberg) and gedit. It makes it easy to work on different machines, ssh to a server and edit stuff there. You are planning to learn a whole lot of new stuff, which may be doable for you, but I couldn't do that. You will find plenty to challenge your mind with python, an editor, and a tutorial or two (or Alan's book!). Read-code-discover-repeat. You can pick up tools along the way when it seems they would make something more productive. but... others like IDEs -- Joel Goldstick From steve at pearwood.info Mon May 21 13:38:19 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 May 2012 21:38:19 +1000 Subject: [Tutor] Is this possible and should it be done? In-Reply-To: References: Message-ID: <4FBA292B.8020203@pearwood.info> Joel Goldstick wrote: > I'm not sure if this is exactly what you are looking for, but python > handles tar files (various compression formats) with this module: > http://docs.python.org/library/tarfile.html. Technically, tar is not a compression format. It just combines multiple files into a single tar file, with no compression. Of course, you can compress the tar file afterwards, with zip, gzip, bzip2, rar, or any other compression format you like. Especially common ones are .tar.gz and .tar.bz2. > What is your motivation for this idea? With respect Joel, the OP did give a use-case for his idea, did you not notice it? -- Steven From joel.goldstick at gmail.com Mon May 21 14:07:32 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 21 May 2012 08:07:32 -0400 Subject: [Tutor] Is this possible and should it be done? In-Reply-To: <4FBA292B.8020203@pearwood.info> References: <4FBA292B.8020203@pearwood.info> Message-ID: On Mon, May 21, 2012 at 7:38 AM, Steven D'Aprano wrote: > Joel Goldstick wrote: > >> I'm not sure if this is exactly what you are looking for, but python >> handles tar files (various compression formats) with this module: >> http://docs.python.org/library/tarfile.html. > > > Technically, tar is not a compression format. It just combines multiple > files into a single tar file, with no compression. > > Of course, you can compress the tar file afterwards, with zip, gzip, bzip2, > rar, or any other compression format you like. Especially common ones are > .tar.gz and .tar.bz2. > > > >> What is your motivation for this idea? > > > With respect Joel, the OP did give a use-case for his idea, did you not > notice it? Maybe I said that wrong. I was just wondering why someone would want to rebuild something that is already available with python module. Sometimes people like to build things to see how they work. Sometimes they build because they aren't aware of a previously built solution. And thanks about pointing out that tar doesn't do the compressing, but can be combined with compression software. > > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick From d at davea.name Mon May 21 15:44:50 2012 From: d at davea.name (Dave Angel) Date: Mon, 21 May 2012 09:44:50 -0400 Subject: [Tutor] Is this possible and should it be done? In-Reply-To: References: Message-ID: <4FBA46D2.5000300@davea.name> On 05/21/2012 06:38 AM, wolfrage8765 at gmail.com wrote: > All, I have had a curious idea for awhile, and was wondering the best > way to implement it in Python and if it is even possible. The concept > is this, a file that is actually a folder that contains multiple files > (Like an Archive format). The actual files are really un-important. > What I want is for the folder to be represented as a single file by > any normal file browser, but to be able to access the files with-in > via Python. I will actually use the word archive to represent my > mystical folder as a file concept for the rest of this message. Some > additional things I would like to be possible: is for multiple copies > of the program to write to the same archive, but different files > with-in at the same time (Reading & Writing to the archive should not > lock the archive as long as they are different files); and for just > the desired files with-in the archive to be loaded to memory with out > having to hold the entire archive in memory. > Use case for these additional capabilities. I was reading about how > some advanced word processing programs (MS Word) actually save > multiple working copies of the file with-in a single file > representation and then just prior to combining the working copies it > locks the original file and saves the working changes. That is what I > would like to do. I want the single file because it is easy for a user > to grasp that they need to copy a single file or that they are working > on a single file, but it is not so easy for them to grasp the multiple > file concepts. > > MS Word uses Binary streams as shown here: > http://download.microsoft.com/download/5/0/1/501ED102-E53F-4CE0-AA6B-B0F93629DDC6/WindowsCompoundBinaryFileFormatSpecification.pdf > Is this easy to do with python? Does it prevent file locking if you > use streams? Is this worth the trouble, or should I just use a > directory and forget this magical idea? > A piece of reference for my archive thoughts, ISO/IEC 26300:2006 chapter 17.2 > When I first read your description, I assumed you were talking about the streams supported by NTFS, where it's possible to store multiple independent, named, streams of data within a single file. That particular feature isn't portable to other operating systems, nor even to non-NTFS systems. And the user could get tripped up by copying what he thought was the whole file, but in fact was only the unnamed stream. However, thanks for the link. That specification describes building an actual filesystem inside the file, which is a lot of work. It does not mention anything about stream locking, and my experience with MSWORD (which has been several years ago, now) indicates that the entire archive is locked whenever one instance of MSWORD is working on it. I think if you're trying to do something as flexible as MSWORD apparently does (or even worse - adding locking to it) you're asking for subtle bugs and race conditions. If the data you were storing is structured such that you can simplify the MS approach, then it may be worthwhile. For example, if each stream is always 4k. -- DaveA From bgailer at gmail.com Mon May 21 16:17:27 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 21 May 2012 10:17:27 -0400 Subject: [Tutor] While learning Py: To IDE or not to IDE? Message-ID: <4FBA4E77.60006@gmail.com> When I started learning Python I was pleased to discover Python For Windows. I probably would have given up if this tool were not available. Perhaps this is because I had spent many years working with other IDEs in other languages/applications. (VBA, FoxPro, Advanced Revelation to name some). I have no concern with there being features I might not use. I am delighted with the ones I do use. There are numerous IDES for Python that run on Linux systems (most are free). You too may find such IDEs a better choice. -- Bob Gailer 919-636-4239 From wolfrage8765 at gmail.com Mon May 21 16:23:46 2012 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Mon, 21 May 2012 16:23:46 +0200 Subject: [Tutor] Fwd: Is this possible and should it be done? In-Reply-To: References: <4FBA2820.6000405@pearwood.info> Message-ID: ---------- Forwarded message ---------- From: wolfrage8765 at gmail.com Date: Mon, May 21, 2012 at 2:16 PM Subject: Re: [Tutor] Is this possible and should it be done? To: Steven D'Aprano Thank you for the information. Sorry if I implied I wanted to re-invent the wheel but actually this feedback is exactly what I was looking for. I wanted to know existing methods to do just such operations. Also good point about the file browsers the only limitation to them is how much they understand the format. So since tar looks like an excellent option for what I want to do, I have another question before I begin my research. Do you already know if any of these formats offer file locking with in them, ;et me say that better. Can I open a, as example, tar file and lock a file with in it, with out locking the entire tar archive? Just asking if you already know if this is possible? Thank you again for the information! From wolfrage8765 at gmail.com Mon May 21 16:25:34 2012 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Mon, 21 May 2012 16:25:34 +0200 Subject: [Tutor] Is this possible and should it be done? In-Reply-To: References: <4FBA292B.8020203@pearwood.info> Message-ID: Forwarded because I did not reply to the list properly. Hopefully I did not forward wrong. ---------- Forwarded message ---------- From: wolfrage8765 at gmail.com Date: Mon, May 21, 2012 at 2:18 PM Subject: Re: [Tutor] Is this possible and should it be done? To: Joel Goldstick Thank you for your help Joel. In this case I don't want to know about the details just want an easy implementation and tar looks like the right solution. I also think that the compression being seperated from the format is likely best and will probably not use the compression as it would hinder my overall goal. OK going to read up on TAR now! Thanks again. From wolfrage8765 at gmail.com Mon May 21 16:32:09 2012 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Mon, 21 May 2012 16:32:09 +0200 Subject: [Tutor] Is this possible and should it be done? In-Reply-To: <14E4C354-0F5C-4694-B139-CDD576247D33@mac.com> References: <14E4C354-0F5C-4694-B139-CDD576247D33@mac.com> Message-ID: On Mon, May 21, 2012 at 4:06 PM, William R. Wing (Bill Wing) wrote: > On May 21, 2012, at 6:38 AM, wolfrage8765 at gmail.com wrote: > >> All, I have had a curious idea for awhile, and was wondering the best >> way to implement it in Python and if it is even possible. The concept >> is this, a file that is actually a folder that contains multiple files >> (Like an Archive format). The actual files are really un-important. >> What I want is for the folder to be represented as a single file by >> any normal file browser, but to be able to access the files with-in >> via Python. I will actually use the word archive to represent my >> mystical folder as a file concept for the rest of this message. Some >> additional things I would like to be possible: is for multiple copies >> of the program to write to the same archive, but different files >> with-in at the same time (Reading & Writing to the archive should not >> lock the archive as long as they are different files); and for just >> the desired files with-in the archive to be loaded to memory with out >> having to hold the entire archive in memory. >> Use case for these additional capabilities. I was reading about how >> some advanced word processing programs (MS Word) actually save >> multiple working copies of the file with-in a single file >> representation and then just prior to combining the working copies it >> locks the original file and saves the working changes. That is what I >> would like to do. I want the single file because it is easy for a user >> to grasp that they need to copy a single file or that they are working >> on a single file, but it is not so easy for them to grasp the multiple >> file concepts. > > As others have noted, this smells a lot like a .tar or similar archive. > > I'd suggest that it also smells like a scaled down and locally served Concurrent Versioning System. ?CVS does exactly what you want in terms of preserving only differences between edited versions of a file and it only locks the particular file that has been checked out; also allows you to back up to any previous version of a file. ?There are CVS-Python bindings (as well as SVN-Python, SVN being a newer more modern version of CVS). ?Google will turn up lots of references to both. > > -Bill Hey that sounds really interesting I did not know that SVN or CVS was even an option, but can they work with an archive, I will have to experiment, but that would take care of the multiple working copies and final merges latter. Thanks for the idea! From malcolm.newsome at gmail.com Mon May 21 16:47:25 2012 From: malcolm.newsome at gmail.com (Malcolm Newsome) Date: Mon, 21 May 2012 09:47:25 -0500 Subject: [Tutor] Coding Challenges Message-ID: <209510759275867618@unknownmsgid> Hey all, Being new to programming, I've found that my learning is accelerated when I've been asked to write scripts and deliver them in a specified time frame...Then, have those scripts critiqued. My question: Would the moderators of this list be interested in creating a monthly "challenge" of sorts? Then, those who participated could receive suggestions on how their code could have been written differently. If not, and you know of something else like this that exists, would you kindly share those resources? Thanks! Malcolm Newsome Sent from my Windows Phone -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolfrage8765 at gmail.com Mon May 21 16:52:40 2012 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Mon, 21 May 2012 16:52:40 +0200 Subject: [Tutor] Coding Challenges In-Reply-To: <209510759275867618@unknownmsgid> References: <209510759275867618@unknownmsgid> Message-ID: On Mon, May 21, 2012 at 4:47 PM, Malcolm Newsome wrote: > Hey all, > > Being new to programming, I've found that my learning is accelerated when > I've been asked to write scripts and deliver them in a specified time > frame...Then, have those scripts critiqued. > > My question: Would the moderators of this list be interested in creating a > monthly "challenge" of sorts? Then, those who participated could receive > suggestions on how their code could have been written differently. > > If not, and you know of something else like this that exists, would you > kindly share those resources? > > Thanks! > > Malcolm Newsome > > > Sent from my Windows Phone > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > If they agree I am all for it, if not I would still like to know what kind of plan that you come up with; as it will only make me better. -- Jordan Farrell From martin at linux-ip.net Mon May 21 17:14:13 2012 From: martin at linux-ip.net (Martin A. Brown) Date: Mon, 21 May 2012 11:14:13 -0400 Subject: [Tutor] Coding Challenges In-Reply-To: <209510759275867618@unknownmsgid> References: <209510759275867618@unknownmsgid> Message-ID: Hello, : Being new to programming, I've found that my learning is : accelerated when I've been asked to write scripts and deliver : them in a specified time frame...Then, have those scripts : critiqued. : : My question: Would the moderators of this list be interested in : creating a monthly "challenge" of sorts? Then, those who : participated could receive suggestions on how their code could : have been written differently. : : If not, and you know of something else like this that exists, : would you kindly share those resources? I'm answering a question slightly tangential to what you asked, in the time-honored tradition of asking a completely different question... Are you familiar with Project Euler? http://projecteuler.net/ http://projecteuler.net/problems I don't know whether critique is involved in the Project Euler, though. I would agree, having a concrete task to approach is a good way to learn. Enjoy, -Martin -- Martin A. Brown http://linux-ip.net/ From brian.van.den.broek at gmail.com Mon May 21 17:44:40 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Mon, 21 May 2012 17:44:40 +0200 Subject: [Tutor] [OT] Re: While learning Py: To IDE or not to IDE? In-Reply-To: <4FB98DF8.4090504@pearwood.info> References: <4FB98DF8.4090504@pearwood.info> Message-ID: On 21 May 2012 03:39, "Steven D'Aprano" wrote: > > boB Stepp wrote: >> now on learning an IDE if it will save me time overall. IF it would be >> beneficial now to learn an IDE, then it begs the question > > > No it doesn't. It RAISES the question -- begging the question means to *assume the answer in the question*, and it is a logical fallacy. > > "Notepad is the best editor, because no other editor is as good as Notepad" is begging the question. Steven, I am a philospher of logic and mathematics. Everytime I encounter 'begs the question' used in the way which you here resist, a little piece inside me dies. Thanks for fighting the good fight! However, as I hear this on the BBC and CBC Radio, and read it in periodicals I think ought be edited by those who know better, I confess I feel the worthy battle is lost. As W.V.O. Quine said: We cannot stem the tide of linguistic change, but we can drag our feet. Best, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremy.traurig at gmail.com Mon May 21 17:47:56 2012 From: jeremy.traurig at gmail.com (Jeremy Traurig) Date: Mon, 21 May 2012 08:47:56 -0700 Subject: [Tutor] Datetime Integers Message-ID: Hello, Is there a module available for python to convert datetime into an array of integers. For example, I have date where the first column is a datetime string (i.e. '2010-10-10 01:10:00') and I would like to convert that into an array with 5 columns corresponding to the integer values of Year,Month,Day,Hour,Minute. There is a function in Matlab that performs called datevec() that performs this operation. I find it much easier to index datetime or perform calculations on other data when date and time are integers. For example, i generally need to calculate averages, std, etc based on specific months, years, days, and hours. Those calculations are extremely simple when I can index an array of datetime integers. If there is no module to convert datetime to an array of integers, does anyone have an example of how i might index datetime using python datetime or numpy datetime64? In each case, I would need an array of datetime the same dimension as my data array. thanks -- jeremy From cfuller084 at thinkingplanet.net Mon May 21 17:31:19 2012 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 21 May 2012 10:31:19 -0500 Subject: [Tutor] Coding Challenges In-Reply-To: References: <209510759275867618@unknownmsgid> Message-ID: <201205211031.20431.cfuller084@thinkingplanet.net> On Monday 21 May 2012, Martin A. Brown wrote: > Hello, > > : Being new to programming, I've found that my learning is > : accelerated when I've been asked to write scripts and deliver > : them in a specified time frame...Then, have those scripts > : critiqued. > : > : My question: Would the moderators of this list be interested in > : creating a monthly "challenge" of sorts? Then, those who > : participated could receive suggestions on how their code could > : have been written differently. > : > : If not, and you know of something else like this that exists, > : would you kindly share those resources? > > I'm answering a question slightly tangential to what you asked, in > the time-honored tradition of asking a completely different > question... > > Are you familiar with Project Euler? > > http://projecteuler.net/ > http://projecteuler.net/problems > > I don't know whether critique is involved in the Project Euler, > though. I would agree, having a concrete task to approach is a good > way to learn. > > Enjoy, > > -Martin Project Euler is *very* math heavy (it is named after a famous mathematician, after all). Some of the problems are accessible to the general programmer, but expect to see a lot of stuff you might not have much familiarity with, if you aren't a math nerd. Another choice is The Python Challenge http://www.pythonchallenge.com/. It emphasizes a puzzle/riddle aspect, often the actual programming is pretty straightforward once you figure out what is needed. On the other hand, I haven't used it enough to progress all that far, so I really don't know it that well. Cheers From vince at vinces.ca Mon May 21 18:04:31 2012 From: vince at vinces.ca (Vince Spicer) Date: Mon, 21 May 2012 10:04:31 -0600 Subject: [Tutor] Datetime Integers In-Reply-To: References: Message-ID: This should do what you want. import time timestring = '2010-10-10 01:10:00' time_format = '%Y-%m-%d %H:%M:%S' timestruct = time.strptime(timestring, time_format) print [x for x in timestruct] For complex date parsing I would recommend checking out the dateutil.parser http://labix.org/python-dateutil On Mon, May 21, 2012 at 9:47 AM, Jeremy Traurig wrote: > Hello, > > Is there a module available for python to convert datetime into an > array of integers. For example, I have date where the first column is > a datetime string (i.e. '2010-10-10 01:10:00') and I would like to > convert that into an array with 5 columns corresponding to the integer > values of Year,Month,Day,Hour,Minute. There is a function in Matlab > that performs called datevec() that performs this operation. I find it > much easier to index datetime or perform calculations on other data > when date and time are integers. For example, i generally need to > calculate averages, std, etc based on specific months, years, days, > and hours. Those calculations are extremely simple when I can index an > array of datetime integers. If there is no module to convert datetime > to an array of integers, does anyone have an example of how i might > index datetime using python datetime or numpy datetime64? In each > case, I would need an array of datetime the same dimension as my data > array. > > thanks -- jeremy > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Vince Spicer -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon May 21 18:06:19 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 21 May 2012 12:06:19 -0400 Subject: [Tutor] Datetime Integers In-Reply-To: References: Message-ID: On Mon, May 21, 2012 at 11:47 AM, Jeremy Traurig wrote: > Hello, > > Is there a module available for python to convert datetime into an > array of integers. For example, I have date where the first column is > a datetime string (i.e. '2010-10-10 01:10:00') and I would like to > convert that into an array with 5 columns corresponding to the integer > values of Year,Month,Day,Hour,Minute. There is a function in Matlab > that performs called datevec() that performs this operation. I find it > much easier to index datetime or perform calculations on other data > when date and time are integers. For example, i generally need to > calculate averages, std, etc based on specific months, years, days, > and hours. Those calculations are extremely simple when I can index an > array of datetime integers. If there is no module to convert datetime > to an array of integers, does anyone have an example of how i might > index datetime using python datetime or numpy datetime64? In each > case, I would need an array of datetime the same dimension as my data > array. > > thanks -- jeremy > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Yes, its called datetime >>> import datetime >>> datetime.datetime.strptime('2010-10-10 01:10:00', "%Y-%m-%d %H:%M:%S") datetime.datetime(2010, 10, 10, 1, 10) >>> print datetime.datetime.strptime('2010-10-10 01:10:00', "%Y-%m-%d %H:%M:%S") 2010-10-10 01:10:00 >>> I think there are Constants that can be used in place of the formatting characters, but I couldn't find them in a quick search -- Joel Goldstick From emile at fenx.com Mon May 21 18:05:59 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 21 May 2012 09:05:59 -0700 Subject: [Tutor] Is this possible and should it be done? In-Reply-To: References: Message-ID: On 5/21/2012 3:38 AM wolfrage8765 at gmail.com said... > All, I have had a curious idea for awhile, and was wondering the best > way to implement it in Python and if it is even possible. The concept > is this, a file that is actually a folder that contains multiple files > (Like an Archive format). The actual files are really un-important. > What I want is for the folder to be represented as a single file by > any normal file browser, pyfuse allows you to create and represent whatever you want using python as a file system to the OS. Probably worth a look... Emile From wprins at gmail.com Mon May 21 18:09:55 2012 From: wprins at gmail.com (Walter Prins) Date: Mon, 21 May 2012 17:09:55 +0100 Subject: [Tutor] Datetime Integers In-Reply-To: References: Message-ID: Hi Jeremy, On 21 May 2012 16:47, Jeremy Traurig wrote: > Is there a module available for python to convert datetime into an > I presume you mean, "convert a datetime *string* into an array of integers"? array of integers. For example, I have date where the first column is > a datetime string (i.e. '2010-10-10 01:10:00') and I would like to > convert that into an array with 5 columns corresponding to the integer > values of Year,Month,Day,Hour,Minute. There is a function in Matlab > Yes, Python datetime objects support that directly. If d is a Python datetime, then d.year gives you the year, d.month gives you the month etc. See here: http://docs.python.org/library/datetime.html Also see 8.1.7 regarding converting to and from datetime strings. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From brian.van.den.broek at gmail.com Mon May 21 18:17:01 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Mon, 21 May 2012 18:17:01 +0200 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: References: Message-ID: On 21 May 2012 01:19, "boB Stepp" wrote: > > On Sun, May 20, 2012 at 4:44 PM, Brian van den Broek > wrote: > > With you polyglot agenda, I would say you would be much better off to learn > > a powerful multipurpose editor well than to try to find the best of breed of > > each class of special purpose tool. > > > > There are three basic choice: emacs, vi or vim, and everything else. There > > is widespread, though not uniform, consensus that The One True Editor is one > > of emacs and vi. After that, the rest is flamewars. > > > > I am an emacist, myself. But some of my best friends are vimists. > > I gather, then, that you feel my time would be well-spent now to learn > a good editor/IDE now, rather than continue with IDLE? > But since you brought it up, I'll ask a somewhat more general > question: Why do you prefer an editor instead of a graphical IDE? I > have limited experience with Emacs as I finally installed it on my PC > at work to avoid having Windows-style end-of-line characters messing > up my scripts which were to run in an UNIX environment. I can see > potential there, but as my future projects get larger and more > involved will it be able to do everything I would want it to do? Would > I find myself wanting a full-fledged IDE? I don't have enough > technical knowledge to answer these questions right now. Your > thoughts? Hi boB, If IDLE is working well for you, there's a good reason to stick with it. I meant to address whether you ought build a stable of purpose-specific IDEs or learn one editor to rule them all. The advantage of emacs, as I see it, is that it provides general purpose tools of high power for text-wrangling and the (non-trivial) time you have to invest to learn to exploit that power yields fruit whenever you are editing text. Emacs key bindings turn on all over the place, too; bash shell supports a bunch, for instance. It might be that editor plus language would be frustrating to try to learn all at once, though. Best, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Mon May 21 18:29:55 2012 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Mon, 21 May 2012 16:29:55 +0000 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: References: Message-ID: <945566790-1337617705-cardhu_decombobulator_blackberry.rim.net-1854341566-@b26.c12.bise7.blackberry> In my humble opinion, I think what is important is to get familiar with python for now. The free version of Komodo is what I have been using and its been cool. When you're comfortable with the language and you want to start writing some apps and all of that, you would be matured and independent enough to make a choice as to which editor to go with. Trust me, when you bury your head into writing amazing codes, the choice of editor would come almost naturally. All the best. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Brian van den Broek Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Mon, 21 May 2012 18:17:01 To: boB Stepp Cc: Subject: Re: [Tutor] While learning Py: To IDE or not to IDE? _______________________________________________ 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 Mon May 21 19:24:39 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 May 2012 18:24:39 +0100 Subject: [Tutor] Fwd: Is this possible and should it be done? In-Reply-To: References: <4FBA2820.6000405@pearwood.info> Message-ID: On 21/05/12 15:23, wolfrage8765 at gmail.com wrote: > if any of these formats offer file locking with in them, ;et me say > that better. Can I open a, as example, tar file and lock a file with > in it, with out locking the entire tar archive? No and you probably shouldn't. If two users are accessing the same file at once and one of them is modifying it (writing) while the other is trying to read it bad things are very likely to happen. Remember that these virtual files inside the tar file(say) are really just blocks of data within a single file. If you want to try modifying blocks inside a single store you will be better with a database. But that's not usually a single file (Access, SQLite etc excepted). Actually SQLite might do what you want by locking at the table row level, I haven't checked. You would need a single table of BLOB records where each BLOB represented a virtual file... Version control tools like CVS and SVN don't quite fit your needs either since they use multiple files not a single file. Although they do usually store all the historic versions of each file in one. So if it is really only historic data you need CVS, SVN, RCS etc may work. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bodsda at googlemail.com Mon May 21 20:34:57 2012 From: bodsda at googlemail.com (Bod Soutar) Date: Mon, 21 May 2012 19:34:57 +0100 Subject: [Tutor] Coding Challenges In-Reply-To: <209510759275867618@unknownmsgid> References: <209510759275867618@unknownmsgid> Message-ID: Pop onto http://ubuntuforums.org and find the programming talk sub-forum. One of the stickies there is an index of beginner programming challenges. It's a rolling process where the winner of the previous challenge posts a new one and then picks a winning entry who goes on to post the next challenge. Bodsda On May 21, 2012 3:50 PM, "Malcolm Newsome" wrote: > > Hey all, > > Being new to programming, I've found that my learning is accelerated when I've been asked to write scripts and deliver them in a specified time frame...Then, have those scripts critiqued. > > My question: Would the moderators of this list be interested in creating a monthly "challenge" of sorts? Then, those who participated could receive suggestions on how their code could have been written differently. > > If not, and you know of something else like this that exists, would you kindly share those resources? > > Thanks! > > Malcolm Newsome > > > Sent from my Windows Phone > > _______________________________________________ > 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 jeremy.traurig at gmail.com Mon May 21 22:04:26 2012 From: jeremy.traurig at gmail.com (Jeremy Traurig) Date: Mon, 21 May 2012 13:04:26 -0700 Subject: [Tutor] Datetime Integer Array Message-ID: Hello, I am reading a data file with a string time stamp as the first column, example below: '03/10/2010 02:00:00' '03/10/2010 02:10:00' '03/10/2010 02:20:00' '03/10/2010 02:30:00' etc to n number of rows. I'm using the numpy function genfromtxt to read this data: import numpy as np datetime_IN = np.genfromtxt('SIL633_original.txt', delimiter='\t', skip_header=141, dtype='|S19', usecols=0) Now I have a variable called datetime_IN which is an array of datetime strings to the nth row. I'd like to convert this strings to a numpy array of integers where each column represents a value of time. For example, using the same values above, i want an array of integers to look like this: 3,10,2010,2,0,0 3,10,2010,2,10,0 3,10,2010,2,20,0 3,10,2010,2,30,0 etc to n number of rows. I have already tried creating a numpy array of integers using this code: import time time_format = %m/%d/%Y %H:%M:%S for x in range(len(datetime_IN)): junk = time.strptime(datetime[x],time_format) junk2 = [y for y in junk] The above code works in general but it doesn't create an array with the same number of rows as datetime_IN, and I understand it doesn't because the previous data in junk2 is lost. I'd like to build the junk2 array but I'm not sure how. In other languages, I'm able to iterate over an array to build it, so in each iteration of a loop a new row is created for the arrray I'm building. I'm not quite sure how to do that in python. thanks -- jt From wolfrage8765 at gmail.com Mon May 21 22:24:39 2012 From: wolfrage8765 at gmail.com (Jordan) Date: Mon, 21 May 2012 22:24:39 +0200 Subject: [Tutor] Fwd: Is this possible and should it be done? In-Reply-To: References: <4FBA2820.6000405@pearwood.info> Message-ID: <4FBAA487.70308@gmail.com> On 05/21/2012 07:24 PM, Alan Gauld wrote: > On 21/05/12 15:23, wolfrage8765 at gmail.com wrote: > >> if any of these formats offer file locking with in them, ;et me say >> that better. Can I open a, as example, tar file and lock a file with >> in it, with out locking the entire tar archive? > > No and you probably shouldn't. > > If two users are accessing the same file at once and one of them is > modifying it (writing) while the other is trying to read it bad things > are very likely to happen. Remember that these virtual files inside > the tar file(say) are really just blocks of data within a single file. > > If you want to try modifying blocks inside a single store you will be > better with a database. But that's not usually a single file (Access, > SQLite etc excepted). Actually SQLite might do what you want by > locking at the table row level, I haven't checked. You would need a > single table of BLOB records where each BLOB represented a virtual > file... > Very interesting idea, I have actually used a SQLite file in this way before, not sure why I did not think of that possibility. SQLite's BLOB could be the perfect already created solution. Thank you all for your inputs. > Version control tools like CVS and SVN don't quite fit your needs > either since they use multiple files not a single file. Although they > do usually store all the historic versions of each file in one. So if > it is really only historic data you need CVS, SVN, RCS etc may work. > From wprins at gmail.com Mon May 21 23:48:13 2012 From: wprins at gmail.com (Walter Prins) Date: Mon, 21 May 2012 22:48:13 +0100 Subject: [Tutor] While learning Py: To IDE or not to IDE? In-Reply-To: <4FBA4E77.60006@gmail.com> References: <4FBA4E77.60006@gmail.com> Message-ID: Hi, On 21 May 2012 15:17, bob gailer wrote: > There are numerous IDES for Python that run on Linux systems (most are > free). > I'd like to add that if/when you do decide to pick up an IDE, I suggest you try Eclipse. For one it will allow you to use it for other languages also (Java, C++, et al). Have a look at the following video demonstrating some of the PyDev features in the following video (also a little demonstration how to develop TDD "red, green, refactor" style) : http://pydev.org/video_pydev_20.html Unit testing (PyUnit & friends), Source code style and problem checking (Pylint), code test coverage (Coverage.py) are all usable from and integrated reasonably well, making life just that little bit easier. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue May 22 00:07:45 2012 From: emile at fenx.com (Emile van Sebille) Date: Mon, 21 May 2012 15:07:45 -0700 Subject: [Tutor] Datetime Integer Array In-Reply-To: References: Message-ID: On 5/21/2012 1:04 PM Jeremy Traurig said... > Hello, > > I am reading a data file with a string time stamp as the first column, > example below: > > '03/10/2010 02:00:00' > '03/10/2010 02:10:00' > '03/10/2010 02:20:00' > '03/10/2010 02:30:00' > etc to n number of rows. > > I'm using the numpy function genfromtxt to read this data: > > import numpy as np > datetime_IN = np.genfromtxt('SIL633_original.txt', delimiter='\t', > skip_header=141, dtype='|S19', > usecols=0) > > Now I have a variable called datetime_IN which is an array of datetime > strings to the nth row. I'd like to convert this strings to a numpy > array of integers where each column represents a value of time. > For example, using the same values above, i want an array of integers > to look like this: > > 3,10,2010,2,0,0 > 3,10,2010,2,10,0 > 3,10,2010,2,20,0 > 3,10,2010,2,30,0 > etc to n number of rows. Using only builtin python functions you can do this as follows: >>> source = ['03/10/2010 02:00:00', ... '03/10/2010 02:10:00', ... '03/10/2010 02:20:00', ... '03/10/2010 02:30:00'] >>> >>> for ts in source: ... print ts, [ int(ii) for ii in ts.replace("/","").replace(":","").split() ] ... 03/10/2010 02:00:00 [3, 10, 2010, 2, 0, 0] 03/10/2010 02:10:00 [3, 10, 2010, 2, 10, 0] 03/10/2010 02:20:00 [3, 10, 2010, 2, 20, 0] 03/10/2010 02:30:00 [3, 10, 2010, 2, 30, 0] HTH, Emile From robertvstepp at gmail.com Tue May 22 05:26:37 2012 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 21 May 2012 22:26:37 -0500 Subject: [Tutor] Optimally configuring Emacs for W7-64bit and Python Message-ID: Many thanks for all of the helpful input to my original questions. The deciding factors came down to the fact that GNU Emacs, vintage year 2001, is available on the Sun Blade at work, I already own the book "Learning GNU Emacs" and it would be nice to have my fingers trained the same way for both work and home study. What is the best way for me to get my W7-64bit laptop configured for Python programming? My consultations with the Google oracle have yielded inconclusive results this evening, though I confess I am quite tired, so I may be missing the obvious. -- Cheers! boB From brian.van.den.broek at gmail.com Tue May 22 10:58:49 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Tue, 22 May 2012 10:58:49 +0200 Subject: [Tutor] Optimally configuring Emacs for W7-64bit and Python In-Reply-To: References: Message-ID: On 22 May 2012 06:58, "boB Stepp" wrote: > > Many thanks for all of the helpful input to my original questions. The > deciding factors came down to the fact that GNU Emacs, vintage year > 2001, is available on the Sun Blade at work, I already own the book > "Learning GNU Emacs" and it would be nice to have my fingers trained > the same way for both work and home study. > > What is the best way for me to get my W7-64bit laptop configured for > Python programming? My consultations with the Google oracle have > yielded inconclusive results this evening, though I confess I am quite > tired, so I may be missing the obvious. boB, Having been the emacs advocate, I feel some obligation to try to help. However, 1) my last Windows use is a dim memory, and 2) I am just now embarking on a period of travel and uncertain connectivity. So, apologies, but I will not be able to provide much (any?) help in the immediate future. (If emacs seems like you will stick to it, do have a look at orgmode.) Best and good luck, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkidken at gmail.com Tue May 22 14:52:24 2012 From: beachkidken at gmail.com (Ken G.) Date: Tue, 22 May 2012 08:52:24 -0400 Subject: [Tutor] Using a Blackjack Chart... Message-ID: <4FBB8C08.7040302@gmail.com> I would like to create a Python program in the manner of an using flash card format. That is, a question is asked and you can respond according and you will be notify if you are correct or incorrect. Using such format stated above, I would like to create a Blackjack program. I wish to utilize a 'cheat sheet chart' format that provide the proper response. The chart has 10 rows across, being identified as the dealer's up card, from 2 to 10 plus Ace. There are 23 columns indicating the player's cards being shown, such as 8 to 12, 13-16, 17+, A2 to A8 and 2,2 to A,A. Each row and column would indicate either Hit, DD (Double), S (Stand) and SP (Split). How can I best utilize such a chart in the Python program? Lists, Tuples, Dictionary or perhaps, a database format such as SQL? I tried using MySQLdb but was unable to use it since I am using Ubuntu 10.04.4 (Linux) as my main OS. My other OS is Windows XP. Thank you for any suggestions or guidances. Ken From joel.goldstick at gmail.com Tue May 22 15:08:32 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 22 May 2012 09:08:32 -0400 Subject: [Tutor] Using a Blackjack Chart... In-Reply-To: <4FBB8C08.7040302@gmail.com> References: <4FBB8C08.7040302@gmail.com> Message-ID: On Tue, May 22, 2012 at 8:52 AM, Ken G. wrote: > I would like to create a Python program in the manner of an using flash card > format. > That is, a question is asked and you can respond according and you will be > notify if > you are correct or incorrect. > > Using such format stated above, I would like to create a Blackjack program. > ?I wish > to utilize a 'cheat sheet chart' format that provide the proper response. > > The chart has 10 rows across, being identified as the dealer's up card, from > 2 to > 10 plus Ace. > > There are 23 columns indicating the player's cards being shown, such as 8 to > 12, > 13-16, 17+, A2 to A8 and 2,2 to A,A. > > Each row and column would indicate either Hit, DD (Double), S (Stand) and SP > (Split). > > How can I best utilize such a chart in the Python program? ?Lists, Tuples, > Dictionary > or perhaps, a database format such as SQL? ?I tried using MySQLdb but was > unable > to use it since I am using Ubuntu 10.04.4 (Linux) as my main OS. ?My other > OS is > Windows XP. > > Thank you for any suggestions or guidances. > > Ken > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor There are lots of google results for python card games -- have you explored those? As to mysql it works fine on linux. If your system doesn't have mysql you can use synaptic package manager to get it Look for mysql-server, mysql-client and python-mysqldb import MySQLdb as mdb -- Joel Goldstick From andipersti at gmail.com Tue May 22 20:01:42 2012 From: andipersti at gmail.com (Andreas Perstinger) Date: Tue, 22 May 2012 20:01:42 +0200 Subject: [Tutor] Datetime Integer Array In-Reply-To: References: Message-ID: <20120522200142.d57518048319f2a2639a3b78@gmail.com> On Mon, 21 May 2012 13:04:26 -0700 Jeremy Traurig wrote: > I have already tried creating a numpy array of integers using this > code: > > import time > time_format = %m/%d/%Y %H:%M:%S > for x in range(len(datetime_IN)): > junk = time.strptime(datetime[x],time_format) > junk2 = [y for y in junk] > > The above code works in general No, this code doesn't work at all because there are two errors in it (syntax error in line 2 and name error in line 4). So in the future please copy&paste your code and don't retype it. > the same number of rows as datetime_IN, and I understand it doesn't > because the previous data in junk2 is lost. I'd like to build the > junk2 array but I'm not sure how. Currently, as you've noticed, you overwrite junk2 with each iteration. You need to append junk2 (which represents one row) to an array: import time time_format = "%m/%d/%Y %H:%M:%S" datetime_IN = ['03/10/2010 02:00:00', '03/10/2010 02:10:00', '03/10/2010 02:20:00', '03/10/2010 02:30:00'] datetime_NEW = [] for d in datetime_IN: junk = time.strptime(d, time_format) junk2 = [y for y in junk] datetime_NEW.append(junk2) You will notice that there is more information than you want in each row and the items are not in the order you've specified. So you probably want to construct each row manually in the order you need: datetime_NEW = [] for d in datetime_IN: d = time.strptime(d, time_format) datetime_NEW.append([d.tm_mon, d.tm_mday, d.tm_year, d.tm_hour, d.tm_min, d.tm_sec]) HTH, Andreas From alan.gauld at btinternet.com Wed May 23 00:25:53 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 May 2012 23:25:53 +0100 Subject: [Tutor] Optimally configuring Emacs for W7-64bit and Python In-Reply-To: References: Message-ID: On 22/05/12 04:26, boB Stepp wrote: > 2001, is available on the Sun Blade at work, I already own the book > "Learning GNU Emacs" and it would be nice to have my fingers trained > the same way for both work and home study. That's a fair reason and emacs will work for any of your languages and incorporates many of the features of an IDE albeit a text based one... > What is the best way for me to get my W7-64bit laptop configured for > Python programming? Install python mode. Learn how to get the python shell running inside emacs. Learn how to get a cmd shell running inside emacs Learn how to do split windows After that emacs is a giant application with everything customisable by the user so its down to your preferences. Colour schemes, key combinations, how much automation (keyword completion etc) is all under your control. One extra that I would strongly encourage for working with Python on windows is to supplement the emacs debugger mode with winpdb. It can be had for Linux too, I don't know about Solaris. But I think your Solaris is non GUI based anyway as I recall? So that won't matter. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From questions.anon at gmail.com Wed May 23 00:28:15 2012 From: questions.anon at gmail.com (questions anon) Date: Wed, 23 May 2012 08:28:15 +1000 Subject: [Tutor] table to dictionary and then analysis In-Reply-To: <1337338495.15934.212.camel@launcelot.winder.org.uk> References: <4FB1CF99.8050609@gmail.com> <1337074605.18804.130.camel@launcelot.winder.org.uk> <1337167648.590.6.camel@lionors.winder.org.uk> <1337239627.15934.94.camel@launcelot.winder.org.uk> <20120517093500.GA11535@ando> <1337338495.15934.212.camel@launcelot.winder.org.uk> Message-ID: thanks for all of the responses, has been really helpful On Fri, May 18, 2012 at 8:54 PM, Russel Winder wrote: > On Thu, 2012-05-17 at 19:35 +1000, Steven D'Aprano wrote: > > On Thu, May 17, 2012 at 08:27:07AM +0100, Russel Winder wrote: > > > > > Should we be promoting use of the format method in strings rather than > > > the % operator? % is deprecated now. > > > > It most certainly is not. > > > > There are no plans to deprecate the string % operator any time in the > > foreseeable future. It may, hypothetically, wither away from lack of use > > OK I am clearly wrong with the statement I made. I had assumed the > statement (*) that it would be deprecated in 3.1 was carried through, I > had not actually checked the reality in the 3.1 and 3.2 differences > documents. My apologies for misdirection, thanks for pulling me up on > this. > > > (*) There is no statement of when deprecation would happen in PEP 3101 > itself http://www.python.org/dev/peps/pep-3101/ but there is an explicit > statement in > > http://docs.python.org/release/3.0/whatsnew/3.0.html#pep-3101-a-new-approach-to-string-formattingwhich clearly didn't happen even though it led to a lot of people thinking > it would. > > -- > Russel. > > ============================================================================= > Dr Russel Winder t: +44 20 7585 2200 voip: > sip:russel.winder at ekiga.net > 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk > London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder > > > _______________________________________________ > 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 brad.hudson at gmail.com Wed May 23 01:30:15 2012 From: brad.hudson at gmail.com (Brad Hudson) Date: Tue, 22 May 2012 18:30:15 -0500 Subject: [Tutor] Optimally configuring Emacs for W7-64bit and Python In-Reply-To: References: Message-ID: Aside from emacs, vim is a nice editor that can be used across UNIX/Linux/Windows OS. It is also more friendly to learn/configure than emacs (install it, type "vim" at a shell/cmd.exe prompt and use the help that comes with it for customization). It comes by default on most modern UNIX/Linux OS. Similar to emacs it also has a wealth of plugins available. On Tue, May 22, 2012 at 5:25 PM, Alan Gauld wrote: > On 22/05/12 04:26, boB Stepp wrote: > > 2001, is available on the Sun Blade at work, I already own the book >> "Learning GNU Emacs" and it would be nice to have my fingers trained >> the same way for both work and home study. >> > > That's a fair reason and emacs will work for any of your languages and > incorporates many of the features of an IDE albeit a text based one... > > What is the best way for me to get my W7-64bit laptop configured for >> Python programming? >> > > Install python mode. > Learn how to get the python shell running inside emacs. > Learn how to get a cmd shell running inside emacs > Learn how to do split windows > > After that emacs is a giant application with everything customisable > by the user so its down to your preferences. Colour schemes, key > combinations, how much automation (keyword completion etc) is all > under your control. > > One extra that I would strongly encourage for working with Python on > windows is to supplement the emacs debugger mode with winpdb. It can be had > for Linux too, I don't know about Solaris. But I think your Solaris is non > GUI based anyway as I recall? So that won't matter. > > hth > -- > Alan G > 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 robertvstepp at gmail.com Wed May 23 04:13:51 2012 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 22 May 2012 21:13:51 -0500 Subject: [Tutor] Optimally configuring Emacs for W7-64bit and Python In-Reply-To: References: Message-ID: > Install python mode. > Learn how to get the python shell running inside emacs. > Learn how to get a cmd shell running inside emacs > Learn how to do split windows On some of the pages I recall looking at, it was mentioned that Emacs comes with two major modes for Python. It was not clear to me which one should be preferred. Also, mention was made of several extensions to Emacs, that provided things like code completion, etc. It was not clear to me if these would work with Windows and it was not clear to me if these were desirable or not. So, I was curious about whether anyone had definite recommendations about these things. > One extra that I would strongly encourage for working with Python on windows > is to supplement the emacs debugger mode with winpdb. It can be had for > Linux too, I don't know about Solaris. But I think your Solaris is non GUI > based anyway as I recall? So that won't matter. Now I just looked at winpdb and it states that it must have wxPython installed. So, I went to its website and the latest version is 2.8.12.1. If the versions of wxPython parallels that of Python then this means that version 3.x won't be supported. Is this correct? Now it did mention that there was a console version of winpdb that did not require wxPython, but would this be what you intended for me, Alan? The Solaris at work is Solaris 8 and has many GUI-based apps, but I am forced to use whatever is on the computers. Normally, we are not allowed to add any software to these workstations as they are radiation oncology planning stations with associated FDA approvals "as sold". At the main site where I work we have three planning stations, one an 810X, one a Sun Blade and the other is even older hardware (I can't remember its exact designation.). The 810X is running on Solaris 10 while the latter two have been upgraded to Solaris 8. The Solaris 8 machines do not have Python installed! Emacs is version 20.7.1 and the Perl I've been using is version 5.005_03. The Solaris 10 machine has Python 2.4.4, but this is of no use to me as the same scripts have to be able to run on all three machines. However, there are plans after July 1st to upgrade all three machines to thin clients connected to an enterprise server. Hopefully if this actually happens then Python will be available on everything. Cheers! boB From robertvstepp at gmail.com Wed May 23 04:17:44 2012 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 22 May 2012 21:17:44 -0500 Subject: [Tutor] Optimally configuring Emacs for W7-64bit and Python In-Reply-To: References: Message-ID: but I will not be able to provide much (any?) help in the immediate future. > > (If emacs seems like you will stick to it, do have a look at orgmode.) > Brian, does org-mode amount to a personal information manager? What are the things you especially like about it? Cheers! boB From ganu.ullu at gmail.com Wed May 23 06:13:16 2012 From: ganu.ullu at gmail.com (=?UTF-8?B?YW5rdXIgfiDgpIXgpILgpJXgpYHgpLA=?=) Date: Wed, 23 May 2012 09:43:16 +0530 Subject: [Tutor] Query with SOAP request generation, which other modules can be used. Message-ID: Dear Pythoneers, We want to butile the SOAP request request in below manner. - In header we want to pass the wsse auth part and custom transref section and both has different xmlns. ------------------------------------------------------------ PORTAL 123456 123456 user pass 1870000000 ------------------------------------------------------------ Currently we are using pysimplesoap ( http://code.google.com/p/pysimplesoap/) module for this. The current python code is attached. But we are not able to pass the custom xmlns ( for bil and for com - the very first line ) with pysimplesoap module. *Any idea which other module we have to explore for generating the SOAP request like above.* Thank You, Ankur. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- from pysimplesoap.client import SoapClient import sys,traceback client = SoapClient( location="http://www.abc.com/ABC/Billing", action = "http://www.abc.org/Service/getBill", namespace="http://www.abc.org/Service/Billing.wsdl", trace=True) client['wsse:Security'] = { 'wsse:UsernameToken': { 'wsse:Username': 'username', 'wsse:Password': 'password', } } client['com:TransRef'] = { 'com:SystemId': 'PORTAL', 'com:TxID': '20012001161378998', 'com:BID': '123456789' } try: response = client.getBill(AccountID=123456) print response except: errortrace = ''.join(traceback.format_exception(*sys.exc_info())) print("Unexpected error: %s" % (errortrace,)) From alan.gauld at btinternet.com Wed May 23 11:14:28 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 May 2012 10:14:28 +0100 Subject: [Tutor] Optimally configuring Emacs for W7-64bit and Python In-Reply-To: References: Message-ID: On 23/05/12 03:13, boB Stepp wrote: > to Emacs, that provided things like code completion, etc. It was not > clear to me if these would work with Windows Yes, emavs is prettty much built on its own environment based on eLisp. So mostfeatures of emacs work regardless of OS etc. Its only where emacs integrates with the OS that differencews emerge. For example on Unix you can run a grep from emacs and then step through the results from inside emacs. Or if you compile a program the errors can be stepped through on Unix because the compilers conform to the standard reporting format, but on windows compilers don't typically share an error format. So you have to do a lot more app specific config on Windows than with Unix. > Now I just looked at winpdb and it states that it must have wxPython > installed. > 2.8.12.1. If the versions of wxPython parallels that of Python then > this means that version 3.x won't be supported. Is this correct? They don;t track Python version numbers but a quick look suggests that you are right there is no v3 version of wxPython yet. Which is surprising and I thought there was... FWIW the mapping of release to Python version is here: http://www.wxpython.org/download.php#stable > it did mention that there was a console version of winpdb that did not > require wxPython, but would this be what you intended for me, Alan? Nope, it was the GUI version. I've never tried the console version, its probably worth a go since the native Python pdb debugger is a bit primitive! OTOH using a debugger with Python is a relatively rare event, simple print statements and the >>> prompt usually suffice. > The Solaris at work is Solaris 8 and has many GUI-based apps, but I am > forced to use whatever is on the computers. Ah, ok, for some reason I thought you only had ssh access. I must be getting my threads crossed :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bala.biophysics at gmail.com Wed May 23 11:51:42 2012 From: bala.biophysics at gmail.com (Bala subramanian) Date: Wed, 23 May 2012 11:51:42 +0200 Subject: [Tutor] removing sq. of items. Message-ID: Friends, While iterating through each list item and printing/writing it, why does the sq. brackets get printed/written to the file. Just a small eg.code is given below. >>>N=100 >>> myl=range(1,100+1) >>> new=[myl[i:i+15] for i in range(0, len(myl),15)] >>> for x in new: print x Thanks, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From tvssarma.omega9 at gmail.com Wed May 23 11:59:20 2012 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Wed, 23 May 2012 15:29:20 +0530 Subject: [Tutor] removing sq. of items. In-Reply-To: References: Message-ID: On 23 May 2012 15:21, Bala subramanian wrote: > Friends, > While iterating through each list item and printing/writing it, why does > the sq. brackets get printed/written to the file. Just a small eg.code is > given below. > > >>>N=100 > >>> myl=range(1,100+1) > >>> new=[myl[i:i+15] for i in range(0, len(myl),15)] > >>> for x in new: print x > > When you slice 'myl[i:i+15]' you are creating a new list and adding that to 'new'. So essentially you are nesting new lists within a list comprehension. Hope that helps! > Thanks, > Bala > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- An monkey typed up this email. Please excuse him if he made a stupid error! -------------- next part -------------- An HTML attachment was scrubbed... URL: From bala.biophysics at gmail.com Wed May 23 12:07:13 2012 From: bala.biophysics at gmail.com (Bala subramanian) Date: Wed, 23 May 2012 12:07:13 +0200 Subject: [Tutor] removing sq. of items. In-Reply-To: References: Message-ID: Hi, I infact want write each of the item in the sliced list to a file. On Wed, May 23, 2012 at 11:59 AM, Sarma Tangirala wrote: > > > On 23 May 2012 15:21, Bala subramanian wrote: > >> Friends, >> While iterating through each list item and printing/writing it, why does >> the sq. brackets get printed/written to the file. Just a small eg.code is >> given below. >> >> >>>N=100 >> >>> myl=range(1,100+1) >> >>> new=[myl[i:i+15] for i in range(0, len(myl),15)] >> >>> for x in new: print x >> >> > When you slice 'myl[i:i+15]' you are creating a new list and adding that > to 'new'. So essentially you are nesting new lists within a > list comprehension. > > Hope that helps! > > >> Thanks, >> Bala >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > An monkey typed up this email. Please excuse him if he made a stupid error! > -- C. Balasubramanian -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed May 23 13:27:51 2012 From: d at davea.name (Dave Angel) Date: Wed, 23 May 2012 07:27:51 -0400 Subject: [Tutor] removing sq. of items. In-Reply-To: References: Message-ID: <4FBCC9B7.3010903@davea.name> On 05/23/2012 06:07 AM, Bala subramanian wrote: > Hi, > I infact want write each of the item in the sliced list to a file. This line is top-posted. Please put your remarks *after* the part you've quoted. There isn't one slice, but many of them. So you have a list of lists. > > On Wed, May 23, 2012 at 11:59 AM, Sarma Tangirala > wrote: >> >> On 23 May 2012 15:21, Bala subramanian wrote: >> >>> Friends, >>> While iterating through each list item and printing/writing it, why does >>> the sq. brackets get printed/written to the file. Just a small eg.code is >>> given below. >>> >>>>>> N=100 >>>>>> myl=range(1,100+1) >>>>>> new=[myl[i:i+15] for i in range(0, len(myl),15)] >>>>>> for x in new: print x Each item in new is a list, since you created it with a slice. So x is a list, and when you print it, you get the default representation, including the square brackets. If you want to print the individual items within x, separated by some marker of your choice, then you have to write such code. Instead of print x, you might want for item in x: print item, This would show the items separated by a space. Or you might want them separated by a comma: print ",".join(x) -- DaveA From wprins at gmail.com Wed May 23 13:31:46 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 23 May 2012 12:31:46 +0100 Subject: [Tutor] removing sq. of items. In-Reply-To: References: Message-ID: On 23 May 2012 11:07, Bala subramanian wrote: > Hi, > I infact want write each of the item in the sliced list to a file. You don't have any actual files in your program so I'm assuming by file you mean "each item is printed to standard output"? Anyway, you might try the following which is I think what you're trying to achieve.: N=100 myl=range(1,100+1) new=[] for i in range(0, len(myl),15): new.extend(myl[i:i+15]) for x in new: print x Ultimately the new list contains the same elements as the old list so by itself isn't very useful except to show that the split/slice and merge operations don't lose items/data from the original list. Walter From ramit.prasad at jpmorgan.com Wed May 23 15:56:34 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 23 May 2012 13:56:34 +0000 Subject: [Tutor] Using a Blackjack Chart... In-Reply-To: References: <4FBB8C08.7040302@gmail.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47409353FA5@SCACMX008.exchad.jpmchase.net> [snip] > > How can I best utilize such a chart in the Python program? Lists, > Tuples, > > Dictionary > > or perhaps, a database format such as SQL? I tried using MySQLdb but > was > > unable > > to use it since I am using Ubuntu 10.04.4 (Linux) as my main OS. My > other > > OS is > > Windows XP. [snip] > As to mysql it works fine on linux. If your system doesn't have mysql > you can use synaptic package manager to get it Look for > mysql-server, mysql-client and python-mysqldb > > import MySQLdb as mdb Or even more simply, why not use SQLite? It is built into Python and will be portable for anywhere that Python is. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From beachkidken at gmail.com Wed May 23 16:39:58 2012 From: beachkidken at gmail.com (Ken G.) Date: Wed, 23 May 2012 10:39:58 -0400 Subject: [Tutor] Using a Blackjack Chart... In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47409353FA5@SCACMX008.exchad.jpmchase.net> References: <4FBB8C08.7040302@gmail.com> <5B80DD153D7D744689F57F4FB69AF47409353FA5@SCACMX008.exchad.jpmchase.net> Message-ID: <4FBCF6BE.3040300@gmail.com> On 05/23/2012 09:56 AM, Prasad, Ramit wrote: > How can I best utilize such a chart in the Python program? Lists, >> Tuples, Dictionary or perhaps, a database format such as SQL? I tried using MySQLdb but >> was unable to use it since I am using Ubuntu 10.04.4 (Linux) as my main OS. My >> other OS is Windows XP. > >> As to mysql it works fine on linux. If your system doesn't have mysql >> you can use synaptic package manager to get it Look for >> mysql-server, mysql-client and python-mysqldb >> >> import MySQLdb as mdb > Or even more simply, why not use SQLite? It is built into Python > and will be portable for anywhere that Python is. > > Ramit > > Thank you. I am looking into SQLite3. It has a steep learning curve for me. I'm still playing with it. Again, thanks. Ken From emailkgnow at gmail.com Wed May 23 18:11:15 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Wed, 23 May 2012 19:11:15 +0300 Subject: [Tutor] sqlite3 question Message-ID: hi all, I'm using Python 3 and have read that you need sqlite to be installed to use the sqlite3 module, but when it is imported it seems to work ok. so, do you need to install it? also, when you create the database where is it saved? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed May 23 18:51:41 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 23 May 2012 12:51:41 -0400 Subject: [Tutor] sqlite3 question In-Reply-To: References: Message-ID: On Wed, May 23, 2012 at 12:11 PM, Khalid Al-Ghamdi wrote: > hi all, > > I'm using Python 3 and have read that you need sqlite to be installed to use > the sqlite3 module, but when it is imported it seems to work ok. so, do you > need to install it? also, when you create the database where is it saved? > > > thanks Here's one of the top listings from google for sqlite3 python http://greeennotebook.com/2010/06/how-to-use-sqlite3-from-python-introductory-tutorial/ See that the database is kept in the file /home/user/mydatabase.db >>> import sqlite3 >>> mydatabase="/home/user/.mydatabase.db" >>> connection=sqlite3.connect(mydatabase) >>> cursor=connection.cursor() >>> cursor.execute('CREATE TABLE mytable (Id INTEGER PRIMARY KEY, Date TEXT, Entry TEXT)') >>> connection.commit() >>> cursor.close() >>> quit() -- Joel Goldstick From beachkidken at gmail.com Wed May 23 19:16:34 2012 From: beachkidken at gmail.com (Ken G.) Date: Wed, 23 May 2012 13:16:34 -0400 Subject: [Tutor] sqlite3 question In-Reply-To: References: Message-ID: <4FBD1B72.3060201@gmail.com> On 05/23/2012 12:51 PM, Joel Goldstick wrote: > On Wed, May 23, 2012 at 12:11 PM, Khalid Al-Ghamdi wrote: >> hi all, >> >> I'm using Python 3 and have read that you need sqlite to be installed to use >> the sqlite3 module, but when it is imported it seems to work ok. so, do you >> need to install it? also, when you create the database where is it saved? >> >> >> thanks > Here's one of the top listings from google for sqlite3 python > > http://greeennotebook.com/2010/06/how-to-use-sqlite3-from-python-introductory-tutorial/ > > See that the database is kept in the file /home/user/mydatabase.db > >>>> import sqlite3 >>>> mydatabase="/home/user/.mydatabase.db" >>>> connection=sqlite3.connect(mydatabase) >>>> cursor=connection.cursor() >>>> cursor.execute('CREATE TABLE mytable (Id INTEGER PRIMARY KEY, Date TEXT, Entry TEXT)') > >>>> connection.commit() >>>> cursor.close() >>>> quit() The file may be hidden due to the dot before the file name and may be located in the home directory of user. Ken From alan.gauld at btinternet.com Wed May 23 20:09:19 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 May 2012 19:09:19 +0100 Subject: [Tutor] Using a Blackjack Chart... In-Reply-To: <4FBCF6BE.3040300@gmail.com> References: <4FBB8C08.7040302@gmail.com> <5B80DD153D7D744689F57F4FB69AF47409353FA5@SCACMX008.exchad.jpmchase.net> <4FBCF6BE.3040300@gmail.com> Message-ID: On 23/05/12 15:39, Ken G. wrote: > Thank you. I am looking into SQLite3. It has a steep learning curve for > me. I'm still playing with it. I assume that means you are new to SQL databases in general? (Since SqLite is probably the easiest SQL database to use!) If so then learning SQL is quite a big task although you shouild get the basics quite quickly. However in case you haven't seen it there is a GUI interface to SQLite that allows yypou to create and populate databases quickly. It can save a lot of SQL typing. It can also do very basic query/report work too without any SQL. And for a little bit of SQL can do quite powerful things... It may be all you need... http://sourceforge.net/projects/sqlitebrowser/files/sqlitebrowser/2.0%20beta1/ Binaries for Windows and MacOS X, tarball for Linux. But it should be available to install from most Linux distro repositories too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed May 23 20:19:00 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 23 May 2012 19:19:00 +0100 Subject: [Tutor] sqlite3 question In-Reply-To: References: Message-ID: On 23/05/12 17:11, Khalid Al-Ghamdi wrote: > I'm using Python 3 and have read that you need sqlite to be installed to > use the sqlite3 module, but when it is imported it seems to work ok. The info is wrong. Unlike other SQL databases SQLite is not a server based system so there is nothing to install. It is just a set of functions in a library, which comes with Python. When you create a SQLite database it creates a file. All the tables and data are stored in that file. You can move your database to anotrher system just be copyting the file. This makes SQLite great for small( <1GB) databases but also ultimately limits its scalability and performance... > when you create the database where is it saved? Wherever you want it to be, you just specify the filename when creating it (or connecting to it). Either natively: $ sqlite3 /home/ag/data/employee.db or from Python: db = sqlite.connect('/home/ag/data/employee.db') See the database topic in my tutorial for some more extensive examples. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Thu May 24 02:37:19 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 May 2012 01:37:19 +0100 Subject: [Tutor] Query with SOAP request generation, which other modules can be used. In-Reply-To: References: Message-ID: On 23/05/2012 08:17, Ataulla S H wrote: > We can try suds its very lightweight soap client. > > Thanks > Ataulla SH > > On Wed, May 23, 2012 at 9:43 AM, ankur ~ ????? wrote: > >> Dear Pythoneers, >> >> We want to butile the SOAP request request in below manner. - >> >> In header we want to pass the wsse auth part and custom transref section >> and both has different xmlns. >> >> ------------------------------------------------------------ >> > xmlns:com="http://some.xmlns.org/.1.0/Common.xsd" xmlns:bil=" >> http://some.xmlns.org/Schema/Billing/1.0/Billing.xsd"> >> >> >> >> >> PORTAL >> 123456 >> 123456 >> >> >> >> >> user >> pass >> >> >> >> >> >> >> >> 1870000000 >> >> >> >> >> ------------------------------------------------------------ >> >> Currently we are using pysimplesoap ( >> http://code.google.com/p/pysimplesoap/) module for this. The current >> python code is attached. >> >> But we are not able to pass the custom xmlns ( for bil and for com - the >> very first line ) with pysimplesoap module. >> >> *Any idea which other module we have to explore for generating the SOAP >> request like above.* >> >> Thank You, >> Ankur. >> >> _______________________________________________ >> BangPypers mailing list >> BangPypers at python.org >> http://mail.python.org/mailman/listinfo/bangpypers >> >> > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > http://mail.python.org/mailman/listinfo/bangpypers What is the unladen airspeed velocity of a swallow in flight? -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Thu May 24 02:45:51 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 24 May 2012 01:45:51 +0100 Subject: [Tutor] removing sq. of items. In-Reply-To: <4FBCC9B7.3010903@davea.name> References: <4FBCC9B7.3010903@davea.name> Message-ID: On 23/05/2012 12:27, Dave Angel wrote: > On 05/23/2012 06:07 AM, Bala subramanian wrote: >> Hi, >> I infact want write each of the item in the sliced list to a file. > This line is top-posted. Please put your remarks *after* the part I agree entirely but top posting is getting worse and worse on all Python mailing lists. I complained several months ago but was told to shut up as it had previously caused too many flame wars. I guess there's two options, keep reminding peole or give up, I prefer the former but would certainly consider the other. -- Cheers. Mark Lawrence. From steve at pearwood.info Thu May 24 03:36:34 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 May 2012 11:36:34 +1000 Subject: [Tutor] Using a Blackjack Chart... In-Reply-To: <4FBB8C08.7040302@gmail.com> References: <4FBB8C08.7040302@gmail.com> Message-ID: <4FBD90A2.8060502@pearwood.info> Ken G. wrote: > I would like to create a Python program in the manner of an using flash > card format. > That is, a question is asked and you can respond according and you will > be notify if you are correct or incorrect. Is this supposed to be a graphical flashcard program? Or something you run at the terminal, using just text? That's much simpler. > Using such format stated above, I would like to create a Blackjack > program. I wish > to utilize a 'cheat sheet chart' format that provide the proper response. > > The chart has 10 rows across, being identified as the dealer's up card, > from 2 to 10 plus Ace. > > There are 23 columns indicating the player's cards being shown, such as > 8 to 12, 13-16, 17+, A2 to A8 and 2,2 to A,A. > > Each row and column would indicate either Hit, DD (Double), S (Stand) > and SP (Split). There's no need for the 200lb sledgehammer of a database to crack this peanut. Your data structure looks like a table, with a mere 10*23 = 230 cells. Just use a dictionary, with keys (dealer-up-card, player-cards) and values the response: table = { (2, 8): 'H', # dealer's card is 2, player's cards add to 8 (2, 9): 'H', ... (2, 21): 'S', (3, 8): 'H', ... } A text-only flash-card test would look something like this: import random def flash(): # Pick a random cell from the table. cell = random.choice(table.keys()) print "The dealer shows", cell[0] print "Your hand is", cell[1] response = raw_input("What do you do? ") if response == table[cell]: print "Correct" else: print "The dealer laughs cruelly as he takes your money." def main(): print "Blackjack flash-card program" print "Type Control-C at any time to halt." try: while True: flash() except KeyboardInterrupt: pass main() -- Steven From __peter__ at web.de Thu May 24 11:34:36 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 May 2012 11:34:36 +0200 Subject: [Tutor] sqlite3 question References: Message-ID: Alan Gauld wrote: > On 23/05/12 17:11, Khalid Al-Ghamdi wrote: > >> I'm using Python 3 and have read that you need sqlite to be installed to >> use the sqlite3 module, but when it is imported it seems to work ok. > > The info is wrong. > Unlike other SQL databases SQLite is not a server based system so there > is nothing to install. It is just a set of functions in a library, which > comes with Python. IIRC Python on Windows comes with its own sqlite library while on Linux it uses the systemwide libsqlite3. The dependency is handled by the package manager, so the user experience is the same. From beachkidken at gmail.com Thu May 24 14:04:59 2012 From: beachkidken at gmail.com (Ken G.) Date: Thu, 24 May 2012 08:04:59 -0400 Subject: [Tutor] Using a Blackjack Chart... In-Reply-To: <4FBD90A2.8060502@pearwood.info> References: <4FBB8C08.7040302@gmail.com> <4FBD90A2.8060502@pearwood.info> Message-ID: <4FBE23EB.70900@gmail.com> On 05/23/2012 09:36 PM, Steven D'Aprano wrote: > Ken G. wrote: >> I would like to create a Python program in the manner of an using >> flash card format. >> That is, a question is asked and you can respond according and you >> will be notify if you are correct or incorrect. > > Is this supposed to be a graphical flashcard program? > > Or something you run at the terminal, using just text? That's much > simpler. > > >> Using such format stated above, I would like to create a Blackjack >> program. I wish >> to utilize a 'cheat sheet chart' format that provide the proper >> response. >> >> The chart has 10 rows across, being identified as the dealer's up >> card, from 2 to 10 plus Ace. >> >> There are 23 columns indicating the player's cards being shown, such >> as 8 to 12, 13-16, 17+, A2 to A8 and 2,2 to A,A. >> >> Each row and column would indicate either Hit, DD (Double), S (Stand) >> and SP (Split). > > There's no need for the 200lb sledgehammer of a database to crack this > peanut. > > Your data structure looks like a table, with a mere 10*23 = 230 cells. > Just use a dictionary, with keys (dealer-up-card, player-cards) and > values the response: > > table = { > (2, 8): 'H', # dealer's card is 2, player's cards add to 8 > (2, 9): 'H', > ... > (2, 21): 'S', > (3, 8): 'H', > ... > } > > > A text-only flash-card test would look something like this: > > import random > > def flash(): > # Pick a random cell from the table. > cell = random.choice(table.keys()) > print "The dealer shows", cell[0] > print "Your hand is", cell[1] > response = raw_input("What do you do? ") > if response == table[cell]: > print "Correct" > else: > print "The dealer laughs cruelly as he takes your money." > > > > def main(): > print "Blackjack flash-card program" > print "Type Control-C at any time to halt." > try: > while True: > flash() > except KeyboardInterrupt: > pass > > > main() > Thank you Steven for saving me from database hell. LOL. Yes, it would be a text based program. I will start working on this approach today. Again, my thanks. Ken > > From ramit.prasad at jpmorgan.com Thu May 24 16:27:52 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 24 May 2012 14:27:52 +0000 Subject: [Tutor] Using a Blackjack Chart... In-Reply-To: <4FBE23EB.70900@gmail.com> References: <4FBB8C08.7040302@gmail.com> <4FBD90A2.8060502@pearwood.info> <4FBE23EB.70900@gmail.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47409359AE4@SCACMX008.exchad.jpmchase.net> > > There's no need for the 200lb sledgehammer of a database to crack this > > peanut. > > Thank you Steven for saving me from database hell. LOL. Yes, it would > be a text > based program. I will start working on this approach today. Again, my > thanks. This would be good practice as an intro to databases. They are a powerful tool and it would probably beneficial to learn it in the long run. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From beachkidken at gmail.com Thu May 24 17:20:22 2012 From: beachkidken at gmail.com (Ken G.) Date: Thu, 24 May 2012 11:20:22 -0400 Subject: [Tutor] Using a Blackjack Chart... In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47409359AE4@SCACMX008.exchad.jpmchase.net> References: <4FBB8C08.7040302@gmail.com> <4FBD90A2.8060502@pearwood.info> <4FBE23EB.70900@gmail.com> <5B80DD153D7D744689F57F4FB69AF47409359AE4@SCACMX008.exchad.jpmchase.net> Message-ID: <4FBE51B6.8090402@gmail.com> On 05/24/2012 10:27 AM, Prasad, Ramit wrote: >>> There's no need for the 200lb sledgehammer of a database to crack this >>> peanut. >> Thank you Steven for saving me from database hell. LOL. Yes, it would >> be a text based program. I will start working on this approach today. Again, my >> thanks. > This would be good practice as an intro to databases. They are a powerful > tool and it would probably beneficial to learn it in the long run. > > Ramit > Thanks. I have a bunch of tutorials printed out to study and learn. Ken From suryak at live.com Sat May 26 11:41:45 2012 From: suryak at live.com (Surya K) Date: Sat, 26 May 2012 15:11:45 +0530 Subject: [Tutor] How to deploy Django project in Google App Engine Message-ID: I wrote a Django project and would like to deploy on Google App Engine. I searched a lot on net and couldn't find a proper tutorial till now. So, can any one explain me?? I used Eclipse Indigo, Python 2.7 for developing... -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat May 26 15:40:03 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 26 May 2012 09:40:03 -0400 Subject: [Tutor] How to deploy Django project in Google App Engine In-Reply-To: References: Message-ID: <4FC0DD33.7020105@gmail.com> On 5/26/2012 5:41 AM, Surya K wrote: > I wrote a Django project and would like to deploy on Google App Engine. > > I searched a lot on net and couldn't find a proper tutorial till now. > So, can any one explain me?? Did you look at http://www.allbuttonspressed.com/blog/django/2010/01/Native-Django-on-App-Engine? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat May 26 15:41:19 2012 From: bgailer at gmail.com (bob gailer) Date: Sat, 26 May 2012 09:41:19 -0400 Subject: [Tutor] How to deploy Django project in Google App Engine In-Reply-To: References: Message-ID: <4FC0DD7F.3090604@gmail.com> On 5/26/2012 5:41 AM, Surya K wrote: > I wrote a Django project and would like to deploy on Google App Engine. also: https://developers.google.com/appengine/articles/django-nonrel -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.charonis at gmail.com Sun May 27 17:47:47 2012 From: s.charonis at gmail.com (Spyros Charonis) Date: Sun, 27 May 2012 16:47:47 +0100 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: References: Message-ID: Returning to this original problem, I have modified my program from a single long procedure to 3 functions which do the following: serialize_pipeline_model(f): takes as input a file, reads it and parses coordinate values (numerical entries in the file) into a list write_to_binary(): writes the generated list to a binary file (pickles it) read_binary(): unpickles the aggregate of merged lists that should be one large list. The code goes like so: ****** z_coords1 = [] def serialize_pipeline_model(f): .... ..... # z_coords1 = [] has been declared global global z_coords1 charged_groups = lys_charged_group + arg_charged_group + his_charged_group + asp_charged_group + glu_charged_group for i in range(len(charged_groups)): z_coords1.append(float(charged_groups[i][48:54])) #print z_coords1 return z_coords1 import pickle, shelve print '\nPickling z-coordinates list' def write_to_binary(): """ iteratively write successively generated z_coords1 to a binary file """ f = open("z_coords1.dat", "ab") pickle.dump(z_coords1, f) f.close() return def read_binary(): """ read the binary list """ print '\nUnpickling z-coordinates list' f = open("z_coords1.dat", "rb") z_coords1=pickle.load(f) print(z_coords1) f.close() return ### LOOP OVER DIRECTORY for f in os.listdir('/Users/spyros/Desktop/3NY8MODELSHUMAN/HomologyModels/'): serialize_pipeline_model(f) write_to_binary() read_binary() print '\n Z-VALUES FOR ALL CHARGED RESIDUES' print z_coords1 ****** The problem is that the list (z_coords1) returns as an empty list. I know the code works (too large to post here) in a procedural format (z_coords1 can be generated correctly), so as a diagnostic I included a print statement in the serialize function to see that the list that is generated for each of the 500 files. Short of some intricacy with the scopes of the program I may be missing, I am not sure why this is happening? Deos anybody have any ideas? Many thanks for your time. Best regards, Spyros On Fri, May 18, 2012 at 7:23 PM, Spyros Charonis wrote: > Dear Python community, > > I have a set of ~500 files which I would like to run a script on. My > script extracts certain information and > generates several lists with items I need. For one of these lists, I need > to combine the information from all > 500 files into one super-list. Is there a way in which I can iteratively > execute my script over all 500 files > and get them to write the list I need into a new file? Many thanks in > advance for your time. > > Spyros > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun May 27 18:47:04 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 May 2012 02:47:04 +1000 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: References: Message-ID: <4FC25A88.10404@pearwood.info> Spyros Charonis wrote: > The problem is that the list (z_coords1) returns as an empty list. I know > the code works (too large to post here) So you want us to diagnose a problem in code that we can't see? I admire your confidence in our powers of deduction. [...] > Short of some intricacy with the scopes of the program I may be missing, I > am not sure why this is happening? Deos anybody have > any ideas? Many thanks for your time. Your code's indentation is messed up again, which makes it impossible to guess what it actually does. Also, it is hard to understand what it *should* do. I'm not sure why you are writing data to a pickle file, only to read it back in again. You already have the data in memory, why not just keep it there? Also, your function serialize_pipeline_model is a misleading name. "Serialize" in computer science and programming means to take a data structure and turn it into a format suitable for saving to a file. You are doing the opposite, taking a file and reading it into a data structure. Here is my best guess as to what you might need: def get_zcoords(filename): """Read z coordinate data from the named file, and return it as a list.""" f = open(filename, 'r') zcoords = [] # ... stuff goes here that you don't show # ... I guess you read from the file and process it somehow # ... f.close() charged_groups = (lys_charged_group + arg_charged_group + his_charged_group + asp_charged_group + glu_charged_group ) for group in charged_groups: zcoords.append(float(group[48:54])) return zcoords location = '/Users/spyros/Desktop/3NY8MODELSHUMAN/HomologyModels/' zdata = [] for filename in os.listdir(location): zdata.extend(get_zcoords(filename)) print 'Z-VALUES FOR ALL CHARGED RESIDUES' print zdata If you need to keep those z coordinates for later use, you can pickle them, once, at the end of the process, and then later unpickle them. import pickle f = open("z_coords1.dat", "wb") pickle.dump(zdata, f) f.close() f = open("z_coords1.dat", "rb") zdata2 = pickle.load(f) f.close() assert zdata == zdata2, "error in pickle/unpickle round trip!" Does this help? -- Steven From kfm at stanford.edu Sun May 27 19:03:40 2012 From: kfm at stanford.edu (Kimberly McManus) Date: Sun, 27 May 2012 10:03:40 -0700 Subject: [Tutor] Tutor Digest, Vol 99, Issue 80 In-Reply-To: References: Message-ID: help On Sat, May 26, 2012 at 3:00 AM, 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. How to deploy Django project in Google App Engine (Surya K) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 26 May 2012 15:11:45 +0530 > From: Surya K > To: Python Tutor > Subject: [Tutor] How to deploy Django project in Google App Engine > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > > I wrote a Django project and would like to deploy on Google App Engine. > I searched a lot on net and couldn't find a proper tutorial till now. So, > can any one explain me?? > I used Eclipse Indigo, Python 2.7 for developing... > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20120526/14bd73f3/attachment-0001.html > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 99, Issue 80 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun May 27 19:49:40 2012 From: d at davea.name (Dave Angel) Date: Sun, 27 May 2012 13:49:40 -0400 Subject: [Tutor] Meaningless In-Reply-To: References: Message-ID: <4FC26934.80100@davea.name> On 05/27/2012 01:03 PM, Kimberly McManus wrote: > help > > Sure. Head for the nearest exit, stopping before each door to make sure it's not hot before opening it. Once outside, call 911 (or your local emergency number), and report the fire, being sure to describe your location exactly, and anything you know about the disaster. Do not re-enter the building till the emergency personnel have done their jobs. A few other clues: try a meaningful subject line, and some content that describes your actual problem. If you're posting a new problem, send the message directly to tutor at python.org, instead of doing a reply to the digest. And if you do insist on replying to the digest, at least remove the irrelevant content and fix the subject line. Which operating system was running when the fire started, and what version of Python were you trying to use to put it out? -- DaveA From brian.van.den.broek at gmail.com Sun May 27 22:37:24 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Sun, 27 May 2012 22:37:24 +0200 Subject: [Tutor] Meaningless In-Reply-To: <4FC26934.80100@davea.name> References: <4FC26934.80100@davea.name> Message-ID: On 27 May 2012 20:52, "Dave Angel" wrote: > > On 05/27/2012 01:03 PM, Kimberly McManus wrote: > > help > > > > > > Sure. Head for the nearest exit, stopping before each door to make sure > it's not hot before opening it. > Hi Kimberly, While I share Dave's sadness at the general decline of list conduct (not a problem special to this list), and got a chuckle out of his message, I suspect your message was an honest mistake rather than what Dave took it to be. Reading >, via email, send a message with subject or body 'help' to tutor-request at python.org and following it with a bit more care should sort you out. HTH, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun May 27 23:29:29 2012 From: d at davea.name (Dave Angel) Date: Sun, 27 May 2012 17:29:29 -0400 Subject: [Tutor] Meaningless In-Reply-To: References: <4FC26934.80100@davea.name> Message-ID: <4FC29CB9.5060208@davea.name> On 05/27/2012 04:37 PM, Brian van den Broek wrote: > On 27 May 2012 20:52, "Dave Angel" wrote: >> >> On 05/27/2012 01:03 PM, Kimberly McManus wrote: >>> help >>> >>> >> >> Sure. Head for the nearest exit, stopping before each door to make sure >> it's not hot before opening it. >> > > Hi Kimberly, > > While I share Dave's sadness at the general decline of list conduct (not a > problem special to this list), and got a chuckle out of his message, I > suspect your message was an honest mistake rather than what Dave took it to > be. Reading > >> , via email, send a message with subject or body 'help' to > tutor-request at python.org > > and following it with a bit more care should sort you out. > > HTH, > > Brian vdB > Thanks Brian, it never occurred to me that the 'help' was was intended for the administration side of the list. I feel embarassed, though I'm glad you at least got a chuckle out of it. Kimberly, I hope I didn't put you off joining us. Please feel free to jump in when you have a question or comment about Python. -- DaveA From brian.van.den.broek at gmail.com Sun May 27 23:45:46 2012 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Sun, 27 May 2012 23:45:46 +0200 Subject: [Tutor] [OT] Re: Optimally configuring Emacs for W7-64bit and Python In-Reply-To: References: Message-ID: On 23 May 2012 05:17, "boB Stepp" wrote: > > but I will not be able to provide much (any?) help in the immediate future. > > > > (If emacs seems like you will stick to it, do have a look at orgmode.) > > > > Brian, does org-mode amount to a personal information manager? What > are the things you especially like about it? > > Cheers! > boB Hi boB, Org-mode is a lot of things. It is an outliner, a PIM, a brain-dump, a blog engine, a website generator, a literate programming tool, it embeds a simple DB and a featurefull spreadsheet, etc. I expect it shall soon achieve sentience. I like it because it is a plain text PIM that allows me to arrange my data as I want it, to quickly and flexibly capture it, and because it lets me employ my emacs-fu on my digital brain. I'd be happy to answer any further questions you might have. But, 1) I won't be prompt due to travel, and 2) if you write about org-mode, let us go off-list as we've strayed from tutor's purpose. Best, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From robertvstepp at gmail.com Mon May 28 00:19:18 2012 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 27 May 2012 17:19:18 -0500 Subject: [Tutor] [OT] Re: Optimally configuring Emacs for W7-64bit and Python In-Reply-To: References: Message-ID: > I'd be happy to answer any further questions you might have. But, 1) I won't > be prompt due to travel, and 2) if you write about org-mode, let us go > off-list as we've strayed from tutor's purpose. > Brian, my primary question(s) are how to best configure Emacs for Python development. Is the existing major mode for Python sufficient for my needs in your opinion? When I have done some Googling, another major mode for Python has been mentioned. However, when I go to the Emacs help manual mention is only made of one. There has also been mention of what I presume are external Lisp modules that add additional functionality to either Python major mode. Are any of these worth pursuing? What type of configuration do you use? Currently I have deferred Python study to work through a few chapters of my Emacs books, so I can start to get comfortable with the keyboard movement and editing commands. Once I feel semi-comfortable with these then I will more thoroughly investigate configuration options for Python within Emacs. Hope you are enjoying your travel time! -- Cheers! boB From suryak at live.com Mon May 28 09:46:48 2012 From: suryak at live.com (Surya K) Date: Mon, 28 May 2012 13:16:48 +0530 Subject: [Tutor] How to deploy Django project in Google App Engine In-Reply-To: <4FC0DD33.7020105@gmail.com> References: , <4FC0DD33.7020105@gmail.com> Message-ID: Date: Sat, 26 May 2012 09:40:03 -0400 From: bgailer at gmail.com To: suryak at live.com CC: tutor at python.org Subject: Re: [Tutor] How to deploy Django project in Google App Engine On 5/26/2012 5:41 AM, Surya K wrote: I wrote a Django project and would like to deploy on Google App Engine. I searched a lot on net and couldn't find a proper tutorial till now. So, can any one explain me?? Did you look at http://www.allbuttonspressed.com/blog/django/2010/01/Native-Django-on-App-Engine? -- Bob Gailer 919-636-4239 Chapel Hill NC This seems to be a nice articles stating directly.. but I have one problem.1. In the test app, the project hierarchy is something like this:/ "project files" - setting.py, __init__.py, manage.py, etc.. However, the Django's dir hierarchy in my PC (i.e, Django 1.4) is quite different./ , manage.py - __init__.py, settings.py, views.py etc... so, where should I store those folders mentioned in the website http://www.allbuttonspressed.com/blog/django/2010/01/Native-Django-on-App-Engine? Thanks Surya -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon May 28 18:31:27 2012 From: bgailer at gmail.com (bob gailer) Date: Mon, 28 May 2012 12:31:27 -0400 Subject: [Tutor] How to deploy Django project in Google App Engine In-Reply-To: References: , <4FC0DD33.7020105@gmail.com> Message-ID: <4FC3A85F.7010403@gmail.com> On 5/28/2012 3:46 AM, Surya K wrote: > I have one problem. > 1. In the test app, the project hierarchy is something like this: > / "project files" - setting.py, __init__.py, manage.py, etc.. > However, the Django's dir hierarchy in my PC (i.e, Django 1.4) is quite different. > / , manage.py > - __init__.py, settings.py, views.py etc... > so, where should I store those folders mentioned in the website http://www.allbuttonspressed.com/blog/django/2010/01/Native-Django-on-App-Engine? AI am a relative newbie to Django - and I don't know. I recommend asking on a django mailing list such as django-users at googlegroups.com. > > > Thanks > > Surya > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From brendan_dornan at hotmail.com Tue May 29 00:15:24 2012 From: brendan_dornan at hotmail.com (Brendan Dornan ) Date: Mon, 28 May 2012 18:15:24 -0400 Subject: [Tutor] manipulating data to delete blank spaces Message-ID: Hi, I'd like to eliminate the no data fields in this XML file, since Tableau, the graphing software doesn't allow this. What would be the easiest way to approach this? I'm a complete neophyte, having gone through the first 15 chapters of the "Think Like a Computer Scientist." Long ways to go and appreciate any help. Cheers. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue May 29 00:30:58 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 May 2012 23:30:58 +0100 Subject: [Tutor] manipulating data to delete blank spaces In-Reply-To: References: Message-ID: On 28/05/12 23:15, Brendan Dornan wrote: > Hi, I?d like to eliminate the no data fields in this XML file, since > Tableau, the graphing software doesn?t allow this. What would be the > easiest way to approach this? I?m a complete neophyte, having gone > through the first 15 chapters of the ?Think Like a Computer Scientist.? > Long ways to go and appreciate any help. Cheers. Ummm, what XML file? Maybe it got stripped in transit, or maybe you forgot to attach it. Or if its big can you put it on a pastebin? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jduenas23 at gmail.com Tue May 29 04:00:48 2012 From: jduenas23 at gmail.com (Jeremy Duenas) Date: Mon, 28 May 2012 19:00:48 -0700 Subject: [Tutor] Concatenating Strings Message-ID: <000001cd3d3e$df2a9930$9d7fcb90$@gmail.com> I am trying to understand the point behind using the '+' character when trying to concatenate strings. I am new to learning Python and going through the book "Python Programming for Absolute Beginners 3rd ed." and do not understand the point or reason for concatenating strings. The reason I do not understand is when experimenting to understand what was being taught I wrote: print("\nThis string" "may not" "seem terr" "ibly impressive") then wrote: print("\nThis string" + "may not" + "seem terr" + "ibly impressive") and the both printed the same output..so why would I want to use '+' to add strings if there seems to be no reason too? -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue May 29 04:07:45 2012 From: d at davea.name (Dave Angel) Date: Mon, 28 May 2012 22:07:45 -0400 Subject: [Tutor] Concatenating Strings In-Reply-To: <000001cd3d3e$df2a9930$9d7fcb90$@gmail.com> References: <000001cd3d3e$df2a9930$9d7fcb90$@gmail.com> Message-ID: <4FC42F71.7040702@davea.name> On 05/28/2012 10:00 PM, Jeremy Duenas wrote: > I am trying to understand the point behind using the '+' character when > trying to concatenate strings. I am new to learning Python and going through > the book "Python Programming for Absolute Beginners 3rd ed." and do not > understand the point or reason for concatenating strings. The reason I do > not understand is when experimenting to understand what was being taught I > wrote: > > > print("\nThis string" "may not" "seem terr" "ibly impressive") > > > then wrote: > > > > print("\nThis string" + "may not" + "seem terr" + "ibly impressive") > > > > > and they both printed the same output..so why would I want to use '+' to add > strings if there seems to be no reason too? > > > As long as they're all literal strings, you can use the implicit concatenation. Or you can just make one longer string. Makes no difference, other than white space and sometimes prettiness. However, as soon as one of the strings is a variable of type "str" then you need the "plus sign." -- DaveA From brianjamesarb at gmail.com Tue May 29 04:22:11 2012 From: brianjamesarb at gmail.com (brian arb) Date: Mon, 28 May 2012 22:22:11 -0400 Subject: [Tutor] Concatenating Strings In-Reply-To: <000001cd3d3e$df2a9930$9d7fcb90$@gmail.com> References: <000001cd3d3e$df2a9930$9d7fcb90$@gmail.com> Message-ID: Your right that example from the book is a terrible example the point or the reason to concatenating strings. here is a simple usage of where concatenating strings prints out a simple string as a counter in a loop. >>> for i in range(5): ... print(str(i) + ' in for loop') ... 0 in for loop 1 in for loop 2 in for loop 3 in for loop 4 in for loop On Mon, May 28, 2012 at 10:00 PM, Jeremy Duenas wrote: > I am trying to understand the point behind using the ?+? character when > trying to concatenate strings. I am new to learning Python and going > through the book ?Python Programming for Absolute Beginners 3rd ed.? and > do not understand the point or reason for concatenating strings. The reason > I do not understand is when experimenting to understand what was being > taught I wrote:**** > > ** ** > > print(?\nThis string? ?may not? ?seem terr? ?ibly impressive?)**** > > ** ** > > then wrote:**** > > ** ** > > print(?\nThis string? + ?may not? + ?seem terr? + ?ibly impressive?)**** > > ** ** > > ** ** > > and the both printed the same output??so why would I want to use ?+? to > add strings if there seems to be no reason too?**** > > ** ** > > ** ** > > ** ** > > _______________________________________________ > 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 Tue May 29 04:07:20 2012 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 28 May 2012 19:07:20 -0700 Subject: [Tutor] Concatenating Strings In-Reply-To: <000001cd3d3e$df2a9930$9d7fcb90$@gmail.com> References: <000001cd3d3e$df2a9930$9d7fcb90$@gmail.com> Message-ID: <4FC42F58.2030303@alchemy.com> On 28-May-12 19:00, Jeremy Duenas wrote: > and the both printed the same output??so why would I want to use ?+? to > add strings if there seems to be no reason too? Juxtaposing strings only works with constants, which may be convenient in some cases, but it won't work at all when concatenating other string values. a="hello" b="world" a+b # will yield "helloworld" but a b # is a syntax error Using + is arguably preferable when you have a choice to make, since it works in all cases, including constants. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From jduenas23 at gmail.com Tue May 29 05:12:50 2012 From: jduenas23 at gmail.com (Jeremy Duenas) Date: Mon, 28 May 2012 20:12:50 -0700 Subject: [Tutor] Concatenating Strings In-Reply-To: References: <000001cd3d3e$df2a9930$9d7fcb90$@gmail.com> Message-ID: <003401cd3d48$ef2c2600$cd847200$@gmail.com> Thanks for the replays all your responses makes perfect sense looking at it that way. I agree the example in the book explained it simply, just made no sense as to why and how it is really used. What ya'll have explained to me makes sense and thank you. I can see the importance of it now. From: brian arb [mailto:brianjamesarb at gmail.com] Sent: Monday, May 28, 2012 7:22 PM To: Jeremy Duenas Cc: tutor at python.org Subject: Re: [Tutor] Concatenating Strings Your right that example from the book is a terrible example the point or the reason to concatenating strings. here is a simple usage of where concatenating strings prints out a simple string as a counter in a loop. >>> for i in range(5): ... print(str(i) + ' in for loop') ... 0 in for loop 1 in for loop 2 in for loop 3 in for loop 4 in for loop On Mon, May 28, 2012 at 10:00 PM, Jeremy Duenas wrote: I am trying to understand the point behind using the '+' character when trying to concatenate strings. I am new to learning Python and going through the book "Python Programming for Absolute Beginners 3rd ed." and do not understand the point or reason for concatenating strings. The reason I do not understand is when experimenting to understand what was being taught I wrote: print("\nThis string" "may not" "seem terr" "ibly impressive") then wrote: print("\nThis string" + "may not" + "seem terr" + "ibly impressive") and the both printed the same output..so why would I want to use '+' to add strings if there seems to be no reason too? _______________________________________________ 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 May 29 07:51:21 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 May 2012 15:51:21 +1000 Subject: [Tutor] Concatenating Strings In-Reply-To: <4FC42F58.2030303@alchemy.com> References: <000001cd3d3e$df2a9930$9d7fcb90$@gmail.com> <4FC42F58.2030303@alchemy.com> Message-ID: <20120529055121.GA23127@ando> On Mon, May 28, 2012 at 07:07:20PM -0700, Steve Willoughby wrote: > On 28-May-12 19:00, Jeremy Duenas wrote: > >and the both printed the same output??so why would I want to use > >?+? to > >add strings if there seems to be no reason too? > > Juxtaposing strings only works with constants, which may be convenient > in some cases, but it won't work at all when concatenating other string > values. > > a="hello" > b="world" > > a+b # will yield "helloworld" but > a b # is a syntax error > > Using + is arguably preferable when you have a choice to make, since it > works in all cases, including constants. I'll argue differently: even though + works with string literals as well as variables, you shouldn't use it. Python the language promises that implicit concatenation of literals will be performed at compile time. That is, if you write source code: print("hello " "world") # implicit concatenation any implementation of Python (such as PyPy, IronPython, Jython, etc.) must ensure that the literals "hello " and "world" are concatenated at compile-time into a single string "hello world", not at run-time. But the same is not the case for + concatenation: print("hello " + "world") # explicit concatenation which may be done either at compile-time, or at run-time, depending on the implementation and version of Python, or the presence of optimizations, or the phase of the moon for all we know. Now, normally this won't matter. The nanosecond or so that it takes to concatenate two short strings like that is trivial. Even if it happens at run-time, who will care? But the *intent* is more clear: implicit concatenation clearly states that these substrings belong together, in a way that + doesn't. (At least in my mind.) Furthermore, there are times where run-time concatentation of literals does add some small, but measurable, cost: for i in range(10000000): print("hello " + "world") do_something_useful(i) In this case, versions of Python that delay the concatenation to run-time will have to add the two substrings not once, but ten million times. Versions of Python that do it at compile time only need to add them together once. Of course, nobody sensible should be concatenating such small strings like that when they could just write "hello world" as a single string. Why would you bother? But this is a useful feature when you have longer strings: print("This is some longer string, where it is not appropriate to " "use a triple-quoted string because it adds linebreaks, but " "the string is too long to fit on a single line. In this case " "implicit string concatenation is the ideal solution to the " "problem. Don't forget to leave a space at the end of each " "line (or the beginning if you prefer).") In cases like this, the difference between a compile-time concatenation and run-time may be significant, especially inside a fast loop. -- Steven From steve at pearwood.info Tue May 29 08:06:57 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 May 2012 16:06:57 +1000 Subject: [Tutor] Concatenating Strings In-Reply-To: <20120529055121.GA23127@ando> References: <000001cd3d3e$df2a9930$9d7fcb90$@gmail.com> <4FC42F58.2030303@alchemy.com> <20120529055121.GA23127@ando> Message-ID: <20120529060657.GB23127@ando> On Tue, May 29, 2012 at 03:51:21PM +1000, Steven D'Aprano wrote: > > Using + is arguably preferable when you have a choice to make, since it > > works in all cases, including constants. > > I'll argue differently: even though + works with string literals as well > as variables, you shouldn't use it. Oops, that sentence is unclear -- what I meant is that you shouldn't use + to concatenate two string literals, not that you should never use it at all! When you have one or both are variables, you MUST use + rather than implicit concatenation. Sorry for any confusion. -- Steven From opher.lubzens at gmail.com Tue May 29 08:42:03 2012 From: opher.lubzens at gmail.com (Opher Lubzens) Date: Tue, 29 May 2012 09:42:03 +0300 Subject: [Tutor] Python 2.7 Static Version and Postgresql Message-ID: Hello to the list, I'm working on a python script that has to interact with a Postgresql database, and the only python version I can use is python 2.7-static. I have two questions: 1) Is there any way to add libraries to this version? 2)If not, what would you recommend as a method to work with the Postgresql API? Thanks, Opher Lubzens -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue May 29 12:25:27 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 29 May 2012 06:25:27 -0400 Subject: [Tutor] Python 2.7 Static Version and Postgresql In-Reply-To: References: Message-ID: On Tue, May 29, 2012 at 2:42 AM, Opher Lubzens wrote: > Hello to the list, I'm working on a python script that has to interact with > a Postgresql database, and the only python version I can use is python > 2.7-static. I have two questions: > > 1) Is there any way to add libraries to this version? > yes. maybe this will get you started: http://zetcode.com/db/postgresqlpythontutorial/ > 2)If not, what would you recommend as a method to work with the Postgresql > API? > > Thanks, > Opher Lubzens > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick From opher.lubzens at gmail.com Tue May 29 13:20:18 2012 From: opher.lubzens at gmail.com (Opher Lubzens) Date: Tue, 29 May 2012 14:20:18 +0300 Subject: [Tutor] Python 2.7 Static Version and Postgresql In-Reply-To: References: Message-ID: On Tue, May 29, 2012 at 1:25 PM, Joel Goldstick wrote: > On Tue, May 29, 2012 at 2:42 AM, Opher Lubzens > wrote: > > Hello to the list, I'm working on a python script that has to interact > with > > a Postgresql database, and the only python version I can use is python > > 2.7-static. I have two questions: > > > > 1) Is there any way to add libraries to this version? > > > > yes. > > maybe this will get you started: > http://zetcode.com/db/postgresqlpythontutorial/ > Unfortunately I'm using this in my work, and cannot rely on the psycopg2 extension being available in the server that the script will run on unless I can enter it into the python-static bundle as an in-built module: I'm aware of the extension and would love to be able to use it. I apologise for my question being unclear- English is not my first language. Thanks, Opher Lubzens -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue May 29 14:28:30 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 29 May 2012 08:28:30 -0400 Subject: [Tutor] Python 2.7 Static Version and Postgresql In-Reply-To: References: Message-ID: On Tue, May 29, 2012 at 7:20 AM, Opher Lubzens wrote: > > > On Tue, May 29, 2012 at 1:25 PM, Joel Goldstick > wrote: >> >> On Tue, May 29, 2012 at 2:42 AM, Opher Lubzens >> wrote: >> > Hello to the list, I'm working on a python script that has to interact >> > with >> > a Postgresql database, and the only python version I can use is python >> > 2.7-static. I have two questions: >> > >> > 1) Is there any way to add libraries to this version? >> > >> >> yes. >> >> maybe this will get you started: >> http://zetcode.com/db/postgresqlpythontutorial/ > > > Unfortunately I'm using this in my work, and cannot rely on the psycopg2 > extension being available in the server that the script will run on unless I > can enter it into the python-static bundle as an in-built module: I'm aware > of the extension and would love to be able to use it. I apologise for my > question being unclear- English is not my first language. > > Thanks, > Opher Lubzens I can't help with python static bundle. Its something I have never heard of. But have you heard about virtualenv? Its a application that lets you create local python environments -- so that downloading modules stay in a local environment and only run when you enter that space. I believe it temporarily changes some paths so that your local modules get loaded instead of looking in normal area where python keeps them. http://pypi.python.org/pypi/virtualenv -- Joel Goldstick From wprins at gmail.com Tue May 29 15:18:07 2012 From: wprins at gmail.com (Walter Prins) Date: Tue, 29 May 2012 14:18:07 +0100 Subject: [Tutor] Python 2.7 Static Version and Postgresql In-Reply-To: References: Message-ID: On 29 May 2012 12:20, Opher Lubzens wrote: >> Unfortunately I'm using this in my work, and cannot rely on the psycopg2 > extension being available in the server that the script will run on unless I > can enter it into the python-static bundle as an in-built module: I'm aware > of the extension and would love to be able to use it. I apologise for my > question being unclear- English is not my first language. What does this work machine run exactly? Why won't you be able to (for example) keep some libraries in your own home lib folder and update the library load path so that your own libraries can be used by your programs? Does this machine have gcc (or some C compiler installed)? Does it have any version of Python available at all? Anyway, if you've got enough freedom to install and run static python from your home account, then IMHO in theory you should have enough freedom to set up your own lib folder and probably ulimately even a complete _non-static_ Python environment in your home account. (+1 for Joel's virtualenv suggestion), though admittedly this may not be trivial by any means. Walter From opher.lubzens at gmail.com Tue May 29 15:40:20 2012 From: opher.lubzens at gmail.com (Opher Lubzens) Date: Tue, 29 May 2012 16:40:20 +0300 Subject: [Tutor] Python 2.7 Static Version and Postgresql In-Reply-To: References: Message-ID: On Tue, May 29, 2012 at 4:18 PM, Walter Prins wrote: > What does this work machine run exactly? ?Why won't you be able to > (for example) keep some libraries in your own home lib folder and > update the library load path so that your own libraries can be used by > your programs? ?Does this machine have gcc (or some C compiler > installed)? ?Does it have any version of Python available at all? > > Anyway, if you've got enough freedom to install and run static python > from your home account, then IMHO in theory you should have enough > freedom to set up your own lib folder and probably ulimately even a > complete _non-static_ Python environment in your home account. (+1 for > Joel's virtualenv suggestion), though admittedly this may not be > trivial by any means. This is supposed to be a QA tool to be run on virtual machines to make sure several of our features work correctly and do not degrade during development and version changes. Our machines are susually running a secure variant of the Linux bash shell, (the specific flavour is company- developed). Unfortunately this means that I cannot make sure there is any additional library, or other modification that is not included in a static bundle, on the machine- thus the need for either a built-in or the ability to rebundle the package so it includes them. Thanks, Opher Lubzens From wprins at gmail.com Tue May 29 17:26:52 2012 From: wprins at gmail.com (Walter Prins) Date: Tue, 29 May 2012 16:26:52 +0100 Subject: [Tutor] Python 2.7 Static Version and Postgresql In-Reply-To: References: Message-ID: Hi, On 29 May 2012 14:40, Opher Lubzens wrote: > This is supposed to be a QA tool to be run on virtual machines to make > sure several of our features work correctly and do not degrade during > development and version changes. OK... > Our machines are susually running a secure variant of the Linux bash > shell, (the specific flavour is company- developed). Unfortunately > this means that I cannot make sure there > is any additional library, or other modification that is not included > in a static bundle, on the machine- thus the need for either a > built-in or the ability to rebundle the package so > it includes them. I presume you can't develop on a VM which is less restrictive by any chance? How about setting up something similar to Movable Python or Portable Python on a disk (or disk file, or USB key, or ISO image or whatever, something that can be accessed by the VM's you want to test) that is less restrictive than static Python? As you can tell I'm resisting the static Python route as I expect that route will ultimately require you to rebuild static Python yourself with the needed Postgres modules/libraries included, and I suspect that path will likely be harder than setting up a distribution of Python that can be moved about easily and re-used on the VM's you're trying to test. Walter From opher.lubzens at gmail.com Tue May 29 20:26:53 2012 From: opher.lubzens at gmail.com (Opher Lubzens) Date: Tue, 29 May 2012 21:26:53 +0300 Subject: [Tutor] Python 2.7 Static Version and Postgresql In-Reply-To: References: Message-ID: On Tue, May 29, 2012 at 6:26 PM, Walter Prins wrote: > Hi, > > On 29 May 2012 14:40, Opher Lubzens wrote: > > I presume you can't develop on a VM which is less restrictive by any > chance? ?How about setting up something similar to Movable Python or > Portable Python on a disk (or disk file, or USB key, or ISO image or > whatever, something that can be accessed by the VM's you want to test) > that is less restrictive than static Python? ?As you can tell I'm > resisting the static Python route as I expect that route will > ultimately require you to rebuild static Python yourself with the > needed Postgres modules/libraries included, and I suspect that path > will likely be harder than setting up a distribution of Python that > can be moved about easily and re-used on the VM's you're trying to > test. > > Walter That actually might be workable- I'll have to look into it. I'll have to understand them better then I do after a brief look in their webpages and check whether they're compatible with our specific flavor of OS, since both of these are Windows oriented according to their pages, but this may be a good answer for what I need. Thank you for your help, Opher Lubzens From steve at pearwood.info Wed May 30 02:09:28 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 May 2012 10:09:28 +1000 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: <4FC25A88.10404@pearwood.info> References: <4FC25A88.10404@pearwood.info> Message-ID: <4FC56538.2030608@pearwood.info> Steven D'Aprano wrote: > location = '/Users/spyros/Desktop/3NY8MODELSHUMAN/HomologyModels/' > zdata = [] > for filename in os.listdir(location): > zdata.extend(get_zcoords(filename)) Hah, that can't work. listdir returns the name of the file, but not the file's path, which means that Python will only look in the current directory. You need something like this: location = '/Users/spyros/Desktop/3NY8MODELSHUMAN/HomologyModels/' zdata = [] for filename in os.listdir(location): zdata.extend(get_zcoords(os.path.join(location, filename))) Sorry about that. -- Steven From jdrishe at gmail.com Wed May 30 02:46:43 2012 From: jdrishe at gmail.com (Joseph Rishe) Date: Tue, 29 May 2012 20:46:43 -0400 Subject: [Tutor] Loop Question - Beginner Help (Thanks in Advance) Message-ID: #Operating System - Mac OS X 10.6.8 #Python Version - Python 2.6.6 ##Goal: I am creating a program to calculate credit card payments. ## The user should be able to put in a credit card balance and interest ## rate, and the program will tell them what monthly payment will allow ## them to pay off the card in 1 year. Note: it should only be ## increments of $10. ##Problem: The program returns incorrent values for some inputs. ## ie ($1200 balance and 18% interest returns a value of $120.01 ## for a monthly payment. Which is fine, but it only takes 11 ## months to pay off that card, not 12. ## So, I need to try different payment values and play out the final ## balance over 12 months. But it somehow needs to be dynamic enough ## to recognize that it will not take 12 months to pay off some values ## if we only allow multiples of $10. ## I thought of scabbing something on the end that will check negative ## balances and somehow revert to the previous month but there must be ## a cleaner way of doing this. # code follows: print "This will help you pay off your credit card in under 1 year." obalance = float(raw_input("What's your balance?")) #takes user input for balance yrate = float(raw_input("What's your interest rate?")) #takes user interest rate mrate = yrate / 12.0 #creates monthly rate cbalance = obalance #this will be experimental balance based on some monthly payment gbalance = 0.0 #this is our goal balance incrementpayment = 10.0 #initial monthly payment x = 1 #our intitial month count while cbalance > gbalance: # while our experimental balance is greater than our goal of 0: for i in range (1,x+12): ppayment = incrementpayment - (cbalance * mrate) #amount of payment going to principle cbalance = cbalance - ppayment #new experimental balance after payment is applied if cbalance > gbalance: cbalance = obalance incrementpayment = incrementpayment + 10.0 #resets experimental balance if monthly payment is not enough to reach zero balance else: print "RESULT" print "Months to pay off: ",i print "Monthly Payment: $",incrementpayment print "Ending Balance: $",cbalance -- Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: From thomasjo2 at wsdstudent.net Wed May 30 02:50:37 2012 From: thomasjo2 at wsdstudent.net (PhantomsCore) Date: Tue, 29 May 2012 17:50:37 -0700 (PDT) Subject: [Tutor] Break Help Message-ID: <1338339037852-4976225.post@n6.nabble.com> if gameIsDone: if playAgain(): missedLetters = '' correctLetters = '' gameIsDone = False secretWord = getRandomWord(words) else: break That is my coding. When I try to run it I get "Break outside loop" -- View this message in context: http://python.6.n6.nabble.com/Break-Help-tp4976225.html Sent from the Python - tutor mailing list archive at Nabble.com. From corey at octayn.net Wed May 30 03:08:12 2012 From: corey at octayn.net (Corey Richardson) Date: Tue, 29 May 2012 21:08:12 -0400 Subject: [Tutor] Break Help In-Reply-To: <1338339037852-4976225.post@n6.nabble.com> References: <1338339037852-4976225.post@n6.nabble.com> Message-ID: <20120529210812.652ee7db@Ulysses.myhome.westell.com> On Tue, 29 May 2012 17:50:37 -0700 (PDT) PhantomsCore wrote: > > if gameIsDone: > if playAgain(): > missedLetters = '' > correctLetters = '' > gameIsDone = False > secretWord = getRandomWord(words) > else: > break > > That is my coding. When I try to run it I get "Break outside loop" > Because (surprise!) you are using break outside of a loop. Break is only valid to break out of a for or while loop, and no where else. What do you want to do with that program? Quit if playAgain() returns false? Just leave out the else entirely, and if gameIsDone is False, it will continue outside of that block. From d at davea.name Wed May 30 03:44:14 2012 From: d at davea.name (Dave Angel) Date: Tue, 29 May 2012 21:44:14 -0400 Subject: [Tutor] Loop Question - Beginner Help (Thanks in Advance) In-Reply-To: References: Message-ID: <4FC57B6E.8000809@davea.name> On 05/29/2012 08:46 PM, Joseph Rishe wrote: > #Operating System - Mac OS X 10.6.8 > #Python Version - Python 2.6.6 > > > > ##Goal: I am creating a program to calculate credit card payments. > ## The user should be able to put in a credit card balance and > interest > ## rate, and the program will tell them what monthly payment will > allow > ## them to pay off the card in 1 year. Note: it should only be > ## increments of $10. > ##Problem: The program returns incorrent values for some inputs. > ## ie ($1200 balance and 18% interest returns a value of $120.01 > ## for a monthly payment. Which is fine, but it only takes 11 > ## months to pay off that card, not 12. > > ## So, I need to try different payment values and play out the > final > ## balance over 12 months. But it somehow needs to be dynamic > enough > ## to recognize that it will not take 12 months to pay off some > values > ## if we only allow multiples of $10. > > ## I thought of scabbing something on the end that will check > negative > ## balances and somehow revert to the previous month but there > must be > ## a cleaner way of doing this. > > # code follows: > > print "This will help you pay off your credit card in under 1 year." > > > obalance = float(raw_input("What's your balance?")) > #takes user input for balance > yrate = float(raw_input("What's your interest rate?")) > #takes user interest rate > mrate = yrate / 12.0 > #creates monthly rate > cbalance = obalance > #this will be experimental balance based on some monthly payment > gbalance = 0.0 > #this is our goal balance > incrementpayment = 10.0 > #initial monthly payment > x = 1 > #our intitial month count > > > while cbalance > gbalance: > # while our experimental balance is greater than our goal of 0: > for i in range (1,x+12): > ppayment = incrementpayment - (cbalance * mrate) > #amount of payment going to principle > cbalance = cbalance - ppayment > #new experimental balance after payment is applied > if cbalance > gbalance: > cbalance = obalance > incrementpayment = incrementpayment + 10.0 > #resets experimental balance if monthly payment is not enough to > reach zero balance > > else: > print "RESULT" > print "Months to pay off: ",i > print "Monthly Payment: $",incrementpayment > print "Ending Balance: $",cbalance > > If you don't mind me saying so, you're trying to write BASIC code in Python. if you want to solve this, decompose it into pieces that you can debug individually. Start by writing small functions that you're confident in, and the rest will fall into place. First function I'd write would take a given original principle, an interest rate, a number of months, and payment amount. It'd return the final balance. Then your other function is just a loop that calls that function with upwardly varying payment amounts till the final balance is negative. Incidentally, if your user types in interest rate as a percentage, you'll need to scale it by 100. If he enters 6, the mrate should be 0.005 -- DaveA From s.charonis at gmail.com Wed May 30 08:00:30 2012 From: s.charonis at gmail.com (Spyros Charonis) Date: Wed, 30 May 2012 07:00:30 +0100 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: <4FC56538.2030608@pearwood.info> References: <4FC25A88.10404@pearwood.info> <4FC56538.2030608@pearwood.info> Message-ID: FINAL SOLUTION: ### LOOP OVER DIRECTORY location = '/Users/spyros/Desktop/3NY8MODELSHUMAN/HomologyModels' zdata = [] for filename in os.listdir(location): filename = os.path.join(location, filename) try: zdata.extend(extract_zcoord(filename)) except NameError: print "No such file!" except SyntaxError: print "Check Your Syntax!" except IOError: print "PDB file NOT FOUND!" else: continue print 'Z-VALUES FOR ALL CHARGED RESIDUES' print zdata #diagnostic ### WRITE Z-COORDINATE LIST TO A BINARY FILE import pickle f1 = open("z_coords1.dat", "wb") pickle.dump(zdata, f1) f1.close() f2 = open("z_coords1.dat", "rb") zdata1 = pickle.load(f2) f2.close() assert zdata == zdata1, "error in pickle/unpickle round trip!" On Wed, May 30, 2012 at 1:09 AM, Steven D'Aprano wrote: > Steven D'Aprano wrote: > > location = '/Users/spyros/Desktop/**3NY8MODELSHUMAN/**HomologyModels/' >> zdata = [] >> for filename in os.listdir(location): >> zdata.extend(get_zcoords(**filename)) >> > I only had the filename and not its path, that's why the system was not able to locate the file, so filename = os.path.join(location, filename) was used to solve that. Many thanks to everyone for their time and efforts! Spyros > > > Hah, that can't work. listdir returns the name of the file, but not the > file's path, which means that Python will only look in the current > directory. You need something like this: > > > location = '/Users/spyros/Desktop/**3NY8MODELSHUMAN/**HomologyModels/' > zdata = [] > for filename in os.listdir(location): > zdata.extend(get_zcoords(os.**path.join(location, filename))) > > > Sorry about that. > > > > > -- > 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 May 30 09:16:16 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 May 2012 17:16:16 +1000 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: References: <4FC25A88.10404@pearwood.info> <4FC56538.2030608@pearwood.info> Message-ID: <20120530071616.GA27475@ando> On Wed, May 30, 2012 at 07:00:30AM +0100, Spyros Charonis wrote: > FINAL SOLUTION: Not quite. You are making the mistake of many newbies to treat Python exceptions as a problem to be covered up and hidden, instead of as a useful source of information. To quote Chris Smith: "I find it amusing when novice programmers believe their main job is preventing programs from crashing. ... More experienced programmers realize that correct code is great, code that crashes could use improvement, but incorrect code that doesn't crash is a horrible nightmare." -- http://cdsmith.wordpress.com/2011/01/09/an-old-article-i-wrote/ There is little as painful as a program which prints "An error occurred" and then *keeps working*. What does this mean? Can I trust that the program's final result is correct? How can it be correct if an error occurred? What error occurred? How do I fix it? Exceptions are your friend, not your enemy. An exception tells you that there is a problem with your program that needs to be fixed. Don't cover-up exceptions unless you absolutely have to. Sadly, your indentation is still being broken when you post. Please ensure you include indentation, and disable HTML or "Rich Text" posting. I have tried to guess the correct indentation below, and fix it in place, but apologies if I get it wrong. > ### LOOP OVER DIRECTORY > location = '/Users/spyros/Desktop/3NY8MODELSHUMAN/HomologyModels' > zdata = [] > for filename in os.listdir(location): > filename = os.path.join(location, filename) > try: > zdata.extend(extract_zcoord(filename)) > except NameError: > print "No such file!" Incorrect. When a file is missing, you do not get NameError. This except-clause merely disguises programming errors in favour of a misleading and incorrect error message. If you get a NameError, your program has a bug. Don't just hide the bug, fix it. > except SyntaxError: > print "Check Your Syntax!" This except-clause is even more useless. SyntaxErrors happen when the code is compiled, not run, so by the time the for-loop is entered, the code has already been compiled and cannot possibly raise SyntaxError. Even if it could, what is the point of this? Instead of a useful exception traceback, which tells you not only which line contains the error, but even highlights the point of the error with a ^ caret, you hide all the useful information and tease the user with a useless message "Check Your Syntax!". Again, if your program raises a SyntaxError, it has a bug. Don't hide the bug, fix it. > except IOError: > print "PDB file NOT FOUND!" This, at least, is somewhat less useless than the others. At least it is a valid exception, and if your intention is to skip missing files, catching IOError is a reasonable way to do it. But you don't just get IOError for *missing* files, but also for *unreadable* files, perhaps because you don't have permission to read them, or perhaps because the file is corrupt and can't be read. In any case, as usual, imagine yourself as the recipient of this message: "PDB file NOT FOUND!" -- what do you expect to do about it? Which file is missing or unreadable? How can you tell? Is this a problem? Are your results still valid without that PDB file's data? If this can be be ignored, IGNORE IT! Don't bother the user with scary messages that a problem occurred, if it isn't a problem! At *most*, print a notice that you have skipped a file: print "Skipping file", filename (perhaps giving the reason for skipping it). Or even just ignore it completely: pass > else: > continue This is pointless. All it does is what would have been done anyway: if no exception occurs, it continues to the next loop. Get rid of it: your code will be shorter and neater without this unnecessary two lines. -- Steven From s.charonis at gmail.com Wed May 30 10:37:52 2012 From: s.charonis at gmail.com (Spyros Charonis) Date: Wed, 30 May 2012 09:37:52 +0100 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: <20120530071616.GA27475@ando> References: <4FC25A88.10404@pearwood.info> <4FC56538.2030608@pearwood.info> <20120530071616.GA27475@ando> Message-ID: On Wed, May 30, 2012 at 8:16 AM, Steven D'Aprano wrote: > On Wed, May 30, 2012 at 07:00:30AM +0100, Spyros Charonis wrote: > > FINAL SOLUTION: > > Not quite. You are making the mistake of many newbies to treat Python > exceptions as a problem to be covered up and hidden, instead of as a > useful source of information. > > To quote Chris Smith: > > "I find it amusing when novice programmers believe their main > job is preventing programs from crashing. ... More experienced > programmers realize that correct code is great, code that > crashes could use improvement, but incorrect code that doesn't > crash is a horrible nightmare." > -- http://cdsmith.wordpress.com/2011/01/09/an-old-article-i-wrote/ > Ok, so basically wrong code beats useless code. > > There is little as painful as a program which prints "An error occurred" > and then *keeps working*. What does this mean? Can I trust that the > program's final result is correct? How can it be correct if an error > occurred? What error occurred? How do I fix it? > My understanding is that an except clause will catch a relevant error and raise an exception if there is one, discontinuing program execution. > > Exceptions are your friend, not your enemy. An exception tells you that > there is a problem with your program that needs to be fixed. Don't > cover-up exceptions unless you absolutely have to. > Sadly, your indentation is still being broken when you post. Please > ensure you include indentation, and disable HTML or "Rich Text" posting. > I have tried to guess the correct indentation below, and fix it in > place, but apologies if I get it wrong. > Yes, that is the way my code looks in a python interpreter > > > > ### LOOP OVER DIRECTORY > > location = '/Users/spyros/Desktop/3NY8MODELSHUMAN/HomologyModels' > > zdata = [] > > for filename in os.listdir(location): > > filename = os.path.join(location, filename) > > try: > > zdata.extend(extract_zcoord(filename)) > > except NameError: > > print "No such file!" > > Incorrect. When a file is missing, you do not get NameError. This > except-clause merely disguises programming errors in favour of a > misleading and incorrect error message. > > If you get a NameError, your program has a bug. Don't just hide the bug, > fix it. > > > > except SyntaxError: > > print "Check Your Syntax!" > > This except-clause is even more useless. SyntaxErrors happen when the > code is compiled, not run, so by the time the for-loop is entered, the > code has already been compiled and cannot possibly raise SyntaxError. > What I meant was, check the syntax of my pathname specification, i.e. check that I did not make a type when writing the path of the directory I want to scan over. I realize syntax has a much more specific meaning in the context of programming - code syntax! > > Even if it could, what is the point of this? Instead of a useful > exception traceback, which tells you not only which line contains the > error, but even highlights the point of the error with a ^ caret, you > hide all the useful information and tease the user with a useless > message "Check Your Syntax!". > Ok, I didn't realize I was being so reckless - thanks for pointing that out. > > Again, if your program raises a SyntaxError, it has a bug. Don't hide > the bug, fix it. > > > > except IOError: > > print "PDB file NOT FOUND!" > > This, at least, is somewhat less useless than the others. At least it is > a valid exception, and if your intention is to skip missing files, > catching IOError is a reasonable way to do it. > > But you don't just get IOError for *missing* files, but also for > *unreadable* files, perhaps because you don't have permission to read > them, or perhaps because the file is corrupt and can't be read. > Understood, but given that I am reading and processing are standard ASCII text files, there is no good reason (which I can think of) that the files would be *unreadable* I verified that I had read/write permissions for all my files, which are the default access privileges anyway (for the owner). > > In any case, as usual, imagine yourself as the recipient of this > message: "PDB file NOT FOUND!" -- what do you expect to do about it? > Which file is missing or unreadable? How can you tell? Is this a > problem? Are your results still valid without that PDB file's data? > Perhaps because I was writing the program I didn't think that this message would be confusing to others, but it did help in making clear that there was a different error (in this case, the absence of **filename = os.path.join(location, filename)** to join a filename to its pathway). Without the PDB file's data, there would be no results - because the program operates on each file of a directory successively (all files are .pdb files) and uses data in the file to build a list. So, since I was working on a directory with only PDB files this error says it hasn't found them - which points to a more basic error (the one mentioned above). > > If this can be be ignored, IGNORE IT! Don't bother the user with scary > messages that a problem occurred, if it isn't a problem! At *most*, > print a notice that you have skipped a file: > > print "Skipping file", filename > > (perhaps giving the reason for skipping it). Or even just ignore it > completely: > > pass > > > > else: > > continue > > This is pointless. All it does is what would have been done anyway: if > no exception occurs, it continues to the next loop. Get rid of it: your > code will be shorter and neater without this unnecessary two lines. > Yes, I see what you mean. Thank you for all the corrections! > > > > -- > 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 akeriatimothy at gmail.com Wed May 30 18:21:42 2012 From: akeriatimothy at gmail.com (Akeria Timothy) Date: Wed, 30 May 2012 12:21:42 -0400 Subject: [Tutor] Joining all strings in stringList into one string Message-ID: Hello all, I am working on learning Python(on my own) and ran into an exercise that I figured out but I wanted to know if there was a different way to write the code? I know he wanted a different answer for the body because we haven't gotten to the ' '.join() command yet. This is what I have: def joinStrings(stringList): string = [] for string in stringList: print ''.join(stringList) def main(): print joinStrings(['very', 'hot', 'day']) print joinStrings(['this', 'is', 'it']) print joinStrings(['1', '2', '3', '4', '5']) main() thanks all -------------- next part -------------- An HTML attachment was scrubbed... URL: From glenbot at gmail.com Wed May 30 18:25:21 2012 From: glenbot at gmail.com (Glen Zangirolami) Date: Wed, 30 May 2012 11:25:21 -0500 Subject: [Tutor] Joining all strings in stringList into one string In-Reply-To: References: Message-ID: Seems like a lot of extra work for joining the strings. You should only need: ''.join(['very', 'hot', 'day']) (no spaces) ' '.join(['very', 'hot', 'day']) (if you want spaces) glen On Wed, May 30, 2012 at 11:21 AM, Akeria Timothy wrote: > Hello all, > > I am working on learning Python(on my own) and ran into an exercise that I > figured out but I wanted to know if there was a different way to write the > code? I know he wanted a different answer for the body because we haven't > gotten to the ' '.join() command yet. > > This is what I have: > > def joinStrings(stringList): > string = [] > for string in stringList: > print ''.join(stringList) > > > def main(): > print joinStrings(['very', 'hot', 'day']) > print joinStrings(['this', 'is', 'it']) > print joinStrings(['1', '2', '3', '4', '5']) > > main() > > > thanks all > > _______________________________________________ > 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 d at davea.name Wed May 30 19:03:44 2012 From: d at davea.name (Dave Angel) Date: Wed, 30 May 2012 13:03:44 -0400 Subject: [Tutor] Joining all strings in stringList into one string In-Reply-To: References: Message-ID: <4FC652F0.3010909@davea.name> On 05/30/2012 12:21 PM, Akeria Timothy wrote: > Hello all, > > I am working on learning Python(on my own) and ran into an exercise that I > figured out but I wanted to know if there was a different way to write the > code? I know he wanted a different answer for the body because we haven't > gotten to the ' '.join() command yet. > > This is what I have: > > def joinStrings(stringList): > string = [] > for string in stringList: > print ''.join(stringList) > > > def main(): > print joinStrings(['very', 'hot', 'day']) > print joinStrings(['this', 'is', 'it']) > print joinStrings(['1', '2', '3', '4', '5']) > > main() > > > thanks all > > I'm not sure what you want us to do here. You don't quote the "exercise" description, so about all I can do is point out the bugs and inefficiencies in the code. Your indentation won't work. You have string = indented by one column, and the for loop indented by 3 more. Those two lines have to start in the same column. Of course, if you had run it that way, the compiler would have told you that. So presumably you've retyped it into this message, which is very bad practice. Use copy/paste. File "timothy.py", line 3 for string in stringList: ^ IndentationError: unexpected indent Fixing that. Next problem is that main() uses the results of joinStrings(), but there is no return statement in joinStrings(). So it prints None. Presumably you meant to have joinStrings() return its result, INSTEAD of printing it. Next, in joinStrings(), you start by initializing string=. But then you immediately overwrite that value with the for loop, so it was wasted. Presumably you wanted to use two different names there, and do something to the first variable each time through the loop. Next, in the loop, you do the same work multiple times, never using the individual value of string. So, please tell us the actual assignment, and we can help you get there. There is certainly a way to have joinStrings() do the equivalent of "".join(), but it wouldn't look much like what you've written. Usually, the practice of making a docstring for each function can help you get the purpose straight in your mind. What does the function expect as argument(s), and what will it do, and what will it return? And what side effects does it have, like printing ? Usually, a function either does some work, or it displays some results. Doing both is a sign of a program that's still being debugged. -- DaveA From bgailer at gmail.com Wed May 30 19:42:19 2012 From: bgailer at gmail.com (bob gailer) Date: Wed, 30 May 2012 13:42:19 -0400 Subject: [Tutor] Joining all strings in stringList into one string In-Reply-To: References: Message-ID: <4FC65BFB.2010206@gmail.com> On 5/30/2012 12:21 PM, Akeria Timothy wrote: In addition to the other comments I point out that join is not a /command/, it is a /string method/. Python does not have commands. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From russel at winder.org.uk Wed May 30 19:36:52 2012 From: russel at winder.org.uk (Russel Winder) Date: Wed, 30 May 2012 18:36:52 +0100 Subject: [Tutor] Joining all strings in stringList into one string In-Reply-To: References: Message-ID: <1338399412.9761.4.camel@launcelot.winder.org.uk> On Wed, 2012-05-30 at 12:21 -0400, Akeria Timothy wrote: [...] > def joinStrings(stringList): > string = [] indentation error in that the above line and the below line should have the same indent level. Also the above line and the following line are both definitions of the variable string so the above is actually redundant. > for string in stringList: > print ''.join(stringList) Given the variable doesn't appear in the block I wonder if the code reflects the intended algorithm? > > def main(): > print joinStrings(['very', 'hot', 'day']) > print joinStrings(['this', 'is', 'it']) > print joinStrings(['1', '2', '3', '4', '5']) > > main() The above code, with the trivial indent fix, outputs: veryhotday veryhotday veryhotday None thisisit thisisit thisisit None 12345 12345 12345 12345 12345 None Is this what was desired? I am tempted to think that actually what was desired was: veryhotday thisisit 12345 in which case I would suggest the code should perhaps read: def main(): print ''.join(['very', 'hot', 'day']) print ''.join(['this', 'is', 'it']) print ''.join(['1', '2', '3', '4', '5']) if __name__ == '__main__': main() but, mayhap, I am missing the intention. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From d at davea.name Wed May 30 21:43:58 2012 From: d at davea.name (Dave Angel) Date: Wed, 30 May 2012 15:43:58 -0400 Subject: [Tutor] Joining all strings in stringList into one string In-Reply-To: References: <4FC652F0.3010909@davea.name> Message-ID: <4FC6787E.3090405@davea.name> A procedural point here: You forgot to include the list, and just replied to me privately. Normally, what you should do is a Reply-All. Or else make sure tutor at python.org is one of the To: or CC: list On 05/30/2012 01:40 PM, Akeria Timothy wrote: > I did copy and paste and I'm learning Python on my own using Hands-on Pyton > Tutorial and this was one of the exercises. He gave us the everything but > the body. So this is what I started out with: > > def joinStrings(stringList): > '''Join all the strings in stringList into one string, > and return the result. For example: > >>> print joinStrings(['very', 'hot', 'day']) > 'veryhotday' > ''' > # finish the code for this function Very good. Why did you remove that docstring from your own code before posting it? > > > def main(): > print joinStrings(['very', 'hot', 'day']) > print joinStrings(['this', 'is', 'it']) > print joinStrings(['1', '2', '3', '4', '5']) > > main() > > > > I know it's wrong but it worked so that's why I'm asking for the proper way > to do it. The output I got from your code (after fixing the indent) was davea at think:~/temppython$ python timothy.py veryhotday veryhotday veryhotday None thisisit thisisit thisisit None 12345 12345 12345 12345 12345 None and what I think the instructor expected was: veryhotday thisisit 12345 Similar, but not the same. First, the function is NOT supposed to print anything. According to the docstring, the function returns the result, not prints it. So you could come up with: def joinStrings(stringList): '''Join all the strings in stringList into one string, and return the result. For example: >>> print joinStrings(['very', 'hot', 'day']) 'veryhotday' ''' # finish the code for this function return "".join(stringList) But as you said in your original message, he presumably hasn't introduced that join method yet, so you would like to do it by hand. Very good way to learn. You had the right concept, of having an 'accumulator" to gather the parts of the result together. However, you are not trying to return a list, you're trying to return a string. So the accumulator must be an empty string. I'll give it a different name, so it doesn't conflict with the loop variable. res = "" for string in stringList: something here that modifies res return res Your challenge is now to supply the line in the middle. -- DaveA From steve at pearwood.info Thu May 31 03:41:19 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 31 May 2012 11:41:19 +1000 Subject: [Tutor] Parsing data from a set of files iteratively In-Reply-To: References: <4FC25A88.10404@pearwood.info> <4FC56538.2030608@pearwood.info> <20120530071616.GA27475@ando> Message-ID: <4FC6CC3F.7030409@pearwood.info> Spyros Charonis wrote: > On Wed, May 30, 2012 at 8:16 AM, Steven D'Aprano wrote: [...] >> There is little as painful as a program which prints "An error occurred" >> and then *keeps working*. What does this mean? Can I trust that the >> program's final result is correct? How can it be correct if an error >> occurred? What error occurred? How do I fix it? >> > My understanding is that an except clause will catch a relevant error and > raise an exception if there is one, discontinuing program execution. No, the opposite. An except clause will catch the exception and *continue* execution past the end of the try...except block. Python automatically raises exceptions and halts execution if you do nothing. For example: py> for x in (1, 0, 2): ... print(1/x) ... 1.0 Traceback (most recent call last): File "", line 2, in ZeroDivisionError: division by zero Notice that the first time around the loop, 1.0 is printed. The second time, an error occurs (1/0 is not defined), so Python raises an exception. Because I don't catch that exception, it halts execution of the loop and prints the traceback. But a try...except clause will catch the exception and keep going: py> for x in (1, 0, 2): ... try: ... print(1/x) ... except ZeroDivisionError: ... print('something bad happened') ... 1.0 something bad happened 0.5 There are good reasons for catching exceptions. Sometimes you can recover from the error, or skip the bad data. Sometimes one calculation fails but you can try another one. Or you might want to catch an exception of one type, and replace it with a different exception with a more appropriate error message. But all too often, I see beginners catching exceptions and just covering them up, or replacing useful tracebacks which help with debugging with bland and useless generic error messages like "An error occurred". >>> except SyntaxError: >>> print "Check Your Syntax!" >> This except-clause is even more useless. SyntaxErrors happen when the >> code is compiled, not run, so by the time the for-loop is entered, the >> code has already been compiled and cannot possibly raise SyntaxError. >> > What I meant was, check the syntax of my pathname specification, i.e. check > that I > did not make a type when writing the path of the directory I want to scan > over. I realize > syntax has a much more specific meaning in the context of programming - > code syntax! That's not what SyntaxError does in Python. Python only understands one form of syntax: *Python* syntax, not the syntax of pathnames to files. If you type the wrong pathname: pathname = "My Documents!letters!personal!letter to my mother+doc" Python will not raise SyntaxError. It will try to open the file called My Documents!letters!personal!letter to my mother+doc *exactly* as you typed it, and either succeed (if by some unimaginable fluke there happens to be a file of that name!) or fail. If it fails, you will get an OSError or IOError, depending on the nature of the failure reported by the operating system. [...] >> But you don't just get IOError for *missing* files, but also for >> *unreadable* files, perhaps because you don't have permission to read >> them, or perhaps because the file is corrupt and can't be read. >> > Understood, but given that I am reading and processing are standard ASCII > text files, > there is no good reason (which I can think of) that the files would be > *unreadable* *Any* file can be unreadable. The disk may develop a fault, and no longer be able to read the file's data blocks. Or the file system may be corrupted and the operating system can see that the file is there, but not where it is. If the file is on a network share, the network may have gone down halfway through reading the file. If it's on a USB stick or external hard drive, somebody might have unplugged it, or the connector might be wobbly. Normally, for a script like this, failure to read a file should be considered a fatal error. If a file which *should* be there is no longer there, you should report the problem and halt. I recommend that you don't catch the exception at all, just let the traceback occur as normal. > I verified that I had read/write permissions for all my files, which are > the default access privileges anyway (for the owner). Fine, but I'm talking in general rather than specific for you. In general, "file not found" is not the only error you can get. There is a remarkably large number of things that can go wrong when reading files, fortunately most of them are very rare. Consider what your code does. First, you ask the operating system for a list of the files in a directory, using os.listdir. Then you expect that some of those files might be missing, and try to catch the exception. Is this reasonable? Do you actually expect the operating system will lie to you and say that files are there that actually don't exist? For a robust application that runs in an environment where it is possible that files will routinely be created or destroyed at the same time that the application is running, a more careful and paranoid approach is appropriate. For a short script that you control, perhaps not so much. -- Steven From zsoltturi at gmail.com Thu May 31 16:43:53 2012 From: zsoltturi at gmail.com (Zsolt Turi) Date: Thu, 31 May 2012 16:43:53 +0200 Subject: [Tutor] separately updating parameters Message-ID: Dear Pythonists, I'm using Python 2.7. on Win 7. Problem description: Currently, I am working on a reinforcement learning paradigm, where I would like to update Qa values with alfaG [if decision_input = 1 and feedback_input = 1] or with alfaL [ if decision_input = 1 and feedback_value = 0]. (1) So, I have two lists for input (with two values) : decision_input = [1,1] - this could be 1,2,3,4,5,6 feedback_input = [1,0] - the value is either 1 or zero (2) The equation is the following for gain: Qa = Qa+(alfaG*(feedback_input-Qa)) thus, I would like to use alfaG only if the i-th element of feedback_input is 1 for lose: Qa = Qa+(alfaL*(feedback_input-Qa)) thus, only if the i-th element of feedback_input is zero Qa value is initialized to zero. (3) Incrementing alfaG and alfaL independently after updating the Qa value alfaG = 0.01 - initial value alfaL = 0.01 - initial value (4) The problematic code :( decision_input = [1,1] feedback_input = [1,0] a = [] alfaG = 0.01 alfaL = 0.01 value = 0.04 for i in range(len(decision_input)): if decision_input[i] == 1 and feedback_input[i] == 1: while alfaG < value: Qa = 0 for feedb in feedback_input: Qa = Qa+(alfaG*(feedb-Qa)) a.append(Qa) if decision_input[i] == 1 and feedback_input[i] == 0: while alfaL < value: for feedb in feedback_input: Qa = Qa+(alfaL*(feedb-Qa)) a.append(Qa) alfaL += 0.01 alfaG += 0.01 print a after this, I've got the following output: [0.01, 0.099], [0.02, 0.0196], [0.03, 0.0291] (5) I have no idea, how to get the following output: [0.01, 0.099], [0.01, 0.098], [0.01, 0.097] -->thus: alfaG = 0.01, alfaL = 0.01, 0.02, 0.03 [0.02, 0.0198], [0.02, 0.0196], [0.02, 0.0194] -->thus: alfaG = 0.02, alfaL = 0.01, 0.02, 0.03 [0.03, 0.0297], [0.03, 0.0294], [0.03, 0.0291] -->thus: alfaG = 0.03, alfaL = 0.01, 0.02, 0.03 Since both alfaG and alfaL have 3 values, I have 3x3 lists. Does anyone have an idea, how to modify the code? Best regards, Zsolt -------------- next part -------------- An HTML attachment was scrubbed... URL: From emeraldoffice at hotmail.com Thu May 31 18:20:28 2012 From: emeraldoffice at hotmail.com (Tamar Osher) Date: Thu, 31 May 2012 11:20:28 -0500 Subject: [Tutor] How install Pyramid on a Windows 7 computer? Message-ID: Months ago, I learned Python version 3. I have read a few books, and want to learn how to use Python for the web. Pyramid is a Python web framework that is ready for Python version 3, but I don't know how to install it on my Windows 7 computer. Online, there are no Pyramid installation instructions that discuss how to install Pyramid on a Windows 7 computer. Can someone please help me? from Tamar Osher, EmeraldOffice at hotmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From vince at vinces.ca Thu May 31 18:31:50 2012 From: vince at vinces.ca (Vince Spicer) Date: Thu, 31 May 2012 10:31:50 -0600 Subject: [Tutor] How install Pyramid on a Windows 7 computer? In-Reply-To: References: Message-ID: Step 1) install Ubuntu OK sorry couldn't resist. This should help. http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/install.html#installing-pyramid-on-a-windows-system Vince On Thu, May 31, 2012 at 10:20 AM, Tamar Osher wrote: > Months ago, I learned Python version 3. I have read a few books, and > want to learn how to use Python for the web. Pyramid is a Python web > framework that is ready for Python version 3, but I don't know how to > install it on my Windows 7 computer. Online, there are no Pyramid > installation instructions that discuss how to install Pyramid on a Windows > 7 computer. Can someone please help me? > > from Tamar Osher, EmeraldOffice at hotmail.com > > > ** > * > > > > * > > * * > > > _______________________________________________ > 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 eire1130 at gmail.com Thu May 31 18:56:28 2012 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 31 May 2012 12:56:28 -0400 Subject: [Tutor] How install Pyramid on a Windows 7 computer? In-Reply-To: References: Message-ID: I don't think django 1.5 is ready, but they are targeting python3k. There is a fork of django i think on bitbucket that works as well. On May 31, 2012 12:33 PM, "Vince Spicer" wrote: > Step 1) install Ubuntu > > OK sorry couldn't resist. > > This should help. > > http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/install.html#installing-pyramid-on-a-windows-system > > Vince > > On Thu, May 31, 2012 at 10:20 AM, Tamar Osher wrote: > >> Months ago, I learned Python version 3. I have read a few books, and >> want to learn how to use Python for the web. Pyramid is a Python web >> framework that is ready for Python version 3, but I don't know how to >> install it on my Windows 7 computer. Online, there are no Pyramid >> installation instructions that discuss how to install Pyramid on a Windows >> 7 computer. Can someone please help me? >> >> from Tamar Osher, EmeraldOffice at hotmail.com >> >> >> ** >> * >> >> >> >> * >> >> * * >> >> >> _______________________________________________ >> 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: